这个问题快把我逼疯了。我有这个字符串url
"verona-api.municipiumstaging.it/system/images/image/image/22/app_1920_1280_4.jpg“和我必须在我的imageView中加载这个图像。
这是我的密码:
do {
let url = URL(fileURLWithPath: "http://verona-api.municipiumstaging.it/system/images/image/image/22/app_1920_1280_4.jpg")
let data = try Data(contentsOf: url)
self.imageView.image = UIImage(data: data)
}
catch{
print(error)
}这会引发异常:
文件或目录不存在。
但是如果我用浏览器搜索这个url,我就能正确地看到图像!
发布于 2017-10-31 08:28:26
您正在使用错误的方法创建URL。尝试URLWithString而不是fileURLWithPath。fileURLWithPath用于从本地文件路径获取图像,而不是从internet url获取图像。
或
do {
let url = URL(string: "http://verona-api.municipiumstaging.it/system/images/image/image/22/app_1920_1280_4.jpg")
let data = try Data(contentsOf: url)
self.imageView.image = UIImage(data: data)
}
catch{
print(error)
}发布于 2017-10-31 08:45:41
方法fileURLWithPath从文件系统打开文件。文件地址加上file://。您可以打印url字符串。
摘自苹果关于+ (NSURL *)fileURLWithPath:(NSString *)path;的文档
NSURL对象将表示的路径。路径应该是有效的系统路径,不能是空路径。如果路径以倾斜开始,则必须首先使用stringByExpandingTildeInPath展开路径。如果path是相对路径,则将其视为相对于当前工作目录。
以下是几种可能的解决方案之一:
let imageName = "http://verona-api.municipiumstaging.it/system/images/image/image/22/app_1920_1280_4.jpg"
func loadImage(with address: String) {
// Perform on background thread
DispatchQueue.global().async {
// Create url from string address
guard let url = URL(string: address) else {
return
}
// Create data from url (You can handle exeption with try-catch)
guard let data = try? Data(contentsOf: url) else {
return
}
// Create image from data
guard let image = UIImage(data: data) else {
return
}
// Perform on UI thread
DispatchQueue.main.async {
let imageView = UIImageView(image: image)
/* Do some stuff with your imageView */
}
}
}
loadImage(with: imageName)如果您只发送一个完成处理程序在主线程上执行到loadImage(with:),这是最好的实践。
发布于 2017-10-31 08:33:56
在这里,url不是本地系统的,而是服务器的。
let url = URL(fileURLWithPath: "http://verona-api.municipiumstaging.it/system/images/image/image/22/app_1920_1280_4.jpg")这里创建的是本地设备上的文件。创建网址如下:-
url = URL(string: "http://verona-api.municipiumstaging.it/system/images/image/image/22/app_1920_1280_4.jpg") https://stackoverflow.com/questions/47030822
复制相似问题