Swift 3 上传图片到 Parse Server
Posted
技术标签:
【中文标题】Swift 3 上传图片到 Parse Server【英文标题】:Swift 3 upload image to Parse Server 【发布时间】:2017-02-27 11:04:23 【问题描述】:我正在尝试使用 PFFile 将图像上传到 Parse Server。从 Parse Dashboard 手动上传并从应用程序检索它没有问题。但是如果我尝试用这种方法上传一个新的,图像不会被更新。
其余字段上传正确(姓名、姓氏、用户名和电子邮件)
保存方法:
@IBAction func saveBtnPressed(_ sender: Any)
print("Start saving...")
let imageData = UIImagePNGRepresentation(profilePic.image!)
print ("imageData value:")
print(imageData!)
let imageFile = PFFile(name:"avatar.png", data:imageData!)
print ("imageFile value:")
print(imageFile!)
let query = PFQuery(className: "_User")
query.whereKey("username", equalTo: (PFUser.current()?.username)!)
query.findObjectsInBackground(block: (objects, error) in
if let user = objects
for object in user
object["name"] = self.nameFld.text
object["lastname"] = self.lastnameFld.text
object["username"] = self.emailFld.text
object["email"] = self.emailFld.text
object["avatar"] = imageFile
print(object)
object.saveInBackground()
)
输出:
Start saving...
imageData value:
8358983 bytes
(lldb)
【问题讨论】:
如果您只想为currentUser
保存图像,我看不到首先查询用户然后更新图像的任何意义。您可以简单地上传图片 aka PFFile
并将其保存为 currentUser
的头像。据我所知,imageFile
无法在 findObjectsInBackground
块中访问。
【参考方案1】:
要完成这项工作,您只需先上传图片,然后将其引用给用户
let imageData = UIImagePNGRepresentation(profilePic.image!)
print ("imageData value:")
print(imageData!)
let imageFile = PFFile(name:"avatar.png", data:imageData!)
print ("imageFile value:")
print(imageFile!)
imageFile.saveInBackground (result, error) in
if let error = error
print(error)
else
let query = PFQuery(className: "_User")
query.whereKey("username", equalTo (PFUser.current()?.username)!)
query.findObjectsInBackground(block: (objects, error) in
if let user = objects
for object in user
object["name"] = self.nameFld.text
object["lastname"] = self.lastnameFld.text
object["username"] = self.emailFld.text
object["email"] = self.emailFld.text
object["avatar"] = imageFile
print(object)
object.saveInBackground()
)
请注意,在上面的示例中,即使没有用户匹配查询,文件也会始终上传到服务器,因此请考虑仅在获得查询结果后上传文件。
【讨论】:
感谢您的回复。现在它支持此输出: 8406442 字节let imageFile = PFFile(data: data:imageData!, contentType: "image/png")
【参考方案2】:
无需查询当前用户。你可以这样做:
@IBAction func saveBtnPressed(_ sender: AnyObject)
let userToUpdate = PFUser.current()!
userToUpdate["name"] = self.nameFld.text
userToUpdate["email"] = self.emailFld.text
userToUpdate["username"] = self.emailFld.text
// Save Avatar
if profilePic.image != nil
let imageData = UIImageJPEGRepresentation(profilePic.image!, 0.5)
let imageFile = PFFile(name:"avatar.jpg", data:imageData!)
userToUpdate["avatar"] = imageFile
// Saving block
userToUpdate.saveInBackground(block: (succ, error) in
if error == nil
print("Your Profile has been updated!")
else
print("Failed")
)
【讨论】:
以上是关于Swift 3 上传图片到 Parse Server的主要内容,如果未能解决你的问题,请参考以下文章
从 Parse (Swift) 中检索图像到 imageView