美文网首页
NSURLSession - 上传照片

NSURLSession - 上传照片

作者: Mikayla321 | 来源:发表于2018-06-29 09:20 被阅读0次

iOS10以下,AFNetworking上传照片,发生内存泄漏;因此用NSURLSesion实现上传照片,代码如下:

NSString *urlStr = [[self class] createImgUrl];
        
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
        [request setHTTPMethod:@"POST"];
        [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
        [request setTimeoutInterval:15.f];
        //必须要写boundary=,不然报错
        NSString *content = [[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@", UploadImageBoundary];
        [request setValue:content forHTTPHeaderField:@"Content-Type"];
        //设置token
        [request setValue:gloginManager.token forHTTPHeaderField:@"apptoken"];
        //配置host
        if ([ServerConfigManager currentUsedServerType] == ServerType_CUSTOM_IP) {
            [request setValue:@"btr.m.jd.com" forHTTPHeaderField:@"host"];
        }
        
        NSMutableData *requestMutableData = [NSMutableData data];
        NSMutableString *myString = [NSMutableString stringWithFormat:@"--%@\r\n", UploadImageBoundary];
        [myString appendString:@"Content-Disposition: form-data; name=\"file\"; filename=\"1.jpg\"\r\n"];
        [myString appendString:@"Content-Type: image/jpg\r\n\r\n"];
        /*转化为二进制数据*/
        [requestMutableData appendData:[myString dataUsingEncoding:NSUTF8StringEncoding]];
        /*文件数据部分,也是二进制*/
        [requestMutableData appendData:imageData];
        /*已--boundary结尾表明结束*/
        [requestMutableData appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", UploadImageBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
        request.HTTPBody = requestMutableData;
        
        /*开始上传*/
        NSURLSessionDataTask *uploadtask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            //请求回调
            NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            DLog(@"finished===========%@", jsonStr);
            NSDictionary *dictionary = [LJUtils toArrayOrDictionaryFromJSONString:jsonStr];
            dispatch_async(dispatch_get_main_queue(), ^{
                callback(YES, dictionary, nil);
            });
        }];
        
        [uploadtask resume];

相关文章

网友评论

      本文标题:NSURLSession - 上传照片

      本文链接:https://www.haomeiwen.com/subject/brmoyftx.html