在swift中的uiscrollview中解析加载图像

时间:2015-07-11 14:59:55

标签: ios swift parse-platform pffile

我想从包含多个图像的PFFile中检索图像,并将它们放在一个scrollview中。到目前为止,我已经尝试了以下内容,但是这会返回错误“警告:正在主线程上执行长时间运行的操作。”

    let scrView = UIScrollView()

    var query = PFQuery(className: "Pictures")
    query.whereKey("uploader", equalTo: PFUser.currentUser()!)
    query.orderByDescending("createdAt")
    query.findObjectsInBackgroundWithBlock{
        (posts: [AnyObject]?, error: NSError?) -> Void in
        if error == nil {
            for post in posts!{
                self.imageFiles.append(post["imageFile"]as! PFFile)
                self.imageText.append(post["imageText"]as! String)
            }


    for var i = 0; i < self.pictNumber; ++i {
        var userImageFile = self.imageFiles[i]
        println(userImageFile)
        var imgFileData = userImageFile.getData()
        var image = UIImage(data: imgFileData!)
        var tempImageView = UIImageView (image: image)
        tempImageView.frame = CGRectMake(CGFloat(width*i), 0, self.view.frame.width, self.view.frame.height)
        scrView.addSubview(tempImageView)


        }

我也尝试过以下操作,但它会跳过从PFFile中提取图像的部分,并将图像添加到滚动视图中。

    let scrView = UIScrollView()

    var query = PFQuery(className: "Pictures")
    query.whereKey("uploader", equalTo: PFUser.currentUser()!)
    query.orderByDescending("createdAt")
    query.findObjectsInBackgroundWithBlock{
        (posts: [AnyObject]?, error: NSError?) -> Void in
        if error == nil {
            for post in posts!{
                self.imageFiles.append(post["imageFile"]as! PFFile)
                self.imageText.append(post["imageText"]as! String)
            }


    for var i = 0; i < self.pictNumber; ++i {
        var userImageFile = self.imageFiles[i]
        println(userImageFile)

        //Extracting pictures from PFFile
        self.imageFiles[i].getDataInBackgroundWithBlock{
            (imageData: NSData?, error: NSError?) -> Void in
            if imageData != nil {
                var image = UIImage(data: imageData!)
                var tempImageView = UIImageView (image: image)
                tempImageView.frame = CGRectMake(CGFloat(width*i), 0, self.view.frame.width, self.view.frame.height)
                scrView.addSubview(tempImageView)
                println(i)

            }else {
                println(error)
            }}



        }

2 个答案:

答案 0 :(得分:1)

尝试使用userImageFile.getDataInBackgroundWithBlock()而不是userImageFile.getData()

userImageFile.getData获取主线程中的文件,如果文件很大或者您的Internet连接速度很慢,可能会冻结您的UI

答案 1 :(得分:0)

您收到错误:

  

警告:正在执行长时间运行的操作   线程。

这意味着您必须在主线程中执行该任务,并且可以使用以下代码执行此操作:

dispatch_async(dispatch_get_main_queue()) {
    //add your code here
}