ios - Swift 4:无法将“数据”类型的值转换为预期的参数类型“数据”

标签 ios uiimage swift4 xcode9

我正在使用Xcode 9,Swift 4。

我正在尝试使用以下代码从URL在ImageView中显示图像:

func getImageFromUrl(sourceUrl: String) -> UIImage {
        let url = URL(string: sourceUrl)
        let dict = NSDictionary(contentsOf: url!)
        let data = Data(dictionary: dict!)
        let image = UIImage(data: data!)
        return image
}

但是我在let image = UIImage(data: data!)中出错。

编译器说:

无法将“数据”类型的值转换为预期的参数类型“数据”

我究竟做错了什么?

最佳答案

/// Returns nil if image data is not correct or some network error has happened
func getImageFromUrl(sourceUrl: String) -> UIImage? {
  if let url = URL(string: sourceUrl) {
    if let imageData = try? Data(contentsOf:url) {
      return UIImage(data: imageData)
    }
  }
  return nil
}

关于ios - Swift 4:无法将“数据”类型的值转换为预期的参数类型“数据”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47234425/

相关文章:

ios - 从委托(delegate)函数 Swift 4 中提取值

ios - 错误: Unsupported compiler 'GCC 4.2' selected for architecture 'i386'

ios - 如何构建与 facebook 集成的 iphone 应用程序的好例子

ios - 从可重复使用的单元中删除旧数据

iOS用户数据存储困境

arrays - 创建 UIImage 数组时出现问题

objective-c - 重复更新 UIImage 未显示在屏幕上

ios - 从NSObject显示图像

xcode 9 无法加载从带有标识符的包中的 Nib 引用的图像

ios - 向 tableview 添加动画后应用程序崩溃 (Swift)