[英]Trying to upload image from iOS to parse.com
I am trying to upload an image from an iOS app to a Parse class. 我正在尝试将图像从iOS应用程序上传到Parse类。
The ViewController has two buttons and an ImageView ViewController有两个按钮和一个ImageView
Button 1 : Select picture from device's PhotoGallery, 按钮1 :从设备的PhotoGallery中选择图片,
ImageView (myImageView): shows the selected picture. ImageView (myImageView):显示所选图片。
This part of the app is working fine. 这部分应用程序运行正常。
In Parse, I have created a class called citas_servicio , with a column called foto , from type file. 在Parse中,我从类型文件创建了一个名为citas_servicio的类,其中有一个名为foto的列。
Button 2 action is subirFoto : 按钮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)
}
})
}
}
Once Button2
is clicked, a new record is created in Parse, but the Image is not added in it, and no message is printed in the console. 单击
Button2
,将在Parse中创建新记录,但不会在其中添加Image,并且控制台中不会打印任何消息。
What is wrong in the code? 代码有什么问题?
首先在后台保存parseImageFile,然后将其与PFObject关联并在后台保存帖子(PFObject)。我希望它能正常工作。
You are saving Object
before setting foto
in posts thats why you are getting error. 您在帖子中设置
foto
之前保存Object
,这就是您收到错误的原因。 First save image then set it to Object
: 首先保存图像然后将其设置为
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)
}
})
}
})
You do not need to save the object, then save with photo again, just add to the PFObject
after create it. 您不需要保存对象,然后再次保存照片,只需在创建后添加到
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
After that, you can easily save the object in the background. 之后,您可以轻松地将对象保存在后台。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.