0

I'm trying to convert NSURL to 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. But while converting it to NSData it gives nil value. I know there are similar questions in stackoverflow but none of them solves my problem. I'm using swift 2.2

Bhavin Ramani
  • 3,221
  • 5
  • 30
  • 41
Linkon Sid
  • 521
  • 1
  • 5
  • 16
  • 2
    Is `imageData` nil? try with `contentsOfFile:` instead if it's local, or change the NSURL construction with `fileURLWithPath:` – Larme Oct 26 '16 at 09:09
  • 1
    If you are loading local file, why do you need to convert it url, nsdata ? Follow this: http://stackoverflow.com/questions/25739762/load-image-from-ios-8-framework – Jamshed Alam Oct 26 '16 at 09:13

3 Answers3

1

If the string points to a local file url then you are using the wrong API. The correct one is

let url = NSURL(fileURLWithPath: urlString)

NSURL(string: is only for URL strings which start with a valid file scheme (e.g. http or ftp)

vadian
  • 274,689
  • 30
  • 353
  • 361
  • Still getting nil value while converting it to NSData. Here is my url string: **"/var/mobile/Media/DCIM/101APPLE/IMG_1827.JPG"** Here is what I get after converting it to NSURL: **file:///var/mobile/Media/DCIM/101APPLE/IMG_1827.JPG** – Linkon Sid Oct 26 '16 at 09:37
  • Do you have access privileges for that directory? – vadian Oct 26 '16 at 09:59
  • I dont think so. How do I ensure that?? – Linkon Sid Oct 26 '16 at 10:07
0

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)
J. Koush
  • 1,028
  • 1
  • 11
  • 17
  • **imageData** is nil – Linkon Sid Oct 26 '16 at 10:39
  • Maybe it's because of your urlString are you sure that it's correct? – J. Koush Oct 26 '16 at 10:43
  • urlString is a String, you would not know if it is a correct string since String types can't check for the data, you have to go thought each folder and check each and every letter, and remember it's case sensitive. – J. Koush Oct 26 '16 at 11:17
  • Or you can copy the link by right clicking of the file and selecting get info, and coping the link from General dropdown Where: – J. Koush Oct 26 '16 at 11:19
-1

The Correct one is use contentsOf: forecastURL! as URL instead of 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!)