What is difference between URLWithString and fileURLWithPath of NSURL?

13,659

Solution 1

+URLWithString: produces an NSURL that represents the string as given. So the string might be @"http://www.google.com" and the URL represents http://www.google.com.

+fileURLWithPath: takes a path, not a URL, and produces an NSURL that represents the path using a file:// URL. So if you give it /foo/bar/baz the URL would represent file:///foo/bar/baz.

You can of course construct a file URL string manually and pass it to +URLWithString:, but +fileURLWithPath: is simpler to use when you already have a path, as you don't have to deal with escaping the string and coercing it to a URL format.

Solution 2

Similar thing happened in my app which use AVAudioPlayer. I tried with [NSURL URLWithString:path] and found out it fails to open certain mp3 files. I looked into error by a line like [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:path] fileTypeHint:AVFileTypeMPEGLayer3 error:&error], but the error was simply nil

However it was resolved by replacing the url with [NSURL fileURLWithPath:path].

In both case, the path path NSString * @"/var/mobile/Containers/Data/Application/4D96D4AE-2ED4-40B0-85D2-230E1AFA90E7/Documents/01-AudioTrack 01.mp3" 0x1457a8f0 Still I don't know the reason but now I should be careful using [NSURL URLWithString:].

PS. In NSURL Reference document, Apple said as below:

IMPORTANT To create NSURL objects for file system paths, use fileURLWithPath:isDirectory: instead.

which clearly indicates [NSURL fileURLWithPath:] should be used for open file, though [NSURL URLWithString] also works for some cases.

Share:
13,659
Ameet Dhas
Author by

Ameet Dhas

I have completed post graduation in Advanced computer science from university of Leicester. I am here to learn and contribute my knowledge.

Updated on June 07, 2022

Comments

  • Ameet Dhas
    Ameet Dhas almost 2 years

    In my code I have to use URLWithString to play streaming(HLS) video and fileURLWithPath to play local video.

    What is the difference between these two methods? How should I use single method to play both videos.

    Also I need to show last frame as still image when HSL video ends. Its now showing blank screen when it ends. How should i achieve this?

    • matt
      matt about 11 years
      "Also I need to show last frame as still image when HSL video ends" Unrelated to the first part of your question. Ask it as a different question! Two for the price of one.
  • matt
    matt about 11 years
    Just to expand on the last part: a file URL is not merely a path with the word "file" stuck on the front. They work quite differently, and it is unlikely that a human being would deal correctly with the differences. The computer does.