尝试将图像从iOS上传到parse.com

时间:2016-01-18 07:06:22

标签: ios swift parse-platform

我正在尝试将图片从iOS应用上传到Parse类。

ViewController有两个按钮和一个ImageView

按钮1 :从设备的PhotoGallery中选择图片,

ImageView (myImageView):显示所选图片。

这部分应用程序运行正常。

在Parse中,我从类型文件中创建了一个名为 citas_servicio 的类,其中包含一个名为 foto 的列。

按钮2操作为 subirFoto

@IBAction func subirFoto(sender: AnyObject) {
    if myImageView.image == nil {
        //image is not included alert user
        print("Image not uploaded")
     }else {
         var posts = PFObject(className: "citas_servicio")
         posts.saveInBackgroundWithBlock({(success: Bool, error: NSError?) -> Void in
             if error == nil {
                 /**success saving, Now save image.***/

                 //create an image data
                 var imageData = UIImagePNGRepresentation(self.myImageView.image!)
                 //create a parse file to store in cloud
                 var parseImageFile = PFFile(name: "uploaded_image.png", data: imageData!)
                 posts["foto"] = parseImageFile
                 posts.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) -> Void in
                     if error == nil {
                         //take user home
                         print("data uploaded")
                     }else {
                         print(error)
                     }
                 })
             }else {
                 print(error)
             }
         })
     }
 }

单击Button2后,将在Parse中创建新记录,但不会在其中添加图像,并且控制台中不会打印任何消息。

代码有什么问题?

3 个答案:

答案 0 :(得分:1)

首先在后台保存parseImageFile,然后将其与PFObject相关联并在后台保存帖子(PFObject)。我希望它能够正常工作。

答案 1 :(得分:1)

您在帖子中设置Object之前保存foto,这就是您收到错误的原因。首先保存图像,然后将其设置为Object

let posts = PFObject(className: "citas_servicio")
        //create an image data
        let imageData = UIImagePNGRepresentation(self.myImageView.image!)
        //create a parse file to store in cloud
        let parseImageFile = PFFile(name: "uploaded_image.png", data: imageData!)
        parseImageFile?.saveInBackgroundWithBlock({ (success, error) -> Void in
            if success{
                posts["foto"] = parseImageFile
                posts.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) -> Void in
                    if error == nil {
                        //take user home
                        print("data uploaded")
                    }else {
                        print(error)
                    }
                })
            }
        })

答案 2 :(得分:1)

您无需保存对象,然后再次保存照片,只需在创建后添加到PFObject即可。

var posts = PFObject(className: "citas_servicio")
let imageData = UIImagePNGRepresentation(self.myImageView.image!)
let parseImageFile = PFFile(name: "uploaded_image.png", data: imageData!)
posts["foto"] = parseImageFile

之后,您可以轻松地将对象保存在后台。