url encoding issue in iOS7 - ios

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];

Related

Trying to send html email body in Outlook but it is broken if the body has the character "&". iOS,Objective c

I am trying to open the Html body via outlook URL but the body is broken if some special character is present on the body example: &nbsp,&,&amp etc.
So I have tried "stringByAddingPercentEncodingWithAllowedCharacters" but still no luck.
It is working if I replace the character "&" with "and", but we need to show "&" in the body.
below is my piece code:
NSString *strTest = [NSString stringWithFormat:#"ms-outlook://compose?to=%#&subject=%#&body=%#", emailTo,emailSubject,emailBody];
NSURL *openurlTest = [NSURL URLWithString:[strTest stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURL *openurl = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
if ([[UIApplication sharedApplication] canOpenURL:openurlTest]) {
if ([[UIApplication sharedApplication] canOpenURL:openurlTest]) {
[[UIApplication sharedApplication] openURL:openurlTest options:#{} completionHandler:nil];
}
}
Instead of constructing the URL using string formatting, I'd recommend using NSURLComponents in conjunction with NSURLQueryItem which will "do the right thing" as far as proper encoding.
NSString *sampleBody = #"Ampersand & and more reserved characters !*'();:#&=+$,/?%#[]";
NSURLComponents *components = [[NSURLComponents alloc] initWithString:#"ms-outlook://compose"];
NSURLQueryItem *toItem = [[NSURLQueryItem alloc] initWithName:#"to" value:#"test#email.com"];
NSURLQueryItem *subjectItem = [[NSURLQueryItem alloc] initWithName:#"subject" value:#"Test Subject"];
NSURLQueryItem *bodyItem = [[NSURLQueryItem alloc] initWithName:#"body" value:sampleBody];
components.queryItems = #[toItem, subjectItem, bodyItem];
NSLog(#"Constructed URL = %#", [components.URL absoluteString]);
Which outputs:
ms-outlook://compose?to=test#email.com&subject=Test%20Subject&body=Ampersand%20%26%20and%20more%20reserved%20characters%20!*'();:#%26%3D+$,/?%25%23%5B%5D
NSURLComponents: https://developer.apple.com/documentation/foundation/nsurlcomponents?language=objc
NSURLQueryItem: https://developer.apple.com/documentation/foundation/nsurlqueryitem?language=objc
NSURLComponents.queryItems: https://developer.apple.com/documentation/foundation/nsurlqueryitem?language=objc
NSURLComponents queryItems header:
// The query component as an array of NSURLQueryItems for this NSURLComponents.
//
// Each NSURLQueryItem represents a single key-value pair,
//
// Note that a name may appear more than once in a single query string, so the name values are not guaranteed to be unique. If the NSURLComponents has an empty query component, returns an empty array. If the NSURLComponents has no query component, returns nil.
//
// The queryItems getter returns an array of NSURLQueryItems in the order in which they appear in the original query string. Any percent-encoding in a NSURLQueryItem name or value is removed.
//
// The queryItems setter combines an array containing any number of NSURLQueryItems, each of which represents a single key-value pair, into a query string and sets the NSURLComponents query property. If the NSURLQueryItems name or value strings contain any characters not allowed in a URL's query component, those characters are percent-encoded. In addition, any '&' and '=' characters in a NSURLQueryItem name are percent-encoded. Passing an empty array sets the query component of the NSURLComponents to an empty string. Passing nil removes the query component of the NSURLComponents.
//
// - note: If a NSURLQueryItem name-value pair is empty (i.e. the query string starts with '&', ends with '&', or has "&&" within it), you get a NSURLQueryItem with a zero-length name and a nil value. If a NSURLQueryItem name-value pair has nothing before the equals sign, you get a zero-length name. If a NSURLQueryItem name-value pair has nothing after the equals sign, you get a zero-length value. If a NSURLQueryItem name-value pair has no equals sign, the NSURLQueryItem name-value pair string is the name and you get a nil value.
Specifically this portion of the header is of interest for your question:
If the NSURLQueryItems name or value strings contain any characters not allowed in a URL's query component, those characters are percent-encoded. In addition, any '&' and '=' characters in a NSURLQueryItem name are percent-encoded.

How to properly form the requestString for a POST NSUrlRequest on iOS when array values are involved?

I need to form a POST NSURLRequest and I need to pass into the request this structure:
inspection (an array of NSDictionaries with string keys and values)
property (same structure as array1)
subcategories (an array of NSDictionaries where each dictionary can have an array of values for a certain key)
Here is how my requestString looks like after I concat everything:
?inspection[name]=inspection_name&inspection[address]=address_value&...&property[type]=property_type&....&subcategories[0][questions][0][title]=title_value&subcategories[0][questions][1][title]=title_value1&...&subcategories[1][questions][0][title]=title_valuen&...
For inspection and property array I've also tried inspection[][name]=inspection_name, property[][address]=property_address
While I'm forming that requestString I'm escaping each parameter using this method:
static NSString *escapeParam(NSString *param) {
param = [param stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
param = [param stringByReplacingOccurrencesOfString:#"&" withString:#"%26"];
param = [param stringByReplacingOccurrencesOfString:#"=" withString:#"%3D"];
param = [param stringByReplacingOccurrencesOfString:#"?" withString:#"%3F"];
return param;
}
There fore something like subcategories[0][questions][0][title]=title_value becomes subcategories%5B0%5D%5Bquestions%5D%5B0%5D%5Btitle%5D=title_value
Obviously I'm doing something wrong and don't know how to properly form this requestString because when I fire the request I get HTTP Error 400 Bad request in response.
Can someone point me in the right direction?
Thanks a bunch!
First of all &,=,? don't need to be encoded, these chars are supported.
Second of all, you don't need to add stringByAddingPercentEscapesUsingEncoding to the whole body, I think you don't need to add it at all because the server should support escaping chars. If the server doesn't support escaping chars, you should apply the stringByAddingPercentEscapesUsingEncoding only on the values, the keys should be as tehy are, something like
inspection[][name]=[inspection_name stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
This will handle eventual escaping chars from your values, but the keys should't have escaping characters since they are created to work on the server.

NSString separation-iOS

I have following strings. But I need to separate them by this "jsonp1343930692" and assign them NSString again. How could I that? I could able to separate them to NSArray but I don't know how to separate to NSString.
jsonp1343930692("snapshot":[{"timestamp":1349143800,"data":[{"label_id":10,"lat":29.7161,"lng":-95.3906,"attr":{"ozone_level":37,"exp":"IN","gridpoint":"29.72:-95.39"}},{"label_id":10,"lat":30.168456,"lng":-95.50448}]}]})
jsonp1343930692("snapshot":[{"timestamp":1349144700,"data":[{"label_id":10,"lat":29.7161,"lng":-95.3906,"attr":{"ozone_level":37,"exp":"IN","gridpoint":"29.72:-95.39"}},{"label_id":10,"lat":30.168456,"lng":-95.50448,"attr":{"ozone_level":57,"exp":"IN","gridpoint":"30.17:-95.5"}},{"label_id":10,"lat":29.036944,"lng":-95.438333}]}]})
The jsonp1343930692 prefix in your string is odd: I don't know where you string come from, but it really seems to be some JSON string with this strange prefix that has no reason to be there. The best shot here is probably to check if it is normal to have this prefix, for example if you get this string from a WebService it is probably the WebService fault to return this odd prefix.
Anyway, if you want to remove the jsonp1343930692 prefix of your string, you have multiple options:
Check that the prefix is existant, and if so, remove the right number of characters from the original string:
NSString* str = ... // your string with the "jsonp1343930692" prefix
static NSString* kStringToRemove = #"jsonp1343930692";
if ([str hasPrefix:kStringToRemove])
{
// rebuilt a string by only using the substring after the prefix
str = [str substringFromIndex:kStringToRemove.length];
}
Split your string in multiple parts, using the jsonp1343930692 string as a separator
NSString* str = ... // your string with the "jsonp1343930692" prefix
static NSString* kStringToRemove = #"jsonp1343930692";
NSArray* parts = [str componentsSeparatedByString:kStringToRemove];
str = [parts componentsJoinedByString:#""];
Replace every occurrences of jsonp1343930692 by the empty string.
NSString* str = ... // your string with the "jsonp1343930692" prefix
static NSString* kStringToRemove = #"jsonp1343930692";
str = [str stringByReplacingOccurrencesOfString:kStringToRemove withString:#""];
So in short you have many possibilities depending on what exactly you want to do :)
Of course, once you have removed your strange jsonp1343930692 prefix, you can deserialize your JSON string to obtain a JSON object (either using some third-party lib like SBJSON or using NSJSONSerializer on iOS5 and later, etc)
Have a look at the NSJSONSerialization class to turn this into a Cocoa collection that you can deal with.

ios - problems after encoding a url string

I have some code to send a url to a remote server. If I do not encode the url, it works perfectly. But if I encode the url, it does not work. So I am pretty sure something is not right with the way I encode the url query string.
Here is my code:
// URL TO BE SUBMITTED.
NSString *urlString =
#"http://www.mydomain.com/test.php?";
// NOW CREATE URL QUERY STRING
NSString *unencoded_query_string =
#"name=%#&user_id=%#&person_name=%#&person_email=%#&privacy=%#";
// PUT PREVIOUSLY SET VALUES INTO THE QUERY STRING
NSString *unencoded_url_with_params =
[NSString stringWithFormat:unencoded_query_string, business , user_id , name , email , privacy_string];
// ENCODE THE QUERY STRING
NSString *escapedString = (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL,
(__bridge CFStringRef)unencoded_url_with_params,
NULL,
(CFStringRef)#"!*'();:#&=+$,/?%#[]",
kCFStringEncodingUTF8);
// NOW APPEND URL TO QUERY STRING
NSString *full_encoded_url_string =
[urlString stringByAppendingString: escapedString];
and then I send this string to the server, and the server does have the correct request file invoked, but isn't able to read the parameters.
Would anyone know what I doing incorrectly here? I am using arc by the way.
Thanks!
I think you probably want to escape each param, not the entire request. Basically you want to escape ampersands, spaces etc that show up in your get variables. Your encoded URL probably looks like this:
http://www.mydomain.com/test.php?name%3DPeter%20Willsey%26user_id%3DUSERID%26person_name%3DPeter%20Willsey%26person_email%3Dpeter%40test.com%26privacy%3D1
and it should look like this:
http://www.mydomain.com/test.php?name=Peter%20Willsey&user_id=25&person_name=Peter%20Willsey&person_email=peter%40test.com&privacy=1

How to handle spaces in search term

I am implementing a search using the following code snippet.
-(void)getData:(NSString *)searchString
{
//Search string is the string the user keys in as keywords for the search. In this case I am testing with the keywords "epic headline"
searchString = [searchString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *resourcePath = [NSString stringWithFormat:#"/sm/search?limit=100&term=%#&types[]=users&types[]=questions&types[]=topics",searchString];
[self sendRequests:resourcePath];
}
//URL sent to server as a result
send Request /sm/search?limit=100&term=epic headline&types[]=users&types[]=questions&types[]=topics
My search is not working as it is unable to handle the space between 'epic' and 'headline'. How can I modify the search term so that the spacing can be handled?
Call stringByAddingPercentEscapesUsingEncoding on the result string to encode space characters as requiredby the rules of URLs.

Resources