[英]NSURL to NSData nil value
I'm trying to convert NSURL
to NSData
. 我正在尝试将
NSURL
转换为NSData
。 My url string is a local file url which I'm getting from my device. 我的网址字符串是我从设备上获取的本地文件网址。
let url = NSURL(string: url)
let imageData = NSData(contentsOfURL: url)
let image = UIImage(data: imageData)
I'm getting NSURL
value properly. 我正在正确获取
NSURL
值。 But while converting it to NSData
it gives nil
value. 但是在将其转换为
NSData
其值为nil
。 I know there are similar questions in stackoverflow but none of them solves my problem. 我知道在stackoverflow中也有类似的问题,但是没有一个能解决我的问题。 I'm using swift 2.2
我正在使用Swift 2.2
If the string points to a local file url then you are using the wrong API. 如果字符串指向本地文件url,则说明您使用的API错误。 The correct one is
正确的是
let url = NSURL(fileURLWithPath: urlString)
NSURL(string:
is only for URL strings which start with a valid file scheme (eg http
or ftp
) NSURL(string:
仅适用于以有效文件方案开头的URL字符串(例如http
或ftp
)
Try this code. 试试这个代码。
let urlString = "/var/mobile/Media/DCIM/101APPLE/IMG_1827.JPG"
let url = URL(fileURLWithPath: urlString)
let imageData = NSData(contentsOf: url)
let image = UIImage(data: imageData as! Data)
The Correct one is use contentsOf: forecastURL! 正确的一种是使用contentsOf:预报URL! as URL instead of contentsOf: forecastURL
作为URL而不是contentsOf:ForecastURL
let forecastURL = NSURL(string: "http://photos.state.gov/libraries/media/788/images/90x90.gif")
let testImage = NSData (contentsOf: forecastURL! as URL)
print("data",testImage!)
let image = UIImage(data: testImage! as Data)
print("imaGE :-",image!)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.