Created
September 7, 2019 02:09
-
-
Save DineshKachhot/9a5cd95a971ec24f65d4c7e00ad92475 to your computer and use it in GitHub Desktop.
NSURLSession GET Request - Swift 4.2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct ImageResponse: Codable { | |
var message:String | |
var totalRecord:Int | |
var totalPage:Int | |
var nextPage:String | |
var images:[Image] | |
enum CodingKeys: String, CodingKey { | |
case message | |
case totalRecord | |
case totalPage | |
case nextPage | |
case images = "data" | |
} | |
} | |
struct Image: Codable { | |
var imageId: Int | |
var title:String | |
var imageUrl: String | |
enum CodingKeys: String, CodingKey { | |
case imageId = "iImageId" | |
case title = "vTitle" | |
case imageUrl = "txImageUrl" | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
guard let urlEncodedString = (AppConstants.URL.imageDownload + "?image_id=\(imageIdCalculated)").addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else { | |
return | |
} | |
let url = URL(string: urlEncodedString)! | |
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in | |
if let er = error { | |
print(er) | |
Utils.showAlertController(with: er.localizedDescription, viewController: self) | |
return | |
} | |
guard let unwrappedData = data else { return } | |
do { | |
let imageResponse = try JSONDecoder().decode(ImageResponse.self, from: unwrappedData) | |
if imageResponse.images.count == 0 { | |
Utils.showAlertController(with: imageResponse.message, viewController: self) | |
return | |
} | |
DispatchQueue.main.async { | |
// Call UI update in main thread | |
} | |
} catch { | |
print("json error: \(error)") | |
} | |
} | |
task.resume() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment