1

你需要在 Operation 类的 main() 方法中使用 URLSession 的 dataTask(with: URL) 吗?例如:

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()
    }
}

如果上述操作无论如何都要在后台操作队列上运行,那么在 main() 方法中使用 dataTask(with:url) 是不是有点矫枉过正?在关于操作的 Ray Wenderlich 教程中,他们指定下载数据,如下所示(参见 #5):

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")
    }
  }
}

但在苹果文档中,它指定从不Data(contentsOf: url)用于下载数据:

在此处输入图像描述

从操作中下载数据的安全方法是否Data(contentsOf: url)会在操作队列上异步运行(并且肯定不会在一次性块中调用)?

4

0 回答 0