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.
Related
This question already has answers here:
NSURL returns Nil Value
(2 answers)
Closed 8 years ago.
I am passing NSString to NSURL and app crashes. I think this is due to 's used in NSString
NSLog of the NSString is
http://www.test.com/?AssessmentID=040714114412 &QuestionID=113&ResponseText=yes&AssessmentName=Housekeeping&AssessmentDate=11:44:21&AssessmentQuestion=Use the guest’s or employee’s name.&ResponseComment=No comment&DepartmentID=9&SectionName=Service Standards
here is the exception
[NSURL initWithString:relativeToURL:]: nil string parameter'
I think it is crashing due to guest's 's
The problem is your URL is not properly encoded. Take this & modify your code accordingly.
NSString *relativeURL = #"http://www.something with Space and parameters";
NSURL *url = [NSURL URLWithString:[relativeURL stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];
This is the right approach rather than replacing white spaces with %20
Hope that helps.
Well i tried out the following piece of code and it is working for me... can you do this as per the following code!
NSString *relativeToURL = #"http://www.test.com/?AssessmentID=040714114412 &QuestionID=113&ResponseText=yes&AssessmentName=Housekeeping&AssessmentDate=11:44:21&AssessmentQuestion=Use the guest’s or employee’s name.&ResponseComment=No comment&DepartmentID=9&SectionName=Service Standards";
NSURL *url = [[NSURL alloc] initWithString:relativeToURL];
[self.webView loadRequest:[NSURLRequest requestWithURL:url]];
This question already has answers here:
How do I URL encode a string
(24 answers)
Closed 9 years ago.
As you know no URL contain a space between the word of there parameters
and I want to pass MyString=#"hello every body" to my URL parameters, like this
[#"http://www.site.com/index.php?contenu=" stringByAppendingString:MyString];
And I don't know how I can convert MyString to a valid format for URL
Try with Following Code :
NSString *urlString = [NSString stringWithFormat:#"http://www.site.com/index.php?contenu=%#", MyString];
NSURL *myURL = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
AlsoRead This Official Documentation about String Format Specifiers.
Why don't you do the whole thing in this manner ?
First make a string with parameter in the following way :
NSString *stringURL = [NSString stringWithFormat:#"http://www.site.com/index.php?contenu=%#",MyString];
Convert the string to URL :
NSURL *url = [NSURL URLWithString:MyString];
Now you can use that url safely.
for space u should use %20, for that use url encode
Try This
Or use stringByReplacingPercentEscapesUsingEncoding
You can try this by replacing space with %20
Code ::
NSString *reqString;
reqString = [NSString stringWithFormat:#"%s%#", Server_URL, your_paramater];
reqString = [reqString stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSLog(#"... URL :::: %#", reqString);
Try it once, It may be help you.
Thanks.
try like this ,
NSString *encodedUrlString = [urlString stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
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.
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);
}
I have code similar to the following with a URL like this... If I use the first *url, webpage will return null. If I put this URL into a URL shortening system like bit.ly it does work and returns the pages HTML as a string. I can only think I have invalid characters in my first *url? Any ideas?
NSString *url =#"http://www.testurl.com/testing/testapp.aspx/app.detail/params.frames.y.tpl.uk.item.1.cm_scid.TB-test/left.html.|metadrill,html/walk.yah.ukHB?cm_re=LN-_-OnNow-_-TestOne";
//above *url does not work, one below does
NSURL *url =[NSURL URLWithString: #"http://bit.ly/shortened"];
NSString *webpage = [NSString stringWithContentsOfURL:url];
You probably need to escape some characters in the first URL, as follows:
NSString *url =#"http://www.testurl.com/testing/testapp.aspx/app.detail/params.frames.y.tpl.uk.item.1.cm_scid.TB-test/left.html.|metadrill,html/walk.yah.ukHB?cm_re=LN-_-OnNow-_-TestOne";
NSString *escapedURL = [url stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSString *webpage = [NSString stringWithContentsOfURL:[NSURL URLWithString:escapedURL]];
The construction of the URL and its fetch will fail if the URL contains characters that aren't escaped properly (looking at your URL, it's probably the pipe (|), question mark, or underscore).