图片path不能转换成swift3中的url

我有post回应,我想从image_path下载图片

 let fileUrl = NSURL(fileURLWithPath: (posts.value(forKey: "image_path") as! [String])[indexPath.row]) print(fileUrl as Any) // here i can get path if FileManager.default.fileExists(atPath: (fileUrl)// nil value { let url = NSURL(string: (posts.value(forKey: "image_path") as! [String])[indexPath.row]) // Here url found nil let data = NSData(contentsOf: url! as URL) cell.LocationImage?.image = UIImage(data: data! as Data) } 

更新:

[1]:https://i.stack.imgur.com/KWC S9.png

该URL不是本地文件pathURL,也不是符合我的浏览器的有效URL。

上面提供的URL返回浏览器中的服务器错误,并且不返回图像。 看截图

截图

您需要确保图像可以访问,并且URL实际上首先返回图像响应。 那么你需要下载图像。 不知道你是否使用任何库,所以我会发表一个例子没有。

 //: Playground - noun: a place where people can play import UIKit import XCPlayground import PlaygroundSupport let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) // random image from images.google.com let urlString = "https://files.allaboutbirds.net/wp-content/uploads/2015/06/prow-featured-240x135.jpg" let url = URL(string: urlString) let session = URLSession.shared let task = session.dataTask(with: url!) { data, response, error in guard error == nil else { print("[ERROR] - Failed to download image") return } if let data = data { let image = UIImage(data: data) DispatchQueue.main.async { imageView.image = image } } } let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) view.addSubview(imageView) task.resume() PlaygroundPage.current.liveView = view 

更新:

截图2