2014-10-20 88 views
0

我正在使用此塊從Parse引入UImages。進度塊運行次數太多 - swift

for object in objects { 
    let thumbNail = object["StaffPic"] as PFFile 

    thumbNail.getDataInBackgroundWithBlock({ 
     (imageData: NSData!, error: NSError!) -> Void in 
     if (error == nil) { 
      let image = UIImage(data:imageData) 


     } 

     }, progressBlock: {(percentDone: CInt) -> Void in 
      self.logoImages.append(self.image) 
    }) 
} 

問題是,它運行ProgressBlock 6次(如果查詢中有6個圖像)。一旦完成,我需要它運行progressBlock一次。

任何想法?

回答

0

progressBlockPFFile's getDataInBackgroundWithBlock:progressBlock:的使用以獲取正在下載的單個文件的進度,而不是知道所有下載何時完成的方式。即使只下載一個文件,也可以很容易地被稱爲更多比6倍。你絕對不應該在那裏追加self.imageself.logoImages,這應該在你創建imageimageData剛剛創建image後在結果塊中完成。

for object in objects { 
    let thumbNail = object["StaffPic"] as PFFile 

    thumbNail.getDataInBackgroundWithBlock({ 
     (imageData: NSData!, error: NSError!) -> Void in 
     if (error == nil) { 
      let image = UIImage(data:imageData) 
      self.logoImages.append(image) 
     } 
    }, progressBlock: {(percentDone: CInt) -> Void in 
     // Update your UI with download progress here (if needed) 
    }) 
} 

現在,您似乎需要一種方法來了解何時所有這些下載都已完成。我會使用dispatch groups。基本步驟是:

  1. 創建dispatch_group_t
  2. 對於每個下載:
    1. 呼叫dispatch_group_enter
    2. 執行下載
    3. 呼叫dispatch_group_leave下載完成時
  3. 呼叫dispatch_group_notify帶有應該在下樓時調用的塊oad完成。

這將是這個樣子:

let downloadGroup = dispatch_group_create() 

for object in objects { 
    let thumbNail = object["StaffPic"] as PFFile 

    dispatch_group_enter(downloadGroup) 

    thumbNail.getDataInBackgroundWithBlock({ 
     (imageData: NSData!, error: NSError!) -> Void in 
     if (error == nil) { 
      let image = UIImage(data:imageData) 
      self.logoImages.append(image) 

      dispatch_group_leave(downloadGroup) 
     } 
    }, progressBlock: {(percentDone: CInt) -> Void in 
     // Update your UI with download progress here (if needed) 
    }) 
} 

dispatch_group_notify(downloadGroup, dispatch_get_main_queue()) { 
    // This will be called when all your downloads are complete 
} 
0

你的方法是用於異步定期更新,所以你可以更新進度指示器或其他東西。所以,你得到定期更新的數據進來......如果你真的只想知道什麼時候做,那麼我建議只是在做你的行動時,percentDone == 100 ...

progressBlock: {(percentDone: CInt) -> Void in 
      if(percentDone==100) 
      { 
       self.logoImages.append(self.image) 
      } 
    }) 
+0

當然這是'Parse'依賴,因爲我不知道該庫,誰知道也許這甚至可能發生不止一次什麼,也許有更好的辦法,比如註冊一個回調,或者輪詢一個對象來完成......我不知道,我只是猜測你發佈的內容。 – 2014-10-20 14:35:41