[英]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.