数据故障

时间:2019-06-13 20:32:08

标签: ios swift flickr

我正在使用Flickr API来获取集合中的所有相册,然后使用中的相册ID来获取每个相册的主要照片。它可以工作,但照片不会按顺序退还给我,因此每个相册的主照片与我的收藏夹视图中的相册标题不匹配。

func getPhotoCollection() {
        let collectionURLString = "https://api.flickr.com/services/rest/?method=flickr.collections.getTree&api_key={API_KEY}&collection_id=72157676119666248&user_id={USER_ID}&format=json&nojsoncallback=1"

        self.session = URLSession(configuration: .default, delegate: self, delegateQueue: nil)
        let task = self.session?.dataTask(with: URL(string: collectionURLString)!, completionHandler: { (data, response, error) in
            let json = self.getJSONFrom(urlString: collectionURLString)
            let collections = json["collections"]
            let collection = collections["collection"].arrayObject as! [[String:AnyObject]]
            for collectionObject in collection {
                let sets = collectionObject["set"] as! [[String: AnyObject]]
                for set in sets {
                    let albumId = set["id"] as! String
                    let albumTitle = set["title"] as! String
                    self.albumIds.append(albumId)
                    self.albumTitles.append(albumTitle)
                }
            }

            self.getAlbumPrimary()
        })

        task?.resume()
    }

func getAlbumPrimary() {
        for albumId in self.albumIds {
            let apiURLString = "https://api.flickr.com/services/rest/?method=flickr.photosets.getPhotos&api_key={API_KEY}&photoset_id=\(albumId)&per_page=1&user_id={USER_ID}&format=json&nojsoncallback=1"

            self.session = URLSession(configuration: .default, delegate: self, delegateQueue: nil)
            let task = self.session?.dataTask(with: URL(string: apiURLString)!, completionHandler: { (data, response, error) in
                let json = self.getJSONFrom(urlString: apiURLString)
                let photos = json["photoset"]
                let photo = photos["photo"].arrayObject as! [[String:AnyObject]]
                let primaryPic = photo[0]
                let farm = primaryPic["farm"] as! Int
                let server = primaryPic["server"] as! String
                let picId = primaryPic["id"] as! String
                let secret = primaryPic["secret"] as! String

                let urlString = String(format: "https://farm%d.static.flickr.com/%@/%@_%@_b.jpg", farm, server, picId, secret)
                self.albumPrimaryURLs.append(urlString)

                DispatchQueue.main.async {
                    self.collectionView.reloadData()
                    self.loaded = true
                }
            })

            task?.resume()
        }
    }

1 个答案:

答案 0 :(得分:2)

这是多个异步任务的工作方式(乱序),您需要创建一个模型而不是单独的数组,然后从数据中加载以填充最后一个属性

class Item {
  let id,title:String
  var url:String?
  init(id:String,title:String){
   self.id = id
   self.title = title 
  }
  func loadUrl(completion:@escaping () -> () ) {
     // here load and set the url
  }
}

var items = [Item]() // declare main array 

 let albumId = set["id"] as! String
 let albumTitle = set["title"] as! String 
 let item = Item(id:albumId,title:albumTitle)
 self.items.append(item) 

然后最终加载集合

let g = DispatchGroup()
items.forEach {
   g.enter()
   $0.loadUrl {
      g.leave()
   }
} 
g.notify(queue:.main) {
  self.collectionView.reloadData()
  self.loaded = true
}