iOS开发(OC)——AFNetworking之文件上传

//urlString服务器地址
//param 字典类型,后面跟你要传的参数及其值
例如:NSDictionary *param = @{@”time”:dateString,@”token”:tokenString,@”userid”:[userDefault objectForKey:userid],@”finger_type”:[NSString stringWithFormat:@”%d”,(int)selectButton.tag-10+1],@”audio”:fileData};

//下面的方法中如果需要回调的就自己写block吧,我怕我写了有些人看不懂
+(void)postAudioWithUrl:(NSString )urlString andParam:(NSDictionary )param keyName:(NSString )key fileName:(NSString )file data:(NSData *)fileData
{
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@”POST” URLString:urlString parameters:param constructingBodyWithBlock:^(id formData) {
//fileData二进制流,例如NSData *fileData=[NSData dataWithContentsOfFile:filePath];//filePath你的文件路径
//key服务器地址url上二进制流的关键字字段
//file,自定义的文件名
//@”application/octet-stream”文件的类型,当你不知道时就默认用这个
[formData appendPartWithFileData:fileData name:key fileName:file mimeType:@”application/octet-stream”];

} error:nil];

AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

manager.responseSerializer = [AFHTTPResponseSerializer serializer];

NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {

    //进度条
    CGFloat progress=(CGFloat)downloadProgress.completedUnitCount/(CGFloat)downloadProgress.totalUnitCount;//运算符/,当两边都是整型时,得出的结果也是整型,所以要进行类型转换


} completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    //失败
    if (error) {
        NSDictionary *info = [NSDictionary dictionaryWithObjectsAndKeys:error.debugDescription,@"info", nil];


    } else {//成功

        NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];

    }

}];


[uploadTask resume];//注意不要漏

}

iOS开发交流群:301058503

你可能感兴趣的:(OC)