Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Put JSON data in NSURL

I'm trying to do something that seems like a no brainer, but for some reason isn't working.

I'm trying to make a get request for JSON data, sending a JSON 'data' parameter in the URL.

Here's the code I'm using:

NSDictionary *whatToPost= [NSDictionary dictionaryWithObjectsAndKeys:
 username, @"username", 
 password, @"password", nil];

NSString *url = [NSString stringWithFormat:@"http://domain.com/user/get?data=%@",
 [whatToPost JSONString]];
NSURL *theUrl = [NSURL URLWithString:
 [url stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//NSLog(url) will produce this:
  http://domain.com/user/get?data={"username":"test1","password":"poop"}

When I set a breakpoint, theUrl is null. I can't quite figure out why it's breaking, but I figure something about sending the {'s or "'s is breaking it. Any ideas? Should I just switch to POST?

like image 896
RyanL Avatar asked Dec 17 '22 09:12

RyanL


1 Answers

NSDictionary *whatToPost= [NSDictionary dictionaryWithObjectsAndKeys:
 username, @"username", 
 password, @"password", nil];

NSString *url = [NSString stringWithFormat:@"http://domain.com/user/get?data=%@",
 [whatToPost JSONString]];
NSURL *theUrl = [NSURL URLWithString:
 [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

you switched method

stringByAddingPercentEscapesUsingEncoding:

Returns a representation of the receiver using a given encoding to determine the percent escapes necessary to convert the receiver into a legal URL string.

by stringByReplacingPercentEscapesUsingEncoding

Returns a new string made by replacing in the receiver all percent escapes with the matching characters as determined by a given encoding.

see:
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html
http://blog.evandavey.com/2009/01/how-to-url-encode-nsstring-in-objective-c.html

like image 75
Marek Sebera Avatar answered Jan 03 '23 10:01

Marek Sebera