NSString won't convert to NSURL (NSURL is null) - iphone

I'm trying to convert a NSString (a path to a file in the documents directory) to a NSURL, but the NSURL is always null. Here is my code:
NSURL *urlToPDF = [NSURL URLWithString:appDelegate.pdfString];
NSLog(#"AD: %#", appDelegate.pdfString);
NSLog(#"PDF: %#", urlToPDF);
pdf = CGPDFDocumentCreateWithURL((CFURLRef)urlToPDF);
And here is the log:
2012-03-20 18:31:49.074 The Record[1496:15503] AD: /Users/John/Library/Application Support/iPhone Simulator/5.1/Applications/E1F20602-0658-464D-8DDC-52A842CD8146/Documents/issues/3.1.12/March 1, 2012.pdf
2012-03-20 18:31:49.074 The Record[1496:15503] PDF: (null)
I think part of the problem might be that the NSString contains slashes / and dashes -. What am I doing incorrectly? Thanks.

Why don't you create your file path in this way which is.
NSString *filePath = [[NSBundle mainBundle]pathForResource:#"pdfName" ofType:#"pdf"];
And then create your url with file path like this.
NSURL *url = [NSURL fileURLWithPath:filePath];

The thing is, appDelegate.pdfString isn't a valid URL, it's a path. A file URL looks like:
file://host/path
or for the local host:
file:///path
So you actually want:
NSURL *urlToPDF = [NSURL URLWithString:[NSString stringWithFormat:#"file:///%#", appDelegate.pdfString]];
...except your path has spaces, which need to be URL encoded, so you actually want:
NSURL *urlToPDF = [NSURL URLWithString:[NSString stringWithFormat:#"file:///%#", [appDelegate.pdfString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]]];

Related

NSUrl FileUrlWith Path is appending " -- file://localhost/" at end

I am using MPMoviePlayerController to play a video from url.
for this i am getting the link from Xml parser.which is fine.
NSString *path=[[self.items objectAtIndex:videoIndex]objectForKey:#"link"];
i am assigning that path to NSURL fileWithPath as below.
NSURL *mediaUrl = [NSURL fileURLWithPath:path];
While printing the mediaUrl, NSLog is giving "http://example.com -- file://localhost/
"
Why the -- file://localhost/ is appended to the url,Because of this video is not palying.
Any help Please.
Thanks.
Change : NSURL *mediaUrl = [NSURL fileURLWithPath:path];
To : NSURL *mediaUrl = [NSURL URLWithString:path];
As you are calling the fileURLWithPath it's appending file://localhost/ to your URL string.
This is probably a bit old, but NSURL appends the -- file:://localhost if the string that you pass in isn't a valid full path string.
In your case, this is probably because you don't have a string with a "/" at the beginning (ie: "var/test" will have file://localhost appended as you've seen, but if you change it to "/var/test" you'll correctly get an NSURL with "file://localhost/var/test"
If you're trying to do a relative path, you could start with the "~/somelink" and then use stringByExpandingTildeInPath first to get the full path.

NSURL and NSString converting issue

When trying to load a request I do like this:
NSString *urlStrings = [NSLocalizedStringFromTable(#"kPicturesURL", #"urls", nil) stringByAppendingPathComponent:#"Articles/a.pdf"];
NSURL *url = [NSURL URLWithString:urlStrings];
Inside of "urls" I have this key:
/* Service pictures directory */
"kPicturesURL" = "http://192.168.2.104/myApp/Pictures";
And I get this result: (The first line is "urlStrings" and the second is the "url")
(NSString *) $6 = 0x092a8f60 http:/192.168.2.104/myApp/Pictures/Articles/a.pdf
2012-11-22 09:18:20.093 NPE[7680:c07] Couldn't issue file extension for path: /192.168.2.104/myApp/Pictures/Articles/a.pdf
I've tried those questions:
NSString and NSUrl not converting properly
NSURL not getting allocatd with NSString
Pass NSString into NSURL URLWithString ?
NSString to NSURL ?
NSString to NSURL
Non of those worked, what seems to be the problem?
Thanks!
Maybe instead of:
http:/192.168.2.104/myApp/Pictures/Articles/a.pdf
This:
http://192.168.2.104/myApp/Pictures/Articles/a.pdf
So, using one of the following did worked eventually.
This one:
NSString *stringURL = [url absoluteString];

NSURL is null while NSString is correct in Objective-C

I have an NSString containing a url and when I allocate NSURL with the NSString, NSURL outputs (null). It's because there are some illegal characters in the url, which NSURL can't read without encoding the NSString containing the url.
NSString *u = [incomingUrlString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:u];
NSLog(#"INCOMINGURLSTRING: %#" , u);
NSLog(#"URL: %#" , url);
Output is:
INCOMINGURLSTRING: /url/path/fileName_blå.pdf
URL: (null)
incomingUrlString contains the Norwegian letter "å", which I think is the reason for the NSURL being (null)
I also tried this:
NSString *trimmedString = [file stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString *encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)trimmedString, NULL, (CFStringRef)#"!*'\"();:#&=+$,/?%#[]% ", kCFStringEncodingUTF8);
NSLog(#"TRIMMEDSTRING: %#" , trimmedString);
NSLog(#"ENCODEDSTRING: %#" , [encodedString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]);
NSURL *url = [NSURL URLWithString:encodedString];
NSLog(#"URL: %#" , url);
Here the output is:
TRIMMEDSTRING: /url/path/fileName_blå.pdf
ENCODEDSTRING: /url/path/fileName_blå.pdf
URL: %2Furl%2FPath%2FfileName_bl%C3%A5.pdf
My goal is to load the URL into a UIWebView. It works for all the other incoming urls except for this one, they all look the same except for the filename. This is the only one containg an illegal character. But I have to find a way to encode this, because there will be more files containg either "æ", "ø" or "å" in the future.
I know the output does not look correct according to url standards, which I did on purpose. I can't show the correct url with http://blah blah because of security reasons.
Can anyone help?
The method you're using for percent-encoding the characters in the string also escapes legal URL characters. This would be appropriate if you were encoding a URL parameter, in this case though it would be better to simply use stringByAddingPercentEscapesUsingEncoding: because it leaves the characters that are part of the URL's structure (':', '/', etc.) intact:
NSString *u = #"http://example/path/fileName_blå.pdf";
u = [u stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:u];
NSLog(#"%#", url); // http://example.com/path/fileName_bl%C3%A5.pdf
If you have an URL that is a file path you must use + (id)fileURLWithPath:(NSString *)path. For the URLWithString: method the String must contain a scheme like file:// or http://.
stringByAddingPercentEscapesUsingEncoding is deprecated.
The new way (iOS 7+) to do it is:
NSString *encoded = [raw stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLPathAllowedCharacterSet];
File path is defined by https://www.rfc-editor.org/rfc/rfc8089.
The key part is to allow characters . and / and disallow %. CharacterSet.urlPathAllowed fits the requirements.
Output with your example:
incomingString: /url/path/fileName_blå.pdf
encodedString: /url/path/fileName_bl%C3%A5.pdf
URL: /url/path/fileName_bl%C3%A5.pdf
I found also that for some North European characters, NSISOLatin1StringEncoding fits better.
- (void) testEncoding {
NSString * urlString = #"http://example/path/fileName_blå.pdf";
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSISOLatin1StringEncoding];
NSURL * url = [NSURL URLWithString:urlString];
NSLog(#"URL: %#", url);
}

Remove ".." from string representation of URL

When you have a filesystem path, you can have a ".." removed (and the previous path component removed as well) by using the stringByResolvingSymlinksInPath selector. How can I achieve the same thing for a URL? For example I start out with, say:
www.example.com/themes/themeA/../common/assetA.png
Which I need converted to:
www.example.com/themes/common/assetA.png
For a URL use the NSURL method:
- (NSURL *)standardizedURL
Returns a new URL that points to the same resource as the original URL and is an absolute path.
Example:
NSString *s = #"www.example.com/themes/themeA/../common/assetA.png";
NSURL *u = [NSURL URLWithString:s];
NSURL *su = [u standardizedURL];
NSLog(#"su: %#", su);
NSLog output:
su: www.example.com/themes/common/assetA.png
What about the following?
NSString* resolved_url
= [[[NSURL URLWithString: #"www.example.com/themes/themeA/../common/assetA.png"] standardizedURL] absoluteString];
If you want NSURL instead of NSString, remove call to absoluteString.

NSString to NSURL?

Trying to convert a string to NSURL and this is not happening.
barcodeTextLabel.text = foundCode.barcodeString;
urlToGrab = [NSString stringWithFormat:#"%#", foundCode.barcodeString]; // foundCode.barcodeString is an NSString
urlToGrab shows the following "error invalid CFStringRef"
This is how you create an NSURL from an NSString:
NSURL *url = [NSURL URLWithString:#"http://www.google.com"];
You can use following for creating the file path to url.
NSURL *yourURL = [NSURL fileURLWithPath:#"/Users/xyz/Desktop/abc.sqlite"];
If foundCode.barcodeString is the string you want as your URL, then (like the above answer) use the NSURL class method URLWithString:(NSString *).
Your code should look like:
NSURL urlToGrab = [NSURL URLWithString:foundCode.barcodeString];
Where is your error coming into to play? The way your code is, urlToGrab is an instance of NSString. I would imagine you would get an error like you described if you tried to make an HTTP request on an NSString rather than NSURL.
Swapnali patil's answer works, but I will add an explanation.
You will get a nil if the format of NSString doesn't fit file criteria for NSURL (file:///xxx/file.ext).
My needs were with loading a JPG image via URL file path to nsdata; NSURL * u=[[NSURL alloc] initWithString:fpath] returned nil, but NSURL *yourURL = [NSURL fileURLWithPath:fpath] as in mentioned answer worked. A URL for files will be file:///users/xxx/pic.jpg format and give disk access. NSURL * u=[[NSURL alloc] initWithString:(NSString*) ] will also give nil object if nsstring is web URL but if missing http://