2017-11-11 158 views
0

我使用的Xcode 9,斯威夫特4斯威夫特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!)中遇到了错误。

编译器说:

无法将类型“数据”预期参数类型“数据”

我在做什么错误的价值?

回答

0

试试这个,

func getImageFromUrl(sourceUrl: String) -> UIImage { 
    let imageData = try! Data(contentsOf: (URL(string: sourceUrl))!) 
    let image = UIImage(data: imageData) 
    return image! 
} 

//代码的另一个版本,您可以检查

func getImageFromUrl(sourceUrl: String) -> UIImage? { 
    if let imageData = try? Data(contentsOf:URL(string: sourceUrl)) { 
    return UIImage(data: imageData) 
    } 
return nil 
} 
+0

当我尝试这一点,我得到了调用错误'不正确的参数标签(有'contentsOf:',期望'字典:')' –

+0

仍然,你得到一个错误尝试这个链接可能会有所帮助https://stackoverflow.com/questions/29472149/how-to-display-an-image - 使用 - 网址 – Ashish

+0

如果确定从URL你得到图像使用编辑的功能,否则你可以检查无条件还@Inderkumar说,仍然有问题的评论! – Ashish

0
/// 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 
} 
相关问题