Is there any way to attach a NSDictionary of parameters to an NSURLRequest instead of manually making a string?
Asked Answered
N

3

16

AFNetworking allows you to add an NSDictionary of parameters to a request, and it will append them to the request. So if I wanted to do a GET request with ?q=8&home=8888 I'd just making an NSDictionary like @{@"q": @"8", @"home": @"8888"} very simply.

Is there a way to do this with NSURLSession / NSURLConnection / NSURLRequest?

I know I can use NSJSONSerialization for appending JSON data, but what if I just want them as GET parameters in the URL? Should I just add a category?

Numskull answered 23/1, 2014 at 4:26 Comment(2)
check i have just posted answer - its pretty simple with NSMutableURLRequestSilvio
possible duplicate of Creating URL query parameters from NSDictionary objects in ObjectiveCConsueloconsuetude
L
10

You can do this by updating the url using NSURLComponents and NSURLQueryItems. In the following example, assume that the URL parameter has already been set on an NSMutableURLRequest. You can modify it before using it to include each parameter from the NSDictionary params. Note that each parameter is encoded before it is written.

NSURLComponents *url = [[NSURLComponents alloc] initWithURL:request.URL resolvingAgainstBaseURL:YES];
NSMutableArray *queryItems = NSMutableArray.new;
[params enumerateKeysAndObjectsUsingBlock:^(NSString *name, NSString *value, BOOL *stop) {
    [queryItems addObject:[NSURLQueryItem queryItemWithName:name
                           value:[value stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLQueryAllowedCharacterSet]]];
            }];
url.queryItems = queryItems;
request.URL = url.URL;
Lapierre answered 17/9, 2015 at 19:11 Comment(0)
S
-1

TRY BELOW WORKING CODE

// Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"YOUR URL"]];

// Specify that it will be a POST request
request.HTTPMethod = @"POST";

// This is how we set header fields
[request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];


// Convert your data and set your request's HTTPBody property

NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"44",@"UserId",@"0",@"NewsArticleId",@"",@"Date", nil];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];

request.HTTPBody = jsonData;


// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
Silvio answered 23/1, 2014 at 5:13 Comment(2)
This is for a POST request, not for a GET request in where the parameters must be url encoded in the url (contrary to as data on the http body for post)Consueloconsuetude
Actually, this is working for me as I'm searching for POST request. Thanks.Grassgreen
S
-2

Example using NSURLSession:

NSURLSession *session = [NSURLSession sharedSession];
//populate json
NSDictionary *gistDict = @{@"files":@"test",@"description":@"test"};
NSError *jsonError;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:gistDict options:NSJSONWritingPrettyPrinted error:&jsonError];
//populate the json data in the setHTTPBody:jsonData    
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://yourURL"]];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:jsonData];
//Send data with the request that contains the json data 
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    // Do your stuff...
}] resume];
Sausa answered 23/1, 2014 at 6:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.