我正在尝试通过'异步'从解析下载图像。
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell? {
var cell:CatsTableViewCell? = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? CatsTableViewCell
if(cell == nil) {
cell = NSBundle.mainBundle().loadNibNamed("CatsTableViewCell", owner: self, options: nil) [0] as? CatsTableViewCell
}
if let pfObject = object {
cell?.catNameLabel?.text = pfObject["name"] as? String
var votes:Int? = pfObject["votes"] as? Int
if votes == nil {
votes = 0
}
cell?.catVotesLabel?.text = "\(votes!) votes"
var credit:String? = pfObject["cc_by"] as? String
if credit != nil {
cell?.catCreditLabel?.text = "\(credit!) / CC 2.0"
}
cell?.catImageView?.image = nil
if var urlString:String? = pfObject["url"] as? String {
var url:NSURL? = NSURL(string: urlString!)
if var url:NSURL? = NSURL(string: urlString!) {
var error:NSError?
var request:NSURLRequest = NSURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReturnCacheDataElseLoad, timeoutInterval: 5.0)
NSOperationQueue.mainQueue().cancelAllOperations()
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {
(response:NSURLResponse?, imageData:NSData?, error:NSError?) -> Void in
cell?.catImageView?.image = UIImage(data: imageData!)
})
}
}
现在我改了几个代码
completionHandler: {
(response:NSURLResponse!, imageData:NSData!, error:NSError!) -> Void in
cell?.catImageView?.image = UIImage(data: imageData)
到
completionHandler: {
(response:NSURLResponse?, imageData:NSData?, error:NSError?) -> Void in
cell?.catImageView?.image = UIImage(data: imageData!)
并且没有严重错误,但图像未显示在模拟器上。 任何帮助将是欣赏。谢谢大家。
- 第一个问题 -
*问题发生在下面 cell?.catImageView?.image = UIImage(data:imageData) 它说
可选类型'()的值?'未展开;你的意思是使用'!'还是'?'?*
答案 0 :(得分:0)
初始化程序init(data :)返回一个可选的UIImage。您应该检查并打开它:
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {
(response: NSURLResponse?, imageData: NSData?, error: NSError?) -> Void in
if let e = error {
print(e)
return
}
guard let data = imageData else { return }
if let image = UIImage(data: data) {
cell?.catImageView?.image = image
}
})