[英]Getting error when loading image file from Parse
有问题的行是“让productImageFile = productData![“ productImage”] as!PFFile”,这给了我错误“严重错误:在展开可选值(lldb)时意外发现nil”。 我找到的唯一答案涉及确保我不试图解开显式定义的可选对象(我认为这是术语),但是我弄乱了可选对象,并且我在何时以及何时取消了绑定,但是我没有运气。 没有其他消息来源能够为我解决此特定问题,我被困住了。 请帮忙。
override func viewDidLoad() {
super.viewDidLoad()
//Create new PFQuery to retrieve info from Parse
var query: PFQuery = PFQuery(className: "MyProduct")
//function to get the data
func getProductData (){
//call function to get the data from parse by specifyng an objectId
query.getObjectInBackgroundWithId("XXXXXXXXXX") {
(productData:PFObject?, error:NSError?) -> Void in
if error == nil && productData != nil {
//Extract values from the productData PFObject and store them in constants
let dayOfTheWeek = productData!.objectForKey("day") as! String
let productTitle = productData!.objectForKey("productTitle") as! String
//-----start image loading
let productImageFile = productData!["productImage"] as! PFFile
productImageFile.getDataInBackgroundWithBlock {
(imageData: NSData?, error: NSError?) -> Void in
if error == nil {
if let imageData = imageData {
let image = UIImage(data:imageData)
self.productImageView.image = image!
} else {println("Could not load image.")}
}
}
//-----end image loading
let productPrice = productData!.objectForKey("productPrice") as! String
let productDescription = productData!.objectForKey("productDescription") as! String
//take the saved constants and assign their values to the labels and UIImage on screen
self.productTitleLabel.text = productTitle
self.dayOfTheWeekLabel.text = dayOfTheWeek
self.productPriceLabel.text = productPrice
self.productDescriptionLabel.text = productDescription
} else if error != nil {
println("Could not load data from Parse")
}
}
}
我认为并非所有产品都有图像,因此您需要按以下方式更新代码:
if let productImageFile = productData!["productImage"] as? PFFile {
productImageFile.getDataInBackgroundWithBlock {
(imageData: NSData?, error: NSError?) -> Void in
if error == nil {
if let imageData = imageData {
let image = UIImage(data:imageData)
self.productImageView.image = image!
} else {println("Could not load image.")}
}
}
}
这将确保仅当productImage的响应为PFFile时,才会处理productImageFile。
如果您的错误没有打印出任何有用的信息,请确保获取有效的数据。 检查数据长度,看看是否与文件大小相对应。
另外,请检查imageView是否在主线程上设置了图像,如果从后台线程调用,它将不会显示。
dispatch_async(dispatch_get_main_queue(), ^ {
self.productImageView.image = image!
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.