Spidy
Spidy

Reputation: 1146

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

Upvotes: 0

Views: 1873

Answers (2)

Alex Reynolds
Alex Reynolds

Reputation: 96937

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.

Upvotes: 7

Rahul Patel
Rahul Patel

Reputation: 5886

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

Upvotes: 0

Related Questions