Using base64 string with NSURLConnection - ios

I am using a NSURLConnect call and I get unsupported URL when I have a space in my query string. To fix this I converted the string to base64 and I am still getting errors. How do I send a base64 string though NSUrlConnect successfully? If this isn't possible, how do I safely send a string with a space in it?
NSData *convertData = [queryWS dataUsingEncoding: NSUnicodeStringEncoding];
queryWS = [convertData base64EncodedStringWithOptions:kNilOptions];
NSURLRequest *urlRequest =
[NSURLRequest requestWithURL:[NSURL URLWithString:queryWS]];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
if (!error) {
responseDictionary =
[NSJSONSerialization JSONObjectWithData:data
options:0
error:&parseError];

You do not want to convert the URL string to base64 encoding. What you want is to properly escape any special characters in the URL. Please see the NSString stringByAddingPercentEscapesUsingEncoding: method or NSString stringByAddingPercentEncodingWithAllowedCharacters: if you only need to support iOS 9 or later.

NSString *queryString = #"SOME_QUERY_STRING";
NSString *encodedQueryString = [queryString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

Related

Objective - C stringByAddingPercentEncodingWithAllowedCharacters not working

I have a URL like so ANC & SHO.pdf
when I encode the URL like so:
NSString *escapedString = [PDFPath stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
now when I use this URL it does not work and I have a feeling it has to do with the & because when I tried another file, it worked perfectly I was able to load the PDF, but with the file with & I was not.
What Am I doing wrong?
Here is the output of escapedString
escapedString __NSCFString * #"Ancaster%5CANC%20&%20SHO%20-%20Laundry%20Closets%20to%20be%20Checked.pdf" 0x16ea33c0
I then use that to call a method:
NSArray *byteArray = [dataSource.areaData GetPDFFileData:[NSString stringWithFormat:#"%#",escapedString]];
Here is the method:
-(NSArray *)GetPDFFileData:(NSString *)PDFFile
{
NSString *FileBrowserRequestString = [NSString stringWithFormat:#"%#?PDFFile=%#",kIP,PDFFile];
NSURL *JSONURL = [NSURL URLWithString:FileBrowserRequestString];
NSURLResponse* response = nil;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:JSONURL];
NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
if(data == nil)
return nil;
NSError *myError;
NSArray *tableArray = [[NSArray alloc]initWithArray:[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&myError]];
return tableArray;
}
[NSCharacterSet URLHostAllowedCharacterSet] contains characters below:
!$&'()*+,-.0123456789:;=ABCDEFGHIJKLMNOPQRSTUVWXYZ[]_abcdefghijklmnopqrstuvwxyz~
which contains '&', so
NSString *escapedString = [PDFPath stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
won't escape '&' for you, then it's not URLEncoded.
see the question about how to url encode a string.

NSURL returning nil When Calling an API

I'm trying to call an API and bring back menu items. My string seems to contain data because when I put it into a browser, I'm getting JSON.
NSString *urlString = [NSString stringWithFormat:#"https://api.nutritionix.com/v1_1/search/subway?results=0%3A20&cal_min=0&cal_max=50000&fields=item_name%2Cbrand_name%2Citem_id%2Cbrand_id&appId=MY_APP_ID&appKey=MY_APP_KEY"];
NSURL *url = [NSURL URLWithString:urlString];
My "urlString" contains a lot of information, but when I put a breakpoint on the NSURL object, it says it returns "nil".
EDIT: Removed spaces however the error persists.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:#"GET"];
[request setURL:[NSURL URLWithString:urlString]];
NSHTTPURLResponse *responseCode = nil;
NSError *error = [[NSError alloc] init];
NSData *ResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:ResponseData options:kNilOptions error:nil];
itemName = dataDictionary[#"item_name"];
NSLog(#"%#", itemName);
EDIT: Added request code
Ok, I have found something interesting about your url
You just forgot about string format. Every percent sign cry to you: 'I want to be replaced with something you gain to me!'
So, to prevent such behavior, you need to hide every percent with another percent: %%
-(void)doNSURLTestOne{
NSString *urlString = [NSString stringWithFormat:#"https://api.nutritionix.com/v1_1/search/subway?results=0%%3A20&cal_min=0&cal_max=50000&fields=item_name%%2Cbrand_name%%2Citem_id%%2Cbrand_id&appId=MY_APP_ID&appKey=MY_APP_KEY"];
NSURL *url = [NSURL URLWithString:urlString];
NSLog(#"is url nil? %#", url);
NSLog(#"is urlString ok? %#", urlString);
}
But I prefer to use AFNetworking library for net part
UPD: better choice to use another clean NSString ( thanks #rmaddy )
-(void)doNSURLTestTwo{
NSString *urlString = #"https://api.nutritionix.com/v1_1/search/subway?results=0%3A20&cal_min=0&cal_max=50000&fields=item_name%2Cbrand_name%2Citem_id%2Cbrand_id&appId=MY_APP_ID&appKey=MY_APP_KEY";
NSURL *url = [NSURL URLWithString:urlString];
NSLog(#"is url nil? %#", url);
NSLog(#"is urlString ok? %#", urlString);
}

NSString convert string to NSData using encoding

I have got small issue in my app.
I make NSMutableURLRequest and send body to my webserice.
jsonRequest = #"{\"s\":\"deón\"}";
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
I need change "ó" symbol to \u00F3.
Any idea?
I would suggest you another way around if you want to deploy on target >=iOS5. It involves more steps, but you can be sure about the correct result, it's less error prone.
NSDictionary * jsonDict = #{ #"s" : #"deón" };
NSData * requestData = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:nil];
convert in UTF-8
NSData *data = [arrayString dataUsingEncoding:NSUTF8StringEncoding];
Try this code it will near to your requirement
NSString *jsonRequest = #"{\"s\":\"deón\"}";
const char *c = [jsonRequest cStringUsingEncoding:NSISOLatin1StringEncoding];

Json crash when sending space and dot

I am trying to request a URL and I am getting error saying
"Data parameter is nil".
I had found that the variables used has got space dot(.). I think this is the problem that is being caused by the URL. So is there any way to send URL having space and dot without crashing?
NSURL *url = [[NSURL alloc]initWithString:[NSString stringWithFormat:#"192.168.1.5/mobileapp?/signin=%#&%#",username,password]];
NSError *errors;
NSData *data = [NSData dataWithContentsOfURL:url];
NSDictionary *json = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errors];
Try using NSUTF8StringEncoding
NSString *myUnencodedString = [NSString stringWithFormat:#"192.168.1.5/mobileapp?/signin=%#&%#",username,password]
NSString *encodedString = [myUnencodedString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *myURL = [[NSURL alloc] initWithString:encodedString]

How to request url which has space and dot in ios?

I am trying to request the following URL and i am getting an error saying "Data parameter is nil". i had found that the 'seller_name' has got space and 'amount' has got dot(.). I think this is the problem that is being caused by the URL. So is there any way to send URL having space and dot without loosing the information?
NSURL *url1 = [[NSURL alloc]initWithString:[NSString stringWithFormat:#"192.168.1.85/localex_postsale.html?contactid=%#&exchangeid=%#&token=%#&buyerid=%#&seller_name=%#&desc=%#&amount=%#&sellerid=%#",contactid,exchangeid,token,buyervalue,sellers,_Description,_Amount,contactid]];
NSError *errors1;
NSData *data1 = [NSData dataWithContentsOfURL:url1];
NSDictionary *json1 = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:data1 options:kNilOptions error:&errors1];
Take a look at the -stringByAddingPercentEscapesUsingEncoding: method in NSString, e.g.:
NSString *myUnencodedString = [NSString stringWithFormat:#"192.168.1.85/localex_postsale.html?contactid=%#&exchangeid=%#&token=%#&buyerid=%#&seller_name=%#&desc=%#&amount=%#&sellerid=%#",contactid,exchangeid,token,buyervalue,sellers,_Description,_Amount,contactid]
NSString *encodedString = [myUnencodedString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *myURL = [[NSURL alloc] initWithString:encodedString]
...
Cf.: Apple documentation.
It is happening because URL should not contain white space. It should be encode to %20 if there is any space. We can encode space and special character in NSString using NSUTF8StringEncoding as below
NSString *string = [[NSString stringWithFormat:#"192.168.1.85/localex_postsale.html?contactid=%#&exchangeid=%#&token=%#&buyerid=%#&seller_name=%#&desc=%#&amount=%#&sellerid=%#",contactid,exchangeid,token,buyervalue,sellers,_Description,_Amount,contactid]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url1 = [[NSURL alloc]initWithString:string];
NSError *errors1;
NSData *data1 = [NSData dataWithContentsOfURL:url1];
NSDictionary *json1 = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:data1 options:kNilOptions error:&errors1];

Resources