2014-12-27 36 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") 
     } 
     } 
    } 
相关问题