Objective - C stringByAddingPercentEncodingWithAllowedCharacters not working - ios

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.

Related

Using base64 string with NSURLConnection

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

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

How to get the values from json service [duplicate]

This question already has an answer here:
Parsing JSON response .
(1 answer)
Closed 8 years ago.
Hai I need to get the id & status from the service for login my code is below. please guide me to get the values.. Thanks in advance..
NSString *Username= txtUsername.text;
NSString *Password=txtPassword.text;
NSString *link = [NSString stringWithFormat:#"http://www.xxx/login.php?user=%#&pass=%#&format=json",Username,Password];
NSURL *url=[NSURL URLWithString:link];
NSData *data=[NSData dataWithContentsOfURL:url];
1st Do the jSon parsing and then get the particular value from the
key .
Before getting any value , we have to understand the tree of jSon.
Here "posts" is an NSArray ,within that one DIctionary "post" is
there ,which again contains another dictionary.
Below is the complete code.
(void)viewDidLoad
{
[super viewDidLoad];
 NSString *Username= txtUsername.text;
NSString *Password=txtPassword.text;
NSString *link =
[NSString stringWithFormat:#"http://www.some.com/webservice/login.php?user=%#&pass=%#&format=json",Username,Password];
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:
kLatestKivaLoansURL];
[self performSelectorOnMainThread:#selector(fetchedData:)
withObject:data waitUntilDone:YES];
}); }
Then call that selector fetchedData
(void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:&error];
 
if(!error){
NSArray* postArray = [json objectForKey:#“posts”]; //This is an array
if (postArray.count>0) {
NSDictionary *dict = [[postArray objectAtIndex:0] objectForKey:#"post" ];
NSString *id_ = [dict objectForKey:#"id"];
NSString *status_ = [dict objectForKey:#"status"];
}
}
}
Can you post your json string. You can use NSJSONSERIALISATION to convert data (json string ) into NSDictionary. Then use the keys to extract the values. I'm replying through mobile so I can't write the actual code.
Use Below code to parse Json in IOS
NSString *Username= txtUsername.text;
NSString *Password=txtPassword.text;
NSString *link = [NSString stringWithFormat:#"http://www.some.com/_webservice/login.php?user=%#&pass=%#&format=json",Username,Password];
NSURL *url=[NSURL URLWithString:link];
NSMutableURLRequest *req1 = [NSMutableURLRequest requestWithURL:url];
NSURLResponse *response;
NSError *error;
//getting the data
NSData *newData = [NSURLConnection sendSynchronousRequest:req1 returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:newData encoding:NSUTF8StringEncoding];
NSLog(#"basavaraj \n\n\n %# \n\n\n",responseString);
NSData* data = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&myError];
NSString *id=[res objectForKey:#"ID"];
NSString *status=[res objectForKey:#"Status"];
and if u need extra info please go through below link it may help you
Click here for more details

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