2014-12-27 35 views
4

在我的ProfileViewController我有一個查詢,用於檢索存儲爲PF文件的用戶個人資料圖片。正在主線程上執行長時間運行的操作。 Swift

var query = PFQuery(className:"Users") 
    query.whereKeyExists("profilePicture") 
    query.findObjectsInBackgroundWithBlock { 
     (objects: [AnyObject]!, error: NSError!) -> Void in 
     if error == nil { 

      self.userNameLabel.text = PFUser.currentUser().username 

      if let imageFile = PFUser.currentUser().objectForKey("profilePicture") as? PFFile { 
       if let data = imageFile.getData() { 
        self.profPic.image = UIImage(data: data) 
       } 
      } 

     } 
     else { 
      println("User has not profile picture") 
     } 
    } 

這是這個視圖中唯一的查詢,我在我的應用程序的主頁中有另一個查詢,它擁有所有用戶的所有帖子。我得到的錯誤我A long-running operation is being executed on the main thread.其次Break on warnBlockingOperationOnMainThread() to debug.

我不知道如何解決這個問題,特別是因爲我需要做另一個查詢,以獲得當前用戶發佈那裏配置文件。我應該使用findObjectsInBackgroundWithBlock以外的東西嗎?謝謝。

+0

您是否絕對肯定這是問題的根源?沒有'... WithContentsOfURL'或'sendSynchronousRequest'徘徊?沒有別的可能會阻止主線程?順便說一句,儀器有一個稱爲「記錄等待線程」功能,以幫助識別這些類型的問題。你用過嗎? – Rob

+0

我沒有使用WithContentsOfUrl或sendSynchronousRequest,你能解釋一下這個工具的功能,所以我可以使用它,謝謝@Rob – kareem

+0

請參閱WWDC 2014應用程序的「時間分析」部分[使用儀器改進您的應用程序](https://developer.apple .com/videos/wwdc/2014 /?id = 418),約18分鐘進入視頻。之前在其他年份的視頻中也有過,但這是一個很好的開始。但丹已經確定了問題的根源,所以現在可能不需要儀器。但下次您可以使用儀器自行查找問題的根源。 – Rob

回答

5

警告來自Parse sdk。這部分:imageFile.getData()是同步的,並且在使用任何阻塞調用時,Parse足以警告您。有幾種getDataInBackground ...作爲替代品可供選擇。 See them in the docs here

+0

謝謝您推薦哪種方法?所以我不應該使用findObjectsWithBlock? @danh – kareem

+0

getDataInBackground可以工作。下一個品種... WithBlock:告訴你它什麼時候完成。另一個... WithBlock:ProgressBlock:完成後會告訴你,完成後會完成。 (但請記住這是PFFile類,所以不能找到對象而是獲取數據)。 – danh

3

要詳細說明@danh解決方案,這是更新的源代碼,並且工作得很好,謝謝@danh!

override func viewDidLoad() { 
    super.viewDidLoad() 


    var query = PFQuery(className:"Users") 
    query.whereKeyExists("profilePicture") 
    query.findObjectsInBackgroundWithBlock { 
     (objects: [AnyObject]!, error: NSError!) -> Void in 
     if error == nil { 

      self.userNameLabel.text = PFUser.currentUser().username 

      if let imageFile = PFUser.currentUser().objectForKey("profilePicture") as? PFFile { 
      imageFile.getDataInBackgroundWithBlock { (data: NSData!, error: NSError!) -> Void in 
        self.profPic.image = UIImage(data: data) 
       } 
      } 

     } 
     else { 
      println("User has not profile picture") 
     } 
     } 
    } 
相關問題