本APIはiOS5.0から利用可能。
第3引数completionHandlerにはデータ取得時に実行するBlock文を記述する。このBlock文は第2引数queueで指定したNSOperationQueue上で実行される。以下のコード例ではBlock文はメインスレッドで実行されることになる。
環境
- Xcode 4.6.3
- ARC ON
- iPhone 6.1 Simulator
#import <UIKit/UIKit.h> @interface ViewController : UIViewController @property (weak, nonatomic) IBOutlet UITextField *requestUrl; @property (weak, nonatomic) IBOutlet UITextField *requestBody; @property (weak, nonatomic) IBOutlet UITextView *requestResult; - (IBAction)getAsync:(id)sender; - (IBAction)postAsync:(id)sender; @end
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (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.
}
// HTTP-GET
- (IBAction)getAsync:(id)sender {
NSLog(@"%@#%@", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
// Create the url-request.
NSURL *url = [NSURL URLWithString:self.requestUrl.text];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// Set the method(HTTP-GET)
[request setHTTPMethod:@"GET"];
// Send the url-request.
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (data) {
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"result: %@", result);
self.requestResult.text = result;
} else {
NSLog(@"error: %@", error);
self.requestResult.text = [NSString stringWithFormat:@"error: %@", error];
}
}];
}
// HTTP-POST
- (IBAction)postAsync:(id)sender {
NSLog(@"%@#%@", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
// Create the url-request.
NSURL *url = [NSURL URLWithString:self.requestUrl.text];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// Set the header(s).
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
// Set the method(HTTP-POST)
[request setHTTPMethod:@"POST"];
// Set the request-body.
NSString *reqBody = self.requestBody.text;
NSLog(@"reqBody: %@", reqBody);
[request setHTTPBody:[reqBody dataUsingEncoding:NSUTF8StringEncoding]];
// Send the url-request.
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (data) {
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"result: %@", result);
self.requestResult.text = result;
} else {
NSLog(@"error: %@", error);
self.requestResult.text = [NSString stringWithFormat:@"error: %@", error];
}
}];
}
@end
0 件のコメント:
コメントを投稿