根据另一个结果创建一个URLSession

提格兰·伊斯坎达良

我有一个URLSession被解雇的人viewDidLoad它返回包含图像URL的JSON。因此,要获取该图像,我需要URLSession从JSON Decoder的完成块中调用另一个权限,而JSON Decoder的完成块将从first的完成块中调用URLSession这是该代码:

 //THIS IS CALLED FROM viewDidLoad()

 let task = urlSession.dataTask(with: url!) { (data, response, error) in
        guard error == nil else {
            print ("Error while fetching collections: \(String(describing: error))")
            return
        }

        if let data = data, let string = String(data: data, encoding: .utf8) {
            print (string)
            URL_Request_Handler.parsingJSON(fromData: data, completion: {(result) in
                if let result = result {
                    print ("JSON IS CONVERTED")
                    print (result)

                    //This method creates another session and fires it

                    self.getFinalCollectionFromResult(result)
                }
            })
        }
    }

    task.resume()

这是getFinalCollectionFromResult方法:

  private func getFinalCollectionFromResult(_ result: Result_Collection) {
    let task = URLSession.shared.dataTask(with: URL(string:result.cover_photo.url)!, completionHandler: { (data, response, error) in
        if error != nil {
            print("Errror")
        }
        if let data = data, let image = UIImage(data: data) {

            DispatchQueue.main.async {
                self.collection = Collection(title: result.title, image: image)
                self.collectionViewLayout.collectionView?.reloadData()
            }
        }
    })
    task.resume()
}

是否可以从第一个会话的完成块开始创建另一个会话?

尼玛·尤塞菲(Nima Yousefi)

是的,这很好。

但有一个建议:您应该为映像使用downloadTask而不是dataTask。苹果表示,dataTask是为处理少量数据而设计的,而不是像从图像中获取大量数据那样,如果要在以后添加该功能,downloadTask将使您能够暂停/恢复下载。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章