Skip to content

Instantly share code, notes, and snippets.

@AlexGladkov
Last active March 2, 2016 15:50
Show Gist options
  • Save AlexGladkov/46b0d13128af2347e0f9 to your computer and use it in GitHub Desktop.
Save AlexGladkov/46b0d13128af2347e0f9 to your computer and use it in GitHub Desktop.
Apple Snippet NSURLSession
-(void)URLPostRequest:(NSString *)stringData success:(void (^)(id responseDict))success failure:(void (^)(NSString *error))failure {
NSURL *url = [NSURL URLWithString:@"yoururladdresshere"]; //Set the url
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; // Set Timeout Interval = 1 minute
[request setValue:@"text/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; // Set Charset Type
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"]; // Set Packet Type
request.HTTPMethod = @"POST"; // Set Method
request.HTTPBody = [stringData dataUsingEncoding:NSUTF8StringEncoding]; // Our data to Post
// Configure Async Request
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:(id)self delegateQueue:nil];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
failure([error localizedDescription]); // return error in completion
return;
} else {
NSError *err;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&err];
success(res);
}];
[postDataTask resume]; // Call Request
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment