如何下载图像以填充我的collectionviewcell JSON?

时间:2017-11-20 17:41:25

标签: ios swift grand-central-dispatch

//Parsing JSON Oké
    let parsedData : [String:AnyObject]
    do{
        parsedData = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:AnyObject]
        guard let results = parsedData["results"] as? [[String:AnyObject]] else {
            print("There is a problem related to results fetch"); return }
        for res in results {

            var dataMi : Data!
            //For the image data
            let urlOfthePic = URL(string: "https://image.tmdb.org/t/p/w92\(res["backdrop_path"]!)")
            let downLoadPicTask = URLSession.shared.dataTask(with: urlOfthePic!, completionHandler: { (data, res, err) in
                guard let data = data else {print("second"); return}
                dataMi = data
                self.mov.movImage = UIImage(data: dataMi)!
                print(dataMi)
            });downLoadPicTask.resume()
            print("2:", dataMi)
            //Error is occured because of the "nil" 
            //self.mov.movImage = UIImage(data:dataMi)!

            self.mov.movTitle = res["original_title"] as! String
            self.mov.desctiption = res["overview"] as! String
            self.movResult.append(self.mov)
            self.resultCount = results.count
        }
        DispatchQueue.main.async() {
            self.myCollectionView.reloadData()
        }
    }catch{
        print("Error is occured because of the Json Serialization")
    }
};task.resume()
  

关于下载顺序的问题

此代码运行良好,但是下载图片存在问题,因为图片网址取决于json网址。当我下载其他数据时,我想下载图像,如电影标题,电影描述等。

代码运行时:

print(dataMi)

返回数据,但......

print("2:", dataMi) 

返回nil。那么我该怎样做才能正确运行该部分? 因为它也会导致错误,我无法在单元格中设置我的imageview

 //Error is occured because of the "nil" 
 //self.mov.movImage = UIImage(data:dataMi)!

Console Screen Shot

2 个答案:

答案 0 :(得分:0)

第一个问题,

let downLoadPicTask = URLSession.shared.dataTask(with: urlOfthePic!, completionHandler: { (data, res, err) in
    guard let data = data else {print("second"); return}
    dataMi = data
    self.mov.movImage = UIImage(data: dataMi)!
    print(dataMi)
});downLoadPicTask.resume()
print("2:", dataMi)

这段代码是异步运行的,因此print("2:", dataMi)会立即执行,print(dataMi)将在dataTask完成后执行。因此,如果您立即打印dataMi,当然会nildataTask完成后,dataMi不是nil包含数据。

对于您的第二个问题,请检查您的urlOfthePic是否正确且可访问。

答案 1 :(得分:0)

我自己解决了这个问题:D当我试图解决这个问题时,我学到了太多的工作人员;我学到的最好的事情是:"不要放弃......" 一段时间后我写的代码:

  1. 我覆盖了我的数据模型并将poster_path添加到我的Movie struct
  2. 通过我的JSON流程,我获得了API中的值
  3. movies数组中填充了更新的Movie个对象
  4. 我在第二部分创建了一个URL,它是源代码中的func
  5. 感谢Dispatch< 3我使用零延迟 填充了集合视图

    override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)
    //MARK: JSON
    //get popular films for moviescontroller page
    
    var components = URLComponents()
    
    components.scheme = Constanst.API.ApiSchema
    components.host = Constanst.API.ApiHost
    components.path = Constanst.API.ApiPath
    components.path = components.path + Constanst.API.Discover + Constanst.API.Movies
    components.queryItems = [URLQueryItem(name: "api_key", value: Constanst.API.ApiKey), URLQueryItem(name: "language", value: "en-US"), URLQueryItem(name: "sort_by", value: "popularity.desc"), URLQueryItem(name: "include_adult", value: "false"), URLQueryItem(name: "include_video", value: "false"),URLQueryItem(name: "page", value: "1")]
    
    
    //Url OKé
    let url = components.url
    
    //Config OKé
    let request = NSMutableURLRequest(url: url!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)
    request.httpMethod = "GET"
    
    //Request OKé
    let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in
        guard (error == nil) else{
            print("Error is occures: \(error!)")
            return
        }
        guard let statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode<300 && statusCode>199 else {
            print("There is an error related to your response")
            return
        }
        guard let data = data else {
            print("There is no data")
            return
        }
    
        //Parsing JSON Oké
        let parsedData : [String:AnyObject]
        do{
            parsedData = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:AnyObject]
            guard let results = parsedData["results"] as? [[String:AnyObject]] else { print("There is a problemGa");return}
            for res in results {
                self.movie.movTitle = res["original_title"] as! String
                self.movie.desctiption = res["overview"] as! String
                self.movie.posterPath = res["poster_path"] as! String
                self.movies.append(self.movie)
            }
        }catch{
            print("Error is occured because of the Json Serialization")
        }
        DispatchQueue.main.async {
            self.myCollectionView.reloadData()
        }
    };task.resume()
    

    func collectionView(_ collectionView:UICollectionView,cellForItemAt indexPath:IndexPath) - &gt; UICollectionViewCell {

    let cell = myCollectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) as! myCollectionViewCell
    cell.setUpConstraints()
    
        cell.movieTitle.text = movies[indexPath.row].movTitle
        cell.desc.text = movies[indexPath.row].desctiption
        cell.movieImage.image = movies[indexPath.row].movImage
    
    let task = URLSession.shared.dataTask(with: URLRequest(url:URL(string:"https://image.tmdb.org/t/p/w92\(movies[indexPath.row].posterPath)")!), completionHandler: { (data, res, err) in
        guard let imageData = data else {return}
        guard (err == nil) else {print(err!); return}
        DispatchQueue.main.async {
            cell.movieImage.image = UIImage(data: imageData)
        }
    });task.resume()
    
    
    
    
    
        return cell