Swift 您是否需要使用URLSession';在操作类';什么是main()方法?
是否需要在操作类的main()方法中使用URLSession的dataTask(with:URL)? 例如:Swift 您是否需要使用URLSession';在操作类';什么是main()方法?,swift,nsoperation,urlsession,nsurlsessiondatatask,initwithcontentsofurl,Swift,Nsoperation,Urlsession,Nsurlsessiondatatask,Initwithcontentsofurl,是否需要在操作类的main()方法中使用URLSession的dataTask(with:URL)? 例如: class Downloader: Operation { let postDetailsPage: PostDetailsPage init(_ postDetailsPage: PostDetailsPage) { self.postDetailsPage = postDetailsPage } override func mai
class Downloader: Operation {
let postDetailsPage: PostDetailsPage
init(_ postDetailsPage: PostDetailsPage) {
self.postDetailsPage = postDetailsPage
}
override func main() {
if isCancelled {
return
}
let url = URL(string: "https://someurl.json")!
NetworkingClient.shared.urlSession.dataTask(with: url) { (jsonData, response, error) in
// work with jsondata
}.resume()
}
}
如果上面的操作要在后台operationqueue上运行,那么在main()方法中使用dataTask(with:url)不是太过了吗?在中,它们指定了下载数据,如下所示(请参见#5):
但在中,它指定从不使用数据(contentsOf:url)
下载数据:
Data(contentsOf:url)
是从操作中下载数据的安全方法吗?该操作无论如何都将在operationqueue上异步运行(并且肯定不会在一次性块中调用)?您需要异步操作才能使用操作进行网络连接您需要异步操作才能使用操作进行网络连接
class ImageDownloader: Operation {
//1
let photoRecord: PhotoRecord
//2
init(_ photoRecord: PhotoRecord) {
self.photoRecord = photoRecord
}
//3
override func main() {
//4
if isCancelled {
return
}
//5
guard let imageData = try? Data(contentsOf: photoRecord.url) else { return }
//6
if isCancelled {
return
}
//7
if !imageData.isEmpty {
photoRecord.image = UIImage(data:imageData)
photoRecord.state = .downloaded
} else {
photoRecord.state = .failed
photoRecord.image = UIImage(named: "Failed")
}
}
}