哎!我是新手上路,搞个头像这么简单的问题,害的我饶了大半圈。我打算以记录的方式,记录我出错后,饶了很久的才解决的问题。
1.首先,这是把头像存储在本地方法
NSFileManager *manager = [NSFileManager defaultManager];
if (![manager fileExistsAtPath:kImageDirPath isDirectory:nil]){//保存在本地文件
[manager createDirectoryAtPath:kImageDirPath withIntermediateDirectories:YES attributes:nil error:nil];
}
NSData *imageData;
if (UIImagePNGRepresentation(image)) {
imageData = UIImagePNGRepresentation(image);
}else{
imageData = UIImageJPEGRepresentation(image, 1);
}
NSString *filePath = [kImageDirPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.photo",ctmID]];
[imageData writeToFile:filePath atomically:YES];
2.存储在本地后上传给后台
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager]; mgr.requestSerializer = [AFJSONRequestSerializer serializer]; mgr.responseSerializer = [AFJSONResponseSerializer serializer]; NSMutableDictionary *dict = [NSMutableDictionary dictionary]; dict[@"ctm_id"] = [UserTool readCtmID]; [mgr POST:kUploadPersonHeadImage parameters:dict constructingBodyWithBlock:^(id_Nonnull formData) {
NSData *data = UIImageJPEGRepresentation(image, 0.1);
[formData appendPartWithFileData:data name:@"head_pic" fileName:@"file.jpg" mimeType:@"image/jpeg"];
} success:^(AFHTTPRequestOperation * _Nonnull operation, id _Nonnull responseObject) {
// NSLog(@"--------responseObject.HeadPicURL:%@",responseObject[@"data"][@"person_info"][@"HeadPicURL"]);
NSLog(@"上传头像成功!");
} failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
NSLog(@"上传头像失败!");
}];
3.然后判断,在用户登录的时候,得到相应的图片路径,然后进行下载
PersonalInfoModel *person = [UserTool readPersonalInfoModel];
if (![UserTool readProfileImage]) {
__block UIImage *NEWImg = [[UIImage alloc]init];
//下载图片
[IconView sd_setImageWithURL:[NSURL URLWithString:person.HeadPicURL] placeholderImage:[UIImage imageNamed:@"美泊logo"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
if (image == nil) {
NEWImg = [UIImage imageNamed:@"美泊logo"];
}else{
NEWImg = image;
}
IconView.image = [UIImage circleImageWithUIImage:NEWImg borderColor:[UIColor whiteColor] borderWidth:5]; ;
//下载好之后存在本地
[UserTool saveProfileImage:image];
}];
}else if ([UserTool readProfileImage]){
//本地读取图片
IconView.image = [UIImage circleImageWithUIImage:[UserTool readProfileImage] borderColor:[UIColor whiteColor] borderWidth:5]; ;
}else{
//默认图片
IconView.image = [UIImage imageNamed:@"head"];
}
总结:就是做事情的时候,真的要懂原理,懂前因后果,多交流,多试验。这次我失败的地方就是没有和后台交流,我只知道在那个接口上把图片上传给后台,儿忘了问他在那个接口获取图片路径。还有就是弥补了SDWebImage的用法。
网友评论