iOS NSURLSession相关

 1. 定义宏 上传图片/请求接口会用到

#define DATA(X)	[X dataUsingEncoding:NSUTF8StringEncoding]
#define kBoundary @"------------0x0x0x0x0x0x0x0x"
#define IMAGE_CONTENT  @"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\nContent-Type: image/jpeg\r\n\r\n"
#define STRING_CONTENT @"Content-Disposition: form-data; name=\"%@\"\r\n\r\n"
#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\n", 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\n";
        [result appendData:DATA(formstring)];
    }
    
    NSString *formstring =[NSString stringWithFormat:@"--%@--\r\n", 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(@"#####################################################\n");
    NSLog(@"post:%@", postData);//[[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding]);
    NSLog(@"#####################################################\n");

    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(@"\n1server return message:%@\n", 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(@"\n2server return message:%@\n", 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:%@\n\n%@", outstring, response);
        
        //3 work
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        NSString *printStr = @"{\n";
        for (NSString *key in dic) {
            printStr = [NSString stringWithFormat:@"%@ %@ = %@\n", printStr, key, dic[key]];
        }
        NSLog(@"返回结果 %@} %@\n", printStr, [NSThread currentThread]);
        
        //处理数据 继承类根据sel来取值
        
    }] resume];
}


你可能感兴趣的:(NSURLSession)