Skip to content

Instantly share code, notes, and snippets.

@DineshKachhot
Created September 7, 2019 02:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DineshKachhot/9a5cd95a971ec24f65d4c7e00ad92475 to your computer and use it in GitHub Desktop.
Save DineshKachhot/9a5cd95a971ec24f65d4c7e00ad92475 to your computer and use it in GitHub Desktop.
NSURLSession GET Request - Swift 4.2
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"
}
}
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