我是一个初学者,希望大家不要喷,写这个都是因为我写的时候没有搜到,方便那些像我一样遇到这个困惑的初学者。
我的进度条是用MBProgressHUB写的
MBProgressHUD * _hud;
_hud = [[MBProgressHUD alloc]initWithView:self.view];
_hud.labelText = @"正在上传";
_hud.mode = MBProgressHUDModeAnnularDeterminate;
[self.view addSubview:_hud];
3.0之后 有些许变化 http://www.jianshu.com/p/047463a7ce9b
progress部分反映了进度情况
上传图片是将数据流压缩了让后上传 ,也可不压缩
AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[_hud show:YES];
[manager POST:@"Url 字符串" parameters:Dictionary constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
NSData * imgData = UIImageJPEGRepresentation(_imgV.image, 0.1);//0.1是把图片压缩
[formData appendPartWithFileData:imgData name:@"PHPhoto" fileName:@"phPhoto.jpg" mimeType:@"image/jpg/png/jpeg"];
} progress:^(NSProgress * _Nonnull uploadProgress) {//进度 NSProgress 配合KVC来使用 反应进度情况
[uploadProgress addObserver:self forKeyPath:@"fractionCompleted" options:NSKeyValueObservingOptionNew context:nil];
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
[_hud hide:YES];
id root = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@",root);
[self performSelectorOnMainThread:@selector(backToMain:) withObject:root waitUntilDone:YES];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
[_hud hide:YES];
[self performSelectorOnMainThread:@selector(backToMain) withObject:nil waitUntilDone:YES];
}];
#pragma mark -
#pragma mark 上传进度
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:@"fractionCompleted"] && [object isKindOfClass:[NSProgress class]]) {
NSProgress *progress = (NSProgress *)object;
_hud.progress = progress.fractionCompleted;
}
}
#pragma mark -
这样就可以反映出 实时的上传进度了。