iOS NSURLSession 관련

6001 단어 NSURLSession
1. 매크로 업로드 그림/요청 인터페이스를 정의하면
#define DATA(X)	[X dataUsingEncoding:NSUTF8StringEncoding]
#define kBoundary @"------------0x0x0x0x0x0x0x0x"
#define IMAGE_CONTENT  @"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r
Content-Type: image/jpeg\r
\r
" #define STRING_CONTENT @"Content-Disposition: form-data; name=\"%@\"\r
\r
" #define MULTIPART @"multipart/form-data; boundary=------------0x0x0x0x0x0x0x0x"

2. 인터페이스 루트 경로
NSString *kAFAppNetworkAPIBaseURLString = @"http://192.168.1.254:80/pmb/";

3. 그림이나 인터페이스 파라미터 포장
- (NSData *)prepareDataForUpload:(NSDictionary*)dict {
    NSArray *keys = [dict allKeys];
    NSMutableData *result = [NSMutableData data];
    
    for (int i = 0; i < [keys count]; i++) {
        id value = dict[keys[i]];
        [result appendData:[[NSString stringWithFormat:@"--%@\r
", kBoundary] dataUsingEncoding:NSUTF8StringEncoding]];                  if ([value isKindOfClass:[NSData class]]) {             // handle image data             NSString *formstring = [NSString stringWithFormat:IMAGE_CONTENT, keys[i], dict[@"fileName"]];             [result appendData: DATA(formstring)];             [result appendData:value];         } else {             // all non-image fields assumed to be strings             NSString *formstring = [NSString stringWithFormat:STRING_CONTENT, keys[i]];             [result appendData: DATA(formstring)];             [result appendData:DATA(value)];         }                  NSString *formstring = @"\r
";         [result appendData:DATA(formstring)];     }          NSString *formstring =[NSString stringWithFormat:@"--%@--\r
", kBoundary];     [result appendData:DATA(formstring)];     return result; }

4. 업로드
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self uploadFileDict:@{@"user_id":@"44", @"file":UIImagePNGRepresentation([UIImage imageNamed:@"icon41"]), @"fileName":@"icon41.png"} toUrlString:[NSString stringWithFormat:@"%@uploadPhoto", kAFAppNetworkAPIBaseURLString]];
}

- (void)uploadFileDict:(NSDictionary *)dict toUrlString:(NSString *)urlString {
    NSData *postData = [self prepareDataForUpload:dict];
    NSLog(@"#####################################################
");     NSLog(@"post:%@", postData);//[[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding]);     NSLog(@"#####################################################
");     NSURL *url = [NSURL URLWithString:urlString];     NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];          [urlRequest setHTTPMethod: @"POST"];     [urlRequest setValue:MULTIPART forHTTPHeaderField: @"Content-Type"];     //[urlRequest setHTTPBody:postData];// session data , session request body           NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];      NSURLSession *session = [NSURLSession sessionWithConfiguration:config]; #if 1      [[session uploadTaskWithRequest:urlRequest fromData:postData completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {          NSLog(@"%@", response);                    NSString *outstring = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];          NSLog(@"
1server return message:%@
", outstring);      }] resume]; #else      [[session dataTaskWithRequest:urlRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {          NSLog(@"%@", response);                    NSString *outstring = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];          NSLog(@"
2server return message:%@
", outstring);      }] resume]; #endif }

5. 요청 인터페이스
// 
- (void)changeName:(NSString *)name {
    [self normalDicPost:@{@"user_id":@"55", @"nickname":name} action:@"uploadUserInfo" selector:@selector(changeName:)];
}

- (void)normalDicPost:(NSDictionary *)param action:(NSString *)path selector:(SEL)sel {
    // 1
    NSString *paramStr = @"";
    for (NSString *key in param) {
        paramStr = [NSString stringWithFormat:@"%@&%@=%@", paramStr, key, param[key]];
    }
    paramStr = [paramStr substringFromIndex:1];
    NSData *paramData = [paramStr dataUsingEncoding:NSUTF8StringEncoding];
    
    // 2
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@", kAFAppNetworkAPIBaseURLString, path]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod: @"POST"];
    [request setHTTPBody:paramData];
    
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration ephemeralSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
    [[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //NSString *outstring = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        //NSLog(@"server return message:%@

%@", outstring, response);                  //3 work         NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];         NSString *printStr = @"{
";         for (NSString *key in dic) {             printStr = [NSString stringWithFormat:@"%@ %@ = %@
", printStr, key, dic[key]];         }         NSLog(@"  %@} %@
", printStr, [NSThread currentThread]);                  //   sel              }] resume]; }

좋은 웹페이지 즐겨찾기