diacritics signs in url AFNetworking GET - ios

I have problem which drives me crazy. My API provider has url with diacritics signs e.g:
NSString *url = #"http://apiprovideraddress.com/user?param_id=sdn-ło-13/z" // ł - diacritic sign
If in url address exists any diacritic sign then "AFNetworking" return in this function NSParameterAssert which breaks code:
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(id)parameters
error:(NSError *__autoreleasing *)error
NSParameterAssert(URLString) //URLString = nil
Stack:
[AFHTTPRequestSerializer requestWithMethod:URLString:parameters:error:]
[AFHTTPRequestOperationManager GET:parameters:success:failure:]
I'm using this function to "GET":
[myManager GET:url parameters:nil success:failure:];
If an "url" is without diacritic then everything works fine. Any ideas?

From RFC 3986: When a new URI scheme defines a component that represents textual data consisting of characters from the Universal Character Set [UCS], the data should first be encoded as octets according to the UTF-8 character encoding [STD63]; then only those octets that do not correspond to characters in the unreserved set should be percent encoded. For example, the character A would be represented as "A", the character LATIN CAPITAL LETTER A WITH GRAVE would be represented as "%C3%80", and the character KATAKANA LETTER A would be represented as "%E3%82%A2".
Use stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding to encode the URL, it will do the right thing with UTF-8 non-ASCII characters.
Example:
NSString *urlString = #"http://apiprovideraddress.com/user?param_id=sdn-ło-13/z"; // ł - diacritic sign
NSLog(#"urlString: %#", urlString);
NSString *s = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"s: %#", s);
NSLog output:
urlString: http://apiprovideraddress.com/user?param_id=sdn-ło-13/z
s: http://apiprovideraddress.com/user?param_id=sdn-%C5%82o-13/z
Note: stringByAddingPercentEscapesUsingEncoding: is known to omit some escapes that are optional.
A more conservative answer to this particular URL is:
http%3A%2F%2Fapiprovideraddress.com%2Fuser%3Fparam_id%3Dsdn-%C5%82o-13%2Fz

URIs can only contain ACSII characters. They may not contain Unicode characters.
RFC3986

Those are the parameters of the requests, you can pass them in the parameter parameter, as a NSDictionary
something like
#{
#"param_id" : #"sdn-ło-13/z"
}

Related

how to print € symbol with star micronics?

i have star micronics and im implementing SDK in my app, but i cant print the € symbol
[mutableData appendData:[#"\x1b\x1d\x74\x04 123" dataUsingEncoding:NSMacOSRomanStringEncoding allowLossyConversion:YES]];
but print other character
also try with
[mutableData appendData:[#"\xE2\x82\xac\r\n 123" dataUsingEncoding: NSUTF8StringEncoding allowLossyConversion:YES]];
someone knows what is the code to print it?
This will do the trick:
builder is your ISCBBuilder variable.
builder.append(.CP858)
builder.appendByte(0xd5)
NSString in Objective-C is internally encoded as UTF-16, and the euro symbol has code 0x20AC. So first you need to define your string like so:
NSString *euroSymbol1 = #"\u20AC";
NSString *euroSymbol2 = #"€"; // same as euroSymbol1
if ([euroSymbol1 isEqualToString:euroSymbol2])
NSLog(#"equivalent"); // this is printed
NSString *price = [NSString stringWithFormat:#"%# %.2f", euroSymbol1, 123.45];
NSLog(#"%#", price); // prints: "€ 123.45"
Note that if you just write "€" the compiler is smart to re-encode your source code encoding to the NSString encoding, so it is trivial to read.
Then you need to understand what encoding does your printer support. If it supports Unicode, you should try it first, because it definitely contains the euro symbol. Note that the whole mutableData must be in the same encoding, so if you have appended other strings before this one, you need to make sure that all of them use the same encoding (for example NSUTF8StringEncoding).
If you need to use NSMacOSRomanStringEncoding, then the euro symbol might not be supported (see this reply), although here in the table you can still see it under the code 219.

NSURL encoding with special characters

I am trying to submit a request using NSURL to the following:
http://api.allsaints.com/v1/product/?category=Women's Knitwear
when putting this URL in a browser with the ' and the space int the category, the browser (chrome) is modifying the request to:
http://api.allsaints.com/v1/product/?category=Women%27s%20Knitwear which works.
However, I can not get the right encoding to work as part of a NSURL and NSDATA request on iOS. I tried various encoding using stringByAddingPercentEscapesUsingEncoding to normalise the URL but it keep on failing.
Can someone point me in the right direction to an encoding that not only swaps the space to a %20 but also swaps the ' to a %27?
Refer to NSString stringByAddingPercentEscapesUsingEncoding: you should use CFURLCreateStringByAddingPercentEscapes to custom which character you want to escape.
- (NSString *) urlencodeStr:(NSString *)str
{
return (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
NULL,
(__bridge CFStringRef) str,
NULL,
CFSTR("!*'();:#+$,/?%#[]"),
kCFStringEncodingUTF8));
}
CFSTR("!*'();:#+$,/?%#[]") contains the characters will be escaped.

Xcode - UTF-8 String Encoding

I have a strange problem encoding my String
For example:
NSString *str = #"\u0e09\u0e31\u0e19\u0e23\u0e31\u0e01\u0e04\u0e38\u0e13";
NSString *utf = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog("utf: %#", utf);
This worked perfectly in log
utf: ฉันรักคุณ
But, when I try using my string that I parsed from JSON with the same string:
//str is string parse from JSON
NSString *str = [spaces stringByReplacingOccurrencesOfString:#"U" withString:#"u"];
NSLog("str: %#, str);
NSString *utf = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog("utf: %#", utf);
This didn't work in log
str: \u0e09\u0e31\u0e19\u0e23\u0e31\u0e01\u0e04\u0e38\u0e13
utf: \u0e09\u0e31\u0e19\u0e23\u0e31\u0e01\u0e04\u0e38\u0e13
I have been finding the answer for hours but still have no clue
Any would be very much appreciated! Thanks!
The string returned by JSON is actually different - it contains escaped backslashes (for each "\" you see when printing out the JSON string, what it actually contains is #"\").
In contrast, your manually created string already consists of "ฉันรักคุณ" from the beginning. You do not insert backslash characters - instead, #"\u0e09" (et. al.) is a single code point.
You could replace this line
NSString *utf = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
with this line
NSString *utf = str;
and your example output would not change. The stringByReplacingPercentEscapesUsingEncoding: refers to a different kind of escaping. See here about percent encoding.
What you need to actually do, is parse the string for string representations of unicode code points. Here is a link to one potential solution: Using Objective C/Cocoa to unescape unicode characters. However, I would advise you to check out the JSON library you are using (if you are using one) - it's likely that they provide some way to handle this for you transparently. E.g. JSONkit does.

url encoding issue in iOS7

I am having a link that i want to post the data.
I am using url encoding like,
http://admin:testsite#www.arabcircleonline.com/index.php?%#=%#",form_urlencode_rfc3986(#"do"),form_urlencode_rfc3986(#"/webservice/whisper/login_chauhankevalp#gmail.com/password_keval/action_whisper/whisperdata_{\"user_status\":\"last123\",\"privacy\":0,\"privacy_comment\":0}
This is giving the response intended when a record should be added, but the record is not getting added, when i execute this link on browser, it works fine.
Please help me out of this.. i am working on this last 2 days with no solution
form_urlencode_rfc3986 method i am using is,
NSString* form_urlencode_rfc3986(NSString* s) {
CFStringRef charactersToLeaveUnescaped = CFSTR(" ");
CFStringRef legalURLCharactersToBeEscaped = CFSTR("/%&=?$#+-~#<>|\\*,.()[]{}^!");
NSString *result = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault,(__bridge CFStringRef)s,charactersToLeaveUnescaped,legalURLCharactersToBeEscaped, kCFStringEncodingUTF8));
return [result stringByReplacingOccurrencesOfString:#" " withString:#"+"];
}
You are probably trying to do this:
You have a url with a query. The query component is separated by a "?" as illustrated below:
URL := scheme-authority-path "?" query
In your case "scheme-authority-path" is
http://admin:testsite#www.arabcircleonline.com/index.php,
and a "query" is a list of parameters, separated by a "&".
Your URL string without query (scheme, authority and path):
NSString* urlString = #"http://admin:testsite#www.arabcircleonline.com/index.php";
Compose a parameter (which is part of the query), e.g. in BNF
parameter := name "=" value
NOTE: name and value need to be encoded with the helper function.
which corresponds in code:
NSString* parameterString = [NSString stringWithFormat:#"%#=%#",
form_urlencode_rfc3986(#"do"),
form_urlencode_rfc3986(
#"/webservice/whisper/login_chauhankevalp#gmail.com/password_keval/action_whisper/whisperdata_{\"user_status\":\"last123\",\"privacy\":0,\"privacy_comment\":0")
];
A query string is composed by concatenating (encoded) parameters and separating them by a "&", e.g. in BNF:
query := parameter ["&" parameter]
You have only one parameter, thus our query string becomes just the parameter string:
NSString* queryString = parameterString;
Now, compose the complete url string (including the query) from the former urlString (scheme, authority and path) and the query, by concatenating urlString, a "?" and the query. For example:
NSString* urlStringWithQuery = [NSString stringWithFormat:#"%#?%#", urlString, queryString];

iOS : How to do proper URL encoding?

I'm unable to open a URL into UIWebView so I've seached & found that I need to encode URL, so I tried to encode it but, I've facing problem in URL encoding : My URL is http://somedomain.com/data/Témp%20Page%20-%20Open.html (It's not real URL).
I'm concerned with %20 that I tried to replace using stringByReplacingOccuranceOfString:#"" withString:#"" , it give me the URL I wanted like http://somedomain.com/data/Témp Page - Open.html However its not opening in UIWebView but amazingly it opens in Safari & FireFox perfect. Even I open unencoded URL its automatically converts and open the page I'm looking for.
I've google for URL encoding & it points me to different results I already checked but no results help me out!! I tried different functions answers in different URL encoding question but it just changed all special characters and make my URL like, http%3A%2F%2Fsomedomain.com%2Fdata%2FT... which can't open in UIWebView and even in any browser.
It gives the following Error Log in UIWebView delegate
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error { }
Error Code : 101
& Description : Error Domain=WebKitErrorDomain Code=101 "The operation couldn’t be completed. (WebKitErrorDomain error 101.)" UserInfo=0x6e4cf60 {}
The answer #Dhaval Vaishnani provided is only partially correct. This method treats the ?, = and & characters as not to be encoded, since they're valid in an URL. Thus, to encode an arbitrary string to be safely used as a part of an URL, you can't use this method. Instead you have to fall back to using CoreFoundation and CFURLRef:
NSString *unsafeString = #"this &string= confuses ? the InTeRwEbZ";
CFStringRef safeString = CFURLCreateStringByAddingPercentEscapes (
NULL,
(CFStringRef)unsafeString,
NULL,
CFSTR("/%&=?$#+-~#<>|\\*,.()[]{}^!"),
kCFStringEncodingUTF8
);
Don't forget to dispose of the ownership of the resulting string using CFRelease(safeString);.
Also, it seems that despite the title, OP is looking for decoding and not encoding a string. CFURLRef has another, similar function call to be used for that:
NSString *escapedString = #"%32%65BCDEFGH";
CFStringRef unescapedString = CFURLCreateStringByReplacingPercentEscapesUsingEncoding (
NULL,
(CFStringRef)escapedString,
CFSTR(""),
kCFStringEncodingUTF8
);
Again, don't forget proper memory management.
I did some tests and I think the problem is not really with the UIWebView but instead that NSURL won't accept the URL because of the é in "Témp" is not encoded properly. This will cause +[NSURLRequest requestWithURL:] and -[NSURL URLWithString:] to return nil as the string contains a malformed URL. I guess that you then end up using a nil request with -[UIViewWeb loadRequest:] which is no good.
Example:
NSLog(#"URL with é: %#", [NSURL URLWithString:#"http://host/Témp"]);
NSLog(#"URL with encoded é: %#", [NSURL URLWithString:#"http://host/T%C3%A9mp"]);
Output:
2012-10-02 12:02:56.366 test[73164:c07] URL with é: (null)
2012-10-02 12:02:56.368 test[73164:c07] URL with encoded é: http://host/T%C3%A9mp
If you really really want to borrow the graceful handling of malformed URLs that WebKit has and don't want to implement it yourself you can do something like this but it is very ugly:
UIWebView *webView = [[[UIWebView alloc]
initWithFrame:self.view.frame]
autorelease];
NSString *url = #"http://www.httpdump.com/texis/browserinfo/Témp.html";
[webView loadHTMLString:[NSString stringWithFormat:
#"<script>window.location=%#;</script>",
[[[NSString alloc]
initWithData:[NSJSONSerialization
dataWithJSONObject:url
options:NSJSONReadingAllowFragments
error:NULL]
encoding:NSUTF8StringEncoding]
autorelease]]
baseURL:nil];
The most straightforward way is to use:
NSString *encodedString = [rawString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
iDhaval was close, but he was doing it the other way around (decoding instead of encoding).
Anand's way would work, but you'll most likely have to replace more characters than spaces and new lines. See the reference here:
http://en.wikipedia.org/wiki/Percent-encoding#Percent-encoding_reserved_characters
Hope that helps.
It's very simple to encode the URL in iPhone. It is as following
NSString* strURL = #"http://somedomain.com/data/Témp Page - Open.html";
NSURL* url = [NSURL URLWithString:[strURL stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
It's a perfect way to encode the URL, I am using it and it's perfectly work with me.
Hope it will help you!!!
This may useful to someone who's reach to this question for URL encoding, as my question likely different which has been solved and accepted, this is the way I used to do encoding,
-(NSString *)encodeURL:(NSString *)urlString
{
CFStringRef newString = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)urlString, NULL, CFSTR("!*'();:#&=+#,/?#[]"), kCFStringEncodingUTF8);
return (NSString *)CFBridgingRelease(newString);
}
You can try this
NSString *url = #"http://www.abc.com/param=Hi how are you";
NSString* encodedUrl = [url stringByAddingPercentEscapesUsingEncoding:
NSASCIIStringEncoding];
I think this will work for you
[strUrl stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLQueryAllowedCharacterSet]
the Native method for URL Encoding.
Swift 4.x
let originalString = "https://www.somedomain.com/folder/some cool file.jpg"
let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
print(escapedString!)
You probably need to break the URL down into it's constituent parts and then URL encode the host and path but not the scheme. Then put it back together again.
Create an NSURL with the string and then use the methods on it such as host, scheme, path, query, etc to pull it apart. Then use CFURLCreateStringByAddingPercentEscapes to encode the parts and then you can put them back together again into a new NSURL.
can you please Try this out.
//yourURL contains your Encoded URL
yourURL = [yourURL stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
yourURL = [yourURL stringByReplacingOccurrencesOfString:#"\n" withString:#""];
NSLog(#"Keyword:%# is this",yourURL);
I am not sure,but I have solved using this in my case.
Hope this will solve yours.

Resources