我在 Parse 中有一张图片,我想将其作为按钮的图片加载。
这是我的代码:
let myData = PFObject(className: "Headliner")
if let theImageFileINeed = myData["ImageFile"] as! PFFile? {
theImageFileINeed.getDataInBackgroundWithBlock { (imageData: NSData?, error: NSError?) -> Void in
if (error == nil) {
print("loadingimage?")
if let imageData = imageData {
let image = UIImage(data: imageData)
self.headlinerImage.setImage(image, forState: UIControlState.Normal)
}
} else {
print("error")
}
}
}
这是我从 Parse 文档中引用的代码:
let userImageFile = anotherPhoto["imageFile"] as PFFile
userImageFile.getDataInBackgroundWithBlock {
(imageData: NSData?, error: NSError?) -> Void in
if error == nil {
if let imageData = imageData {
let image = UIImage(data:imageData)
}
}
}
当我使用那个确切的代码时(我把它放在 viewDidLoad 中,但我不确定这是否正确),在示例中将我的表的名称换成“anotherPhoto”(imageFile 是我的字段的名称,也,所以我不必更改它),我收到以下错误消息:“使用未解析的标识符“Headliner”。所以,我假设这可能在查询中?或者我需要以某种方式指定表我想从中提取数据,所以我添加了 myData 变量来提取数据。
当我运行它时,我没有收到错误消息,但我的按钮没有更新来自解析的图像。
我怀疑它与类型有关,可能是因为“let my data = PFObject(className: "headliner")”行...但我不知道如何修复...
任何帮助将不胜感激!我烤 cookies ,所以如果你帮我解决这个问题,我会寄给你一些!!!
马里
最佳答案
使用 PFFile 从 Parse 加载 tableView 中的图像
第一步,确保导入解析库:
import Parse
第二步,声明一个 PFFile 数组,像这样:
var imageFiles = [PFFile]()
第三,将所有图片存入数组:
let query = PFQuery(className:"your_class")
query.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
if error == nil{
for writerData in objects! {
self.imageFiles.append(writerData["avatar"] as! PFFile)
}
/*** reload the table ***/
self.yourTableView.reloadData()
} else {
print(error)
}
}
第四,为了显示它(在我的例子中,我在 UITableView 中显示图像),所以在 cellForRowAtIndexPath 中:
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! YourClassTableViewCell
imageFiles[indexPath.row].getDataInBackgroundWithBlock{
(imageData: NSData?, error: NSError?) -> Void in
if imageData != nil{
let image = UIImage(data: imageData!)
cell.cellAvatarImage.image = image
} else {
print(error)
}
}
关于ios - 如何将图像从 Parse 加载到 Swift 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32831393/