0
我有一個collectionViewView作爲另一個視圖的子視圖。我希望僅在執行查詢以獲取圖片以填充圖片後才顯示它,並在未準備好時放置活動指示符。 我試圖把我的代碼放在viewWillAppear中,但是在顯示視圖之前我沒有下載照片。處理這個問題的最佳方法是什麼?如何僅在查詢回調後加載視圖
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let query = queryAPI()
query.userExtra(currentUser, completion: { (user:ModelUser) ->() in
self.currentUser = user
if let userPhotos = self.currentUser.photos as [ModelAttachment]! {
self.photos = [UIImage]()
for object in userPhotos as [ModelAttachment] {
Utils.getImageAsync(object.url!, completion: { (img: UIImage?) ->() in
self.photos?.append(img!)
object.image = img
})
}
self.photosCollectionView.reloadData()
}
})
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView == photosCollectionView {
if let hasPhotos = photos as [UIImage]! {
return photos!.count
} else {
return 0
}
}else{
return friends.count
}
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
if collectionView == photosCollectionView {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! UICollectionViewCell
let imageView = cell.viewWithTag(1) as! UIImageView
let photo = photos![indexPath.row]
imageView.image = photo
return cell
}
}
和函數來獲取圖像異步:
class func getImageAsync(url:String, completion: (UIImage?) ->()){
var escapedUrl = url.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
var imageUrl = NSURL(string: escapedUrl!)
if(imageUrl == nil)
{
println("Invalid Url!")
completion(nil)
}
else
{
var stdUrl = imageUrl!.standardizedURL!
println("Downlading image: "+stdUrl.description)
let req = NSURLRequest(URL: stdUrl)
NSURLConnection.sendAsynchronousRequest(req, queue: NSOperationQueue.mainQueue()) { (resp, data, error) -> Void in
var image: UIImage?
if data != nil {
image = UIImage(data: data!)!
} else {
println("Error while download the image: \(error)")
}
dispatch_async(dispatch_get_main_queue()) {
completion(image)
}
}
}
}
你調用方法'完成(圖)'圖像下載完成之後,所以你應該重裝從那裏收集視圖;像'self.photosCollectionView.reloadData()' – Gandalf
該函數是在另一個文件,因爲我在我的代碼中的不同位置使用它,我怎麼能調用重新加載另一個控制器的數據呢? –