Skip to content

Instantly share code, notes, and snippets.

@wwwins
Created October 23, 2014 09:18
Show Gist options
  • Save wwwins/c142da5a10129a810221 to your computer and use it in GitHub Desktop.
Save wwwins/c142da5a10129a810221 to your computer and use it in GitHub Desktop.
NSURLSession sample code
//
// NSURLSessionDemoViewController.m
// NSURLSessionDemo
//
// Created by wwwins on 2014/10/23.
// Copyright (c) 2014年 isobar. All rights reserved.
//
#import "NSURLSessionDemoViewController.h"
//#define JSON_REQUEST
#define URL_FORM_REQUEST
@interface NSURLSessionDemoViewController ()
@end
@implementation NSURLSessionDemoViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)clicked:(id)sender
{
// URL of the endpoint we're going to contact.
NSURL *url = [NSURL URLWithString:@"http://your.server.com/app/api/register.ashx"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
#ifdef JSON_REQUEST
// Create a simple post dictionary.
NSDictionary *postDictionary = @{
@"Mobile": @"0933123456",
@"Email": @"aa@bb.cc"
};
// Convert the dictionary into JSON data.
NSData *JSONData = [NSJSONSerialization dataWithJSONObject:postDictionary
options:0
error:nil];
// Create a POST request with our JSON as a request body.
request.HTTPMethod = @"POST";
request.HTTPBody = JSONData;
#endif
#ifdef URL_FORM_REQUEST
NSString *postString = [NSString stringWithFormat:@"Mobile=%@&Email=%@",@"0933123456", @"aa@bb.cc"];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-type"];
request.HTTPBody = [postString dataUsingEncoding:NSUTF8StringEncoding];
#endif
// Create a task.
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (!error) {
NSLog(@"Status code: %li", (long)((NSHTTPURLResponse *)response).statusCode);
id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(@"name: %@", [result objectForKey:@"Success"]);
}
else {
NSLog(@"Error: %@", error.localizedDescription);
}
}];
// Start the task.
[task resume];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment