[英]How do I load an image from Parse into Swift
我在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变量以将其引入。
当我运行它时,我没有收到错误消息,但是我的按钮没有从解析中更新图像。
我怀疑它与类型有关,可能是在“让我的数据= PFObject(className:“ headliner”)行...但是我不知道该如何解决...
任何帮助,将不胜感激! 我烤饼干,所以如果您能解决这个问题,我会给您发送的!
马里
使用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)
}
}
您需要尝试在其他线程中更新图像。 (这也给了我很多次)另外,我通常会更改变量的名称的未包装版本,以便于区分它们。
dispatch_async(dispatch_get_main_queue(), { () -> Void in
//Image update code goes here
if let unWrappedimageData = imageData {
let image = UIImage(data: unWrappedimageData)
self.headlinerImage.setImage(unWrappedimageData, forState: UIControlState.Normal)
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.