Swift致命错误:在展开可选值uiimage时意外发现nil

时间:2014-10-20 16:57:19

标签: ios swift uiimageview uiimage

在为UIImageView的属性图像分配UIImage时出现错误

func connectionDidFinishLoading(connection: NSURLConnection!) {
  var err: NSError
  var jsonResult : NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
  println("\(jsonResult)")
  if jsonResult.count > 0 {
    let homepage = jsonResult.objectForKey("homepage") as NSMutableDictionary
    if homepage.count > 0 {
      let imageUrl = homepage.objectForKey("url_img") as NSString
      let backgroundImageUrl = NSURL.URLWithString(imageUrl)
      let backgroundImageData = NSData(contentsOfURL: backgroundImageUrl)
      var image :UIImage = UIImage(data: backgroundImageData)
      println("\(image)")
      self.backgroundImage.image = image
    }
  }
}

它是来自get请求的委托函数。 backgroundImageDataimage不是零,但它不起作用,我不明白。

我是Swift的新手:

此代码适用于Objective-C

NSString *imageUrl = [metaData objectForKey:@"url_img"];
NSURL *backgroundImageUrl = [NSURL URLWithString:imageUrl];
NSData *backgroundImageData = [NSData dataWithContentsOfURL:backgroundImageUrl];
self.backgroundImage.image = [UIImage imageWithData:backgroundImageData];

1 个答案:

答案 0 :(得分:1)

数据很好,图片不是零。这里的错误不是代码,而是请求完成的地方。 请求需要一个委托对象,我以为我给它控制器但它不是控制器实例,HomeController()àlaplace de self 我的坏^^“