Send Post Request Using Nsurlsession

Send POST request using NSURLSession

You could try using a NSDictionary for the params. The following will send the parameters correctly to a JSON server.

NSError *error;

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:@"[JSON SERVER"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];

[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPMethod:@"POST"];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: @"TEST IOS", @"name",
@"IOS TYPE", @"typemap",
nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request setHTTPBody:postData];


NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

}];

[postDataTask resume];

Hope this helps (I'm trying to sort a CSRF authenticity issue with the above - but it does send the params in the NSDictionary).

iOS POST request using NSURLSession

In addition to setting up your code to do a GET when you say you want to do a POST (as josemando points out in his comment), you're not starting your task.

You need to change your last line like this:

NSURLSessionDataTask *task = [[NSURLSession sharedSession] 
dataTaskWithRequest: request
completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error)
{
NSLog(@"resp: %@, err: %@", response, error);
}];
[task resume];

(dataTaskWithRequest creates and returns a data task object which you then have to submit for execution with the resume method.)

Send NSString as body of post method using NSURLSession

I ended up using the first example that I found here is my implementation:

NSURL *url = [NSURL URLWithString:@"MY_LINK/smtg"];


//Create thhe session with custom configuration
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfiguration.HTTPAdditionalHeaders = @{
@"Authorization" : [NSString stringWithFormat:@"BEARER %@",finalToken],
@"Content-Type" : @"application/json"
};

NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];

// 2
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = @"POST";

// 3

NSError *error = nil;

NSData* jsonData = [bodyContainerString dataUsingEncoding:NSUTF8StringEncoding];


if (!error) {
// 4
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request
fromData:jsonData completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
// Handle response here
}];

// 5
[uploadTask resume];
}}

Wait response for HTTP request using NSURLSession - Objective C

You can use GCD to implement synchronous request like this:

swift code

public static func requestSynchronousData(request: URLRequest) -> Data? {
var data: Data? = nil
let semaphore: DispatchSemaphore = DispatchSemaphore(value: 0)
let task = URLSession.shared.dataTask(with: request, completionHandler: {
taskData, _, error -> () in
data = taskData
if data == nil, let error = error {print(error)}
semaphore.signal()
})
task.resume()
_ = semaphore.wait(timeout: .distantFuture)
return data
}

Objective-C code

+ (NSData *)requestSynchronousData:(NSURLRequest *)request {
__block NSData * data = nil;
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable taskData, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
NSLog(@"%@", error);
}
data = taskData;
dispatch_semaphore_signal(semaphore);
}];
[task resume];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
return data;
}

You can use dispatch_async to handle UI interaction inside the block

DummyModel * dummy = [[DummyModel alloc] init];

__block ResponseModel * result = [[ResponseModel alloc] init];

[HTTPRequest sendPOSTRequest1:dummy withResponse:^(ResponseModel *data) {
result = data;
dispatch_async(dispatch_get_main_queue(), ^{
// handle some ui interaction
});
NSLog(@"data %@",data);
}];


Related Topics



Leave a reply



Submit