URLSession接続サンプルコード [objective-c]

URLSession接続サンプルコード [objective-c]


donald chi / 2017-03-10 11:38

音声ファイル作成中...
Audio: Visited: 1630


URLSessionのサンプルコードを書いてみた。 直接コードをのける。

@interface MyServerConnector (Private)
    -(void)alertWithMessage:(NSString *)message;
@end
@implementation MyServerConnector
@synthesize Products_MyServer;
@synthesize name;

- (void)connect2server:(NSString*)url {
    url = @"http://localhost:8081/panrolling/json.php";
    if (self.Products_MyServer !=nil) [self.Products_MyServer release];
        self.Products_MyServer = [[[NSMutableData alloc] init]retain];
        // セッション作成
        NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
        // タイムアウトの設定
        sessionConfig.timeoutIntervalForRequest  =  TIME_OUT_REQUEST;
        sessionConfig.timeoutIntervalForResource =  TIME_OUT_RESOURCE;  
        // 通信設定
        self->sessionConnect = [NSURLSession sessionWithConfiguration: sessionConfig delegate: self delegateQueue: [NSOperationQueue mainQueue]];
        // Header 作成
        NSMutableURLRequest *request = [NSMutableURLRequest new];
        [request setURL            :[NSURL URLWithString:url]];
        [request setHTTPMethod     :@"GET"];
        [request setValue:@"application/json; charaset=utf-8" forHTTPHeaderField: @"Content-Type"];
        NSURLSessionDataTask *dataTask =  [self->sessionConnect dataTaskWithRequest:request];
        //接続開始
        [dataTask resume];
}
- (void)URLSession:(NSURLSession *)session
    dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler{
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
    if(httpResponse.statusCode == 200) {
        completionHandler(NSURLSessionResponseAllow); //続ける
    } else {
        // error.code = -999で終了メソッドが呼ばれる
        completionHandler(NSURLSessionResponseCancel); //止める
    }
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
    // 受信データ格納
    [self.Products_MyServer appendData:data];
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
    if (!error) {
        //
        // 正常終了
        //
    NSLog(@"Complete!");
    } else {
        NSLog(@"Error: %@", error);
        //
        // エラー終了
        //
    }
    [session invalidateAndCancel];
}
- (void)alertWithMessage:(NSString *)message {
    NSLog(@"message");
}
- (void)dealloc {
    [Products_MyServer release];
    [super dealloc];
}
@end

0

0

Share with: Facebook Twitter Google+ LinkedIn Wechat Email Print

Comments: 0 件

There is no Comment now.

Add Comment

Name:
Email:
Comment: