NSURL URLWithString: giving nil - iphone

Please see the below code :
UIImage *image;
NSString *str = [[[Data getInstance]arrPic]objectAtIndex:rowIndex];
NSLog(str);
NSURL *url = [NSURL URLWithString:str];
NSData *data = [NSData dataWithContentsOfURL:url];
image = [UIImage imageWithData:data];
str is giving me http://MyDomain/Pics\\1.png but url is giving me nil.

Just try using this,
[NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

From the documentation, the URLWithString: methods takes a well-formed URL string :
This method expects URLString to contain any necessary percent escape codes, which are ‘:’, ‘/’, ‘%’, ‘#’, ‘;’, and ‘#’. Note that ‘%’ escapes are translated via UTF-8.
I suggest you retry the same using NSString's (NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding; method before.

As of iOS9, stringByAddingPercentEscapesUsingEncoding is deprecated. To safely escape a URL string, use:
NSMutableCharacterSet *alphaNumSymbols = [NSMutableCharacterSet characterSetWithCharactersInString:#"~!##$&*()-_+=[]:;',/?."];
[alphaNumSymbols formUnionWithCharacterSet:[NSCharacterSet alphanumericCharacterSet]];
str = [str stringByAddingPercentEncodingWithAllowedCharacters:alphaNumSymbols];
This creates sets of characters to keep as is and asks everything outside of these CharacterSets to be converted to %percent encoded values.

Related

Pass special characters through NSURL and NSData [duplicate]

This question already has answers here:
Objective-C and Swift URL encoding
(13 answers)
Closed 9 years ago.
I just learned the hard way that you cannot pass special characters through NSURL. I am in need of a function that will help me pass characters like "&, %, ", ñ" and others via NSURL and NSData.
My code is below. You can see below that I replace the line breaks (\n) and spaces with %20. Is there a function or simple way I can have the types of characters listed above pass through NSURL? Any help would be great! Thank you!
NSString *var1_pre = [myTextView.text stringByReplacingOccurrencesOfString:#" "
withString:#"%20"];
NSString *var1 = [var1_pre stringByReplacingOccurrencesOfString:#"\n" withString:#"%20"];
NSString *strURL = [NSString stringWithFormat:#"http://www.website.com/page.php?
var1=%#",var1];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
Use
NSString *strUrl=[#"YOURURL" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url=[NSURL URLWithString:strUrl];
NSString *urlString = [NSString stringWithFormat:#"URL_STRING"];
NSURL *MyUrl = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
stringByAddingPercentEscapesUsingEncoding. convert Legal URL String.

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);
}

NSURL and URL Validity

I'm using a URL from an API where a search term is surrounded by quotation marks. For example:
http://www.example.com/searchterm="search".
However, because of the quotation marks, my NSURL (generated by URLWithString) is nil due to an invalid URL. Is there a way around this? Thanks!
You can place a backslash before the quotation mark, or the URL encoded value %22:
http://www.example.com/searchterm=\"search\"
http://www.example.com/searchterm=%22search%22
or you can remove the quotations before using it as an NSURL.
NSString * searchUrl = #"http://www.example.com/searchterm=\"search\"";
searchUrl =
[searchUrl stringByReplacingOccurrencesOfString:#"\"" withString:#""]; // something to this effect, not tested.
Then you can go about your normal NSURL call:
[NSURL URLWithString: searchUrl];
Try the following:
#define SAFARI_SEARCH_URL_FORMAT #"http://search/search?q=\"%#\""
mySearchBar.text =#"hello";
NSString * tempstr = [NSString stringWithFormat:SAFARI_SEARCH_URL_FORMAT, mySearchBar.text];
NSURL *an1Url = [[[NSURL alloc] initWithString:[tempstr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
] autorelease];
NSLog(#"--(%#)--",an1Url);
an1Url will not be nil

NSURL with string

I have problem with NSURL. I am trying to create NSURL with string
code
NSString *prefix = (#"tel://1234567890 ext. 101");
NSString *dialThis = [NSString stringWithFormat:#"%#", prefix];
NSURL *url = [[NSURL alloc] initWithString:dialThis];
NSLog(#"%#",url);
also tried
NSURL *url = [NSURL URLWithString:dialThis];
but it gives null . what is wrong ?
Thanks..
Your problem is the unescaped spaces in the URL. This, for instance, works:
NSURL *url = [NSURL URLWithString:#"tel://1234567890x101"];
Edit: As does this..
NSURL *url2 = [NSURL URLWithString:[#"tel://1234567890 ext. 101"
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
Before passing any string as URL you don't control, you have to encode the whitespace:
NSString *dialThis = [prefix stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// tel://1234567890%20ext.%20101
As a side note, iOS is not going to dial any extension. The user will have to do that manually.
From Apple URL Scheme Reference: Phone Links:
To prevent users from maliciously redirecting phone calls or changing the behavior of a phone or account, the Phone application supports most, but not all, of the special characters in the tel scheme. Specifically, if a URL contains the * or # characters, the Phone application does not attempt to dial the corresponding phone number.
Im not sure the "ext." in phone number can be replce by what value? but you can try like this,
NSString *prefix = [NSString stringWithString: #"tel://1234567890 ext. 101"];
NSString *dialThis = [NSString stringWithFormat:#"%#", prefix];
NSURL *url = [NSURL URLWithString:[dialThis stringByReplacingOccurrencesOfString:#" ext. " withString:#"#"]];
// it might also represent by the pause symbol ','.
you can go to find the ext. is equivalent to what symbol in the phone, then replace it.
but dunno it can be work in actual situation or not....
As with iOS 9.0,
stringByAddingPercentEscapesUsingEncoding:
has been deprecated.
Use the following method for converting String to NSURL.
let URL = "URL GOES HERE"
let urlString = URL.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLFragmentAllowedCharacterSet())
If you've got something you think should be a URL string but know nothing about how URL strings are supposed to be constructed, you can use NSURL's URLWithDataRepresentation:relativeToURL: method. It parses the URL string (as bytes in an NSData) and percent-encodes characters as needed. Use the NSUTF8StringEncoding for best results when converting your NSString to NSData.
NSURL *url = [NSURL URLWithDataRepresentation:[#"tel:1234567890 ext. 101" dataUsingEncoding:NSUTF8StringEncoding] relativeToURL:nil];
NSLog(#"%#",url);
creates a URL with the string 1234567890%20ext.%20101
It attempts to do the right thing. However, for best results you should find the specification for the URL scheme you using and follow it's syntax to create your URL string. For the tel scheme, that is https://www.rfc-editor.org/rfc/rfc3966.
P.S. You had "tel://" instead of "tel:" which is incorrect for a tel URL.
Try this one, It works for me....
NSString *prefix = (#"tel://1234567890 ext. 101");
NSString *dialThis = [NSString stringWithFormat:#"%#", prefix];
NSURL *url = [NSURL URLWithString:[queryString stringByReplacingOccurrencesOfString:#" " withString:#"%20"]];
NSLog(#"%#",url);
Make an extension for use in any part of the project as well:
extension String {
var asNSURL: NSURL! {
return NSURL(string: self)
}
}
From now you can use
let myString = "http://www.example.com".asNSURL
or
myString.asNSURL

NSData & NSURL - url with space having problem

I have following code in my application.
NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:pathOfThumbNail]];
pathOfThumbNail has following path
http://70.84.58.40/projects/igolf/TipThumb/GOLF 58B.jpg
When I open above path in safari browser - path is changed automatically & image is successfully displayed.
http://70.84.58.40/projects/igolf/TipThumb/GOLF%2058B.jpg
But in iPhone, due to space in path, image isn't loaded in nsdata.
Use: stringByAddingPercentEscapesUsingEncoding:
Returns a representation of the receiver using a given encoding to determine the percent escapes necessary to convert the receiver into a legal URL string.
-(NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
A representation of the receiver using encoding to determine the percent escapes necessary to convert the receiver into a legal URL string. Returns nil if encoding cannot encode a particular character
Added per request by #rule
NSString* urlText = #"70.84.58.40/projects/igolf/TipThumb/GOLF 58B.jpg";
NSString* urlTextEscaped = [urlText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString: urlTextEscaped];
NSLog(#"urlText: '%#'", urlText);
NSLog(#"urlTextEscaped: '%#'", urlTextEscaped);
NSLog(#"url: '%#'", url);
NSLog output:
urlText: '70.84.58.40/projects/igolf/TipThumb/GOLF 58B.jpg'
urlTextEscaped: '70.84.58.40/projects/igolf/TipThumb/GOLF%2058B.jpg'
url: '70.84.58.40/projects/igolf/TipThumb/GOLF%2058B.jpg'
A swift 3.0 approach (stringByAddingPercentEscapesUsingEncoding and stringByAddingPercentEncodingWithAllowedCharacters seems now deprecated):
let urlString ="your/url/".addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed)
stringByAddingPercentEscapesUsingEncoding has been deprecated in iOS 9.0, it is recommended you use stringByAddingPercentEncodingWithAllowedCharacters instead.
Here's the Objective-C code for > iOS 9.0
NSString* urlText = #"70.84.58.40/projects/igolf/TipThumb/GOLF 58B.jpg";
NSString* urlTextEscaped = [urlText stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURL *url = [NSURL URLWithString: urlTextEscaped];
NSLog(#"urlText: '%#'", urlText);
NSLog(#"urlTextEscaped: '%#'", urlTextEscaped);
NSLog(#"url: '%#'", url);