Skip to content

Instantly share code, notes, and snippets.

@wszdwp
Last active June 28, 2019 16:06
Show Gist options
  • Save wszdwp/18ba8e51043f6df2f4b0435a14000be7 to your computer and use it in GitHub Desktop.
Save wszdwp/18ba8e51043f6df2f4b0435a14000be7 to your computer and use it in GitHub Desktop.
Swift gist
// multithread
// 1. GCD
DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async {
var data:Data?
if let imageURL = URL(string: imageURLStr) {
data = try? Data(contentsOf: imageURL)
}
DispatchQueue.main.async(execute: {
if data == nil {
cell.itemImage.setImage(UIImage(named: "NoImageFound.png"), for: UIControlState())
} else {
cell.itemImage.setImage(UIImage(data:data!), for: UIControlState())
}
})
}
// 2. URLSession.shared.dataTask
// No need to provide background queue when use this. DispatchQueue.main is used since completion block run on background
// explaninations: [SO post](https://stackoverflow.com/questions/31746229/does-nsurlsession-for-http-data-task-nsurlsessiondatatask-runs-in-background-t)
URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in
DispatchQueue.main.async(execute: {
})
}.resume()
// 3. NSURLConnection.sendAsynchronousRequest
// Need to provoide a operationQueue when doing this
let queue:OperationQueue = OperationQueue()
NSURLConnection.sendAsynchronousRequest(request as URLRequest, queue: queue, completionHandler:{(response: URLResponse?, data: Data?, error: Error?) -> Void in
DispatchQueue.main.async(execute: {
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment