将多个图像保存到Parse

时间:2017-03-06 00:38:16

标签: ios objective-c swift swift3 parse-framework

所以我有一系列我从xcassets访问过的图像用于演示目的。我正在尝试使用解析框架一次保存到我的解析服务器的150张图像。这是我到目前为止的代码。我遇到的问题是我的应用程序CPU在测试中达到100%并且降至0.此外,图像不会保存到解析。我希望有人可以帮我找到一个有效的方法来保存150张图片进行解析。

var imageNameList: [String] {
    var imageNameList2:[String] = [] //[NSMutableArray]()
    for i in 0...149 {
        let imageName = String(format: "pic_%03d", Int(i))
        imageNameList2.append(imageName)
    }
    return imageNameList2
}
@IBAction func Continue(_ sender: Any) {
        for imageName in imageNameList {
            var objectForSave:PFObject = PFObject(className: "Clo")
            let object:UIImage = UIImage(named: imageName)!
            let tilesPF = imageNameList.map({ name in
                let data = UIImagePNGRepresentation(object as! UIImage)!
                let file = PFFile(data: data)

                let tile = PFObject(className: "Tile")
                tile["tile"] = file
            })

            objectForSave["tiles"] = tilesPF

            objectForSave.saveInBackground(block: { responseObject, error in

                //you'll want to save the object ID of the PFObject if you want to retrieve a specific image later
            })


        }

}

1 个答案:

答案 0 :(得分:1)

麻烦的是,紧密的for循环会同时启动所有这些请求,导致http堆栈的某些部分出现瓶颈。

相反,按如下顺序运行请求(在我最接近的Swift中)...

func doOne(imageName: String, completion: (success: Bool)->()) {
    var objectForSave:PFObject = PFObject(className: "Clo")
    let object:UIImage = UIImage(named: imageName)!
    // ... OP code that forms the request
    objectForSave.saveInBackground(block: { responseObject, error in
        success(error == nil) 
    })
}

func doMany(imageNames: Array<String>, completion: (success: Bool)->()) {
    if (imageNames.count == 0) return completion(YES)
    let nextName = imageNames[0];

    self.doOne(imageName:imageNames[0] completion: {(success: Bool) -> Void in
        if (success) {
            let remainingNames = imageNames[1..imageNames.count-1]
            self.doMany(imageNames: remainingNames completion:completion)
        } else {
            completion(NO)
    })
}

在英语中,为了防止Swift,我的想法是用一个完成处理程序将一个请求分解为它自己的函数。构建第二个函数,该函数接受网络请求的参数数组,并像使用待办事项列表一样使用该数组:执行列表中的第一项,完成时,递归调用自身以执行其余项。