iOS 开发APP更换用户头像问题的处理方式
iOS 开发APP更换用户头像问题的处理方式
1.常见的处理方式:SDWebImage处理
这种使用方式是后台提供头像下载的URL
使用的方法—options参数选择options:SDWebImageRefreshCached–会自动更新头像
- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock {[self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:completedBlock];
}
tableview 的headview里的方法
- (void)setIconImageURLString:(NSString *)iconImageURLString {[self.iconView sd_setImageWithURL:[NSURL URLWithString:iconImageURLString] placeholderImage:[UIImage imageNamed:@"placeholderImage"] options:SDWebImageRefreshCached completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {if (error) {NSLog(@"====%@",error);}NSLog(@"%@===%@",image,imageURL);//把新图片保存到沙盒[self saveIconImageToDocument:image withName:@"newIconImage.jpeg"];}];
}//头像保存到本地
- (void)saveIconImageToDocument:(UIImage *)newIconImage withName:(NSString *)newIconImageName {NSData *imageData = UIImageJPEGRepresentation(newIconImage, 0.5);NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:newIconImageName];[imageData writeToFile:fullPath atomically:NO];
}
tableview控制器里的代码
/*************************更换头像从相册还是相机选择*******************************/
#pragma mark - 跳转到更换头像界面
- (void)changeIcon:(NSNotification *)notification {UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"更换头像" message:nil preferredStyle:UIAlertControllerStyleActionSheet];UIImagePickerController *imagePickerVc = [[UIImagePickerController alloc] init];imagePickerVc.delegate = self;imagePickerVc.allowsEditing = YES;UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"从相册选择照片" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {imagePickerVc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;[self presentViewController:imagePickerVc animated:YES completion:nil];}];UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {imagePickerVc.sourceType = UIImagePickerControllerSourceTypeCamera;[self presentViewController:imagePickerVc animated:YES completion:nil];}];UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];[alertC addAction:albumAction];[alertC addAction:cameraAction];[alertC addAction:cancel];[self presentViewController:alertC animated:YES completion:nil];
}
- (void)dealloc {[[NSNotificationCenter defaultCenter] removeObserver:self];
}
/*************************更换头像*******************************/
//选择图片后,更换头像,并保存到沙盒,上传到服务器
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary*)info {UIImage *newIconImage = [info objectForKey:UIImagePickerControllerEditedImage];self.headView.iconImage = newIconImage;[self saveIconImageToDocument:newIconImage withName:@"newIconImage.jpeg"];
// [self updateIconImage:newIconImage];[self dismissModalViewControllerAnimated:YES];
}
2.后台没有提供下载头像的URL,而是提供了头像图片的二进制数据
从服务器获取头像
// MARK: 下载头像
- (void)downloadIconImage {// 1.网络请求管理者AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];// 让AFN返回原始的二进制数据,我们自己来解析manager.responseSerializer = [AFHTTPResponseSerializer serializer]; NSString *URLString = [NSString stringWithFormat:@"%@",BaseURLString];NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:URLString]];NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {// 在这个代码块里面指定文件下载完成之后的缓存路径,指定好了之后,会自动的剪切到completionHandler里面NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"newIconImage.jpg"];NSURL *pathURL = [NSURL fileURLWithPath:fullPath];return pathURL;} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {//下载完后,从Documents里获取头像,并显示NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];NSString *newIconImagePath = [documents stringByAppendingPathComponent:@"newIconImage.jpg"];UIImage *newIconImage = [UIImage imageWithContentsOfFile:newIconImagePath];self.headView.iconImage = newIconImage;}];[downloadTask resume];
}
上传头像到服务器
//MARK: 上传头像到服务器
- (void)updateIconImage:(UIImage *)newIconImage {AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];NSString *URLString = [NSString stringWithFormat:@"%@",BaseURLString];// file---存到服务器里的字段--// 文件上传的文本信息NSDictionary *parameters = @{@"file":@"newIconImage.jpg",};[manager POST:URLString parameters:parameters constructingBodyWithBlock:^(id _Nonnull formData) {NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];NSString *path = [documents stringByAppendingPathComponent:@"newIconImage.jpg"];NSData *data = [NSData dataWithContentsOfFile:path];// formData : 用于拼接文件上传时的表单数据[formData appendPartWithFileData:data name:@"file" fileName:@"newIconImage.jpg" mimeType:@"image/jpeg"];} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {ZYLog(@"%@",responseObject);NSString *result = responseObject[@"result"];if ([result isEqualToString:@"success"]) {[self sendUIAlertControllerWithTitle:@"更换的头像成功上传到服务器" message:nil];[self saveIconImageToDocument:newIconImage withName:@"newIconImage.jpg"];}else if ([result isEqualToString:@"not_login_in"]) {[self sendUIAlertControllerWithTitle:@"用户未登录,请登录后再操作" message:nil];}else if ([result isEqualToString:@"isNotMultipart"]) {[self sendUIAlertControllerWithTitle:@"文件格式有误,请选择图片上传" message:nil];}} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {[self sendUIAlertControllerWithTitle:@"网络延迟,更换头像失败" message:@"请检查网络后重新尝试"];}];
}
//头像保存到本地
- (void)saveIconImageToDocument:(UIImage *)newIconImage withName:(NSString *)newIconImageName {NSData *imageData = UIImageJPEGRepresentation(newIconImage, 0.5);NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:newIconImageName];[imageData writeToFile:fullPath atomically:NO];
}
headview拿到头像赋值
- (void)setIconImage:(UIImage *)iconImage {_iconImage = iconImage;NSData *imageData = UIImageJPEGRepresentation(iconImage, 0.5);UIImage *smallImage = [UIImage imageWithData:imageData];self.iconView.image = smallImage;self.baseView.image = smallImage;
}
// MARK: 自定义弹框
- (void)sendUIAlertControllerWithTitle:(NSString *)title message:(NSString *)message {UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];[self presentViewController:alert animated:YES completion:^{dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{[alert dismissViewControllerAnimated:YES completion:nil];});}];
}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
