Commit 83a1e5a9 cgx

完成用户头像修改

1 个父辈 3b33f99b
......@@ -20,6 +20,12 @@ NS_ASSUME_NONNULL_BEGIN
*/
+ (CGFloat)getHeightWithText:(NSString *)text withFont:(UIFont *)font withMaxWidth:(CGFloat)maxWidth;
/**
* @brief 去掉字符串中的空格,换行,回车符号
* @param oldStr 传入的字符串
* @return 转换后的string
*/
+ (NSString *)trimString:(NSString *)oldStr;
@end
NS_ASSUME_NONNULL_END
......@@ -16,4 +16,25 @@
return size.height;
}
+ (NSString *)trimString:(NSString *)oldStr
{
oldStr = oldStr ? oldStr : @"";
NSMutableString* newStr = [NSMutableString stringWithString:oldStr];
NSRange range1 = {0, oldStr.length};
[newStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range1];
NSRange range2 = {0, newStr.length};
[newStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
NSRange range3 = {0, newStr.length};
[newStr replaceOccurrencesOfString:@"\r" withString:@"" options:NSLiteralSearch range:range3];
return newStr;
}
@end
......@@ -11,6 +11,10 @@ NS_ASSUME_NONNULL_BEGIN
@interface UIImage (Extras)
- (UIImage *)imageByScalingToSize:(CGSize)targetSize;
/// UIImage转base64字符串
/// @param image image
- (NSString *)imageToBase64Str:(UIImage *)image;
@end
NS_ASSUME_NONNULL_END
......@@ -51,4 +51,144 @@
return newImage ;
}
- (NSString *)imageToBase64Str:(UIImage *)image {
NSData *imageData = [self resetSizeOfImage:image maxSize:150];
NSString *base64Str = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
NSString *trimStr = [NSString trimString:base64Str];
return trimStr;
}
/**
图片宽高尺寸限制在200-1024之间,maxSize kb以内
*/
- (NSData *)resetSizeOfImage:(UIImage *)sourceImage maxSize:(NSInteger)maxSize {
// 最终图片data
__block NSData *finallImageData = UIImageJPEGRepresentation(sourceImage, 1.0);
// 原图宽高比
CGFloat sourceImageAspectRatio = sourceImage.size.width / sourceImage.size.height;
CGFloat defaultWidth = sourceImage.size.width;
CGFloat defaultHeight = sourceImage.size.height;
CGSize defaultSize = sourceImage.size;
if (defaultWidth > 1024 || defaultHeight > 1024) {
// 判断尺寸是否过大
if (defaultWidth > 1024 && defaultWidth > defaultHeight) {
defaultSize = CGSizeMake(1024, 1024 / sourceImageAspectRatio);
} else if (defaultHeight > 1024 && defaultWidth < defaultHeight) {
defaultSize = CGSizeMake(1024 * sourceImageAspectRatio, 1024);
}
} else if (defaultWidth < 200 || defaultHeight < 200) {
// 判断尺寸是否过小
if (defaultWidth < 200 && defaultWidth < defaultHeight) {
defaultSize = CGSizeMake(200, 200 / sourceImageAspectRatio);
} else if (defaultHeight < 200 && defaultWidth > defaultHeight) {
defaultSize = CGSizeMake(200 * sourceImageAspectRatio, 200);
}
}
// 先调整分辨率
UIImage *newImage = [self newSizeImage:defaultSize image:sourceImage];
finallImageData = UIImageJPEGRepresentation(newImage, 1.0);
// 判断当前质量是否满足要求,不满足再进行压缩
NSUInteger sizeOrigin = finallImageData.length;//data.length即可得到图片的字节大小
NSUInteger sizeOriginKB = sizeOrigin / 1000;
if (sizeOriginKB <= maxSize) {
return finallImageData;
}
// 保存压缩系数
NSMutableArray *compressionQualityArr = [NSMutableArray array];
CGFloat avg = 1.0/250;
CGFloat value = avg;
for (int i = 250; i >= 1; i--) {
value = i*avg;
[compressionQualityArr addObject:@(value)];
}
/*
调整大小
说明:压缩系数数组compressionQualityArr是从大到小存储。
*/
// 思路:使用二分法搜索
finallImageData = [self halfFuntion:compressionQualityArr image:newImage sourceData:finallImageData maxSize:maxSize];
// 如果还是未能压缩到指定大小,则进行降分辨率
while (finallImageData.length == 0) {
//每次降100分辨率
CGFloat reduceWidth = 100.0;
CGFloat reduceHeight = 100.0/sourceImageAspectRatio;
if (defaultSize.width-reduceWidth <= 0 || defaultSize.height-reduceHeight <= 0) {
break;
}
defaultSize = CGSizeMake(defaultSize.width-reduceWidth, defaultSize.height-reduceHeight);
UIImage *image = [self newSizeImage:defaultSize
image:[UIImage imageWithData:UIImageJPEGRepresentation(newImage,[[compressionQualityArr lastObject] floatValue])]];
finallImageData = [self halfFuntion:compressionQualityArr image:image sourceData:UIImageJPEGRepresentation(image,1.0) maxSize:maxSize];
}
return finallImageData;
}
#pragma mark - 调整图片分辨率/尺寸(等比例缩放)
- (UIImage *)newSizeImage:(CGSize)size image:(UIImage *)sourceImage {
CGSize newSize = CGSizeMake(sourceImage.size.width, sourceImage.size.height);
CGFloat tempHeight = newSize.height / size.height;
CGFloat tempWidth = newSize.width / size.width;
if (tempWidth > 1.0 && tempWidth > tempHeight) {
newSize = CGSizeMake(sourceImage.size.width / tempWidth, sourceImage.size.height / tempWidth);
} else if (tempHeight > 1.0 && tempWidth < tempHeight) {
newSize = CGSizeMake(sourceImage.size.width / tempHeight, sourceImage.size.height / tempHeight);
} else {
newSize = size;
}
UIGraphicsBeginImageContext(newSize);
[sourceImage drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
#pragma mark - 二分法
- (NSData *)halfFuntion:(NSArray *)arr image:(UIImage *)image sourceData:(NSData *)finallImageData maxSize:(NSInteger)maxSize {
NSData *tempData = [NSData data];
NSUInteger start = 0;
NSUInteger end = arr.count - 1;
NSUInteger index = 0;
NSUInteger difference = NSIntegerMax;
while(start <= end) {
index = start + (end - start)/2;
finallImageData = UIImageJPEGRepresentation(image,[arr[index] floatValue]);
NSUInteger sizeOrigin = finallImageData.length;
NSUInteger sizeOriginKB = sizeOrigin / 1024;
DSLog(@"当前降到的质量:%ld", (unsigned long)sizeOriginKB);
DSLog(@"\nstart:%zd\nend:%zd\nindex:%zd\n压缩系数:%lf", start, end, (unsigned long)index, [arr[index] floatValue]);
if (sizeOriginKB > maxSize) {
start = index + 1;
} else if (sizeOriginKB < maxSize) {
if (maxSize-sizeOriginKB < difference) {
difference = maxSize-sizeOriginKB;
tempData = finallImageData;
}
if (index<=0) {
break;
}
end = index - 1;
} else {
break;
}
}
return tempData;
}
@end
......@@ -6,14 +6,40 @@
//
#import "UserInfoTableView.h"
#import "UserModel.h"
/// 自定义用户信息显示数据model
@interface UserShowModel : NSObject
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *detail;
// 获取用户显示数据
+ (NSArray *)getUserShowDatas;
@end
@implementation UserShowModel
+ (NSArray *)getUserShowDatas {
NSArray *titles = @[@"昵称", @"性别", @"生日"];
UserModel *userModel = [LoginUtils getUserLoginData];
NSString *nick_name = userModel && userModel.nick_name ? userModel.nick_name : @"";
NSString *gender = userModel ? (userModel.gender ? @"男" : @"女") : @"";
NSString *birthday = userModel && userModel.birthday ? userModel.birthday : @"";
NSArray *details = @[nick_name, gender, birthday];
NSMutableArray *tmpArr = [NSMutableArray array];
for (int i = 0; i < titles.count; i++) {
UserShowModel *m = [UserShowModel new];
m.title = titles[i];
m.detail = details[i];
[tmpArr addObject:m];
}
return [tmpArr copy];
}
@end
/// 设置自定义Cell
@interface UserCell : UITableViewCell
@property (nonatomic, strong) UILabel *titleLab;
@property (nonatomic, strong) UILabel *detailLab;
@property (nonatomic, strong) UIImageView *rightIcon;
- (void)updateUIWithModel:(UserModel *)model;
- (void)updateUIWithModel:(UserShowModel *)model;
@end
@implementation UserCell
......@@ -40,9 +66,9 @@
[super setSelected:selected animated:animated];
}
- (void)updateUIWithModel:(UserModel *)model {
- (void)updateUIWithModel:(UserShowModel *)model {
self.titleLab.text = model.title;
self.detailLab.text = @"";
self.detailLab.text = model.detail;
[self.titleLab sizeToFit];
[self.detailLab sizeToFit];
......@@ -71,7 +97,7 @@
- (instancetype)initWithFrame:(CGRect)frame delegate:(id<UserInfoTableViewDelegate>)delegate {
if (self = [super initWithFrame:frame style:UITableViewStylePlain]) {
self.dataArr = [UserModel getAllUserDatas];
self.dataArr = [UserShowModel getUserShowDatas];
self.setDelegate = delegate;
[self cornerRadius:10];
self.scrollEnabled = NO;
......@@ -84,7 +110,7 @@
- (DSDataSource *)infoDataSource {
if (!_infoDataSource) {
CellConfigureBlock cellBlock = ^(UserCell * cell, UserModel * model, NSIndexPath * indexPath) {
CellConfigureBlock cellBlock = ^(UserCell * cell, UserShowModel * model, NSIndexPath * indexPath) {
[cell updateUIWithModel:model];
};
NSString * const userCell = @"UserCell";
......
......@@ -10,6 +10,7 @@
#import "UserInfoTableView.h"
#import "DSImagePickerController.h"
#import "RSKImageCropper.h"
#import "UserRequestModel.h"
@interface UserInfoView () <PhotoAlertViewDelegate, UserInfoTableViewDelegate, DSImagePickerControllerDelegate, RSKImageCropViewControllerDelegate>
@property (nonatomic, strong) UIButton *portraitBtn;
......@@ -24,7 +25,7 @@
if (self = [super initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - kTopHeight(0))]) {
_delegate = delegate;
[self.portraitBtn yy_setImageWithURL:[NSURL URLWithString:@"https://img2.ydniu.com/sleep_ssmain/face_img/1648892614555_QhXhJX.jpg"] forState:UIControlStateNormal placeholder:[UIImage imageNamed:@"portrait"]];
[self.portraitBtn yy_setImageWithURL:[NSURL URLWithString:[LoginUtils getFaceImg]] forState:UIControlStateNormal placeholder:[UIImage imageNamed:@"basicPlaceholder"]];
[self addSubview:self.userInfoTV];
[self addSubview:self.layoutBtn];
......@@ -70,9 +71,16 @@
}
- (void)imageCropViewController:(RSKImageCropViewController *)controller didCropImage:(UIImage *)croppedImage usingCropRect:(CGRect)cropRect {
// 用户头像上传,成功后存入沙盒
[DSProgressHUD showProgressHUDWithInfo:@""];
[UserRequestModel updateFaceImgRequest:croppedImage completion:^(UserRequestModel * _Nonnull requestModel) {
[DSProgressHUD dissmissProgressHUD];
// 用户头像上传成功后存入沙盒(暂不处理)
if (requestModel.resCode == DSResCodeSuccess) {
[DSProgressHUD showToast:@"修改成功"];
[self.portraitBtn setImage:croppedImage forState:UIControlStateNormal];
[self.ds_viewController dismissViewControllerAnimated:YES completion:nil];
}
}];
}
#pragma mark - UserInfoTableViewDelegate
......
......@@ -16,6 +16,8 @@
@interface ProfileController ()
@property (nonatomic, strong) UIView *userInfoView;
@property (nonatomic, strong) NSArray *tmpDatas;
@property (nonatomic, strong) UIImageView *headIV;
@property (nonatomic, strong) UILabel *nickLab;
@end
@implementation ProfileController
......@@ -27,6 +29,13 @@
self.tableView.dk_backgroundColorPicker = DKColorPickerWithKey(VCViewBG);
self.tmpDatas = @[@"模拟用户登录", @"意见反馈", @"系统设置", @"邀请好友", @"关于我们", @"前往小程序", @"关注公众号", @"添加客服微信", @"失眠的认知行为疗法"];
self.tableView.tableHeaderView = self.userInfoView;
// 监听用户数据更新通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateUserView) name:HasUpdateUserDataNoti object:nil];
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self name:HasUpdateUserDataNoti object:nil];
}
#pragma mark - 导航栏日间、黑夜模式
......@@ -129,15 +138,39 @@
}
}
- (void)updateUserView {
UserModel *model = [LoginUtils getUserLoginData];
if (model) {
[self.headIV yy_setImageWithURL:[NSURL URLWithString:model.face_img] placeholder:[UIImage imageNamed:@"basicPlaceholder"]];
self.nickLab.text = model.nick_name;
} else {
self.headIV.image = [UIImage imageNamed:@"basicPlaceholder"];
self.nickLab.text = @"";
}
}
#pragma mark - lazy
- (UIView *)userInfoView {
if (!_userInfoView) {
_userInfoView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 100)];
_headIV = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 60, 60)];
_headIV.centerY = _userInfoView.centerY;
[_headIV cornerRadius:30];
[_userInfoView addSubview:_headIV];
_nickLab = [UILabel dkLabWithFont:BoldFont(15)];
_nickLab.frame = CGRectMake(CGRectGetMaxX(_headIV.frame) + 5, 0, 100, 20);
_nickLab.centerY = _userInfoView.centerY;
[_userInfoView addSubview:_nickLab];
UIButton *btn = [UIButton btnWithTitle:@"点击修改信息" titleColor:BrandColor font:SysFont(16) bgColor:DSClearColor];
btn.frame = CGRectMake(0, 0, 150, 40);
btn.center = _userInfoView.center;
btn.frame = CGRectMake(CGRectGetMaxX(_nickLab.frame) + 5, 0, 150, 40);
btn.centerY = _userInfoView.centerY;
[btn addTarget:self action:@selector(modifyUserInfoAction) forControlEvents:UIControlEventTouchUpInside];
[_userInfoView addSubview:btn];
[self updateUserView];
}
return _userInfoView;
}
......
......@@ -6,7 +6,7 @@
//
#import <Foundation/Foundation.h>
@class UserModel;
#import "UserModel.h"
NS_ASSUME_NONNULL_BEGIN
......@@ -25,11 +25,18 @@ NS_ASSUME_NONNULL_BEGIN
/// 获取token
+ (NSString *)getToken;
/// 获取用户头像
+ (NSString *)getFaceImg;
/// 更新sid和token
/// @param sid sid
/// @param token token
+ (void)updateSid:(NSString *)sid token:(NSString *)token;
/// 更新用户头像
/// @param face_img face_img
+ (void)updateFaceImg:(NSString *)face_img;
/// 保存用户登录数据
+ (void)saveUserLoginData:(UserModel *)model;
......
......@@ -6,7 +6,6 @@
//
#import "LoginUtils.h"
#import "UserModel.h"
#import "LoginController.h"
@implementation LoginUtils
......@@ -31,6 +30,11 @@
return userModel.token;
}
+ (NSString *)getFaceImg {
UserModel *userModel = [self getUserLoginData];
return userModel.face_img;
}
+ (void)updateSid:(NSString *)sid token:(NSString *)token {
UserModel *userModel = [self getUserLoginData];
userModel.sid = sid;
......@@ -38,14 +42,24 @@
[self saveUserLoginData:userModel];
}
+ (void)updateFaceImg:(NSString *)face_img {
UserModel *userModel = [self getUserLoginData];
userModel.face_img = face_img;
[self saveUserLoginData:userModel];
}
+ (void)saveUserLoginData:(UserModel *)model {
NSData *userData = [NSKeyedArchiver archivedDataWithRootObject:model];
kSetUserDefaultsObj(userData, UserBasicInfo);
kUserDefaultsSynchronize;
// 发送更新用户数据显示UI通知
[[NSNotificationCenter defaultCenter] postNotificationName:HasUpdateUserDataNoti object:nil];
}
+ (void)clearUserLoginData {
kUserDefaultsRemoveObj(UserBasicInfo);
// 发送更新用户数据显示UI通知
[[NSNotificationCenter defaultCenter] postNotificationName:HasUpdateUserDataNoti object:nil];
}
+ (void)jumpToLoginControllerWithTarget:(UIViewController *)target {
......
......@@ -11,20 +11,24 @@ NS_ASSUME_NONNULL_BEGIN
/// 用户数据model
@interface UserModel : NSObject <NSCoding>
#pragma mark - 微信登录、apple登录、自动登录用户数据model
// 昵称
@property (nonatomic, copy) NSString *nick_name;
// 性别
@property (nonatomic, assign) BOOL gender;
// 生日
@property (nonatomic, copy) NSString *birthday;
// 用户id
@property (nonatomic, assign) int user_id;
// 登录token
@property (nonatomic, copy) NSString *token;
// 获取后每次发送请求存放到请求头
@property (nonatomic, copy) NSString *sid;
// 用户名
@property (nonatomic, copy) NSString *user_name;
// 用户头像
@property (nonatomic, copy) NSString *face_img;
@property (nonatomic, assign) int is_access;
@property (nonatomic, copy) NSString *title;
+ (NSArray *)getAllUserDatas;
@end
NS_ASSUME_NONNULL_END
......@@ -31,15 +31,4 @@
return self;
}
+ (NSArray *)getAllUserDatas {
NSArray *titles = @[@"昵称", @"性别", @"生日"];
NSMutableArray *tmpArr = [NSMutableArray array];
for (int i = 0; i < titles.count; i++) {
UserModel *m = [UserModel new];
m.title = titles[i];
[tmpArr addObject:m];
}
return [tmpArr copy];
}
@end
......@@ -6,7 +6,6 @@
//
#import "DSNetworkTool.h"
#import "UserModel.h"
NS_ASSUME_NONNULL_BEGIN
......@@ -38,6 +37,11 @@ NS_ASSUME_NONNULL_BEGIN
/// @param completion completion
+ (NSURLSessionDataTask *)autoLoginRequestWithCompletion:(void (^)(UserRequestModel *requestModel))completion;
/// 修改用户头像接口
/// @param faceImg 图片数据
/// @param completion completion
+ (NSURLSessionDataTask *)updateFaceImgRequest:(UIImage *)faceImg completion:(void (^)(UserRequestModel *requestModel))completion;
@end
NS_ASSUME_NONNULL_END
......@@ -105,6 +105,24 @@
}];
}
+ (NSURLSessionDataTask *)updateFaceImgRequest:(UIImage *)faceImg completion:(void (^)(UserRequestModel *requestModel))completion {
UserRequestModel * requestModel = [[UserRequestModel alloc] init];
NSString *api = @"update_face_img";
int user_id = [LoginUtils getUserID];
NSString *base64 = [faceImg imageToBase64Str:faceImg];
NSString *argStr = [NSString stringWithFormat:@"mutation{%@(user_id:%d,base64:\"%@\")}", api, user_id, base64];
return [self httpPostBodyRequestWithAPI:api params:@{@"query" : argStr} view:nil hasNetActivity:YES loadingInfo:nil hasFailInfo:YES success:^(NSDictionary * _Nonnull apiDic) {
DSLog(@"用户头像修改接口apiDic:%@", apiDic);
[LoginUtils updateFaceImg:apiDic[@"result"]];
requestModel.resCode = DSResCodeSuccess;
completion(requestModel);
} failure:^(id _Nonnull failureInfo) {
requestModel.resCode = DSResCodeNetFail;
requestModel.errorInfo = failureInfo;
completion(requestModel);
}];
}
// 修改用户信息
+ (NSURLSessionDataTask *)updateUserInfoWithCompletion:(void (^)(UserRequestModel *requestModel))completion {
UserRequestModel * requestModel = [[UserRequestModel alloc] init];
......
{
"images" : [
{
"filename" : "allowed.png",
"idiom" : "universal",
"scale" : "1x"
},
{
"filename" : "allowed@2x.png",
"idiom" : "universal",
"scale" : "2x"
},
{
"filename" : "allowed@3x.png",
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
......@@ -30,8 +30,10 @@ FOUNDATION_EXTERN NSString * const ExpireTime1;
FOUNDATION_EXTERN NSString * const StartTime2;
FOUNDATION_EXTERN NSString * const ExpireTime2;
// 通知相关
// 微信登录通知
FOUNDATION_EXTERN NSString * const WXLoginAuthNoti;
// 更新用户数据通知
FOUNDATION_EXTERN NSString * const HasUpdateUserDataNoti;
// 用户基础信息
FOUNDATION_EXTERN NSString * const UserBasicInfo;
......
......@@ -24,6 +24,7 @@ NSString * const StartTime2 = @"00:00:00";
NSString * const ExpireTime2 = @"06:00:00";
NSString * const WXLoginAuthNoti = @"wxLoginAuthNoti";
NSString * const HasUpdateUserDataNoti = @"hasUpdateUserDataNoti";
NSString * const UserBasicInfo = @"UserBasicInfo";
......
......@@ -26,6 +26,7 @@
#import "UIButton+Extras.h"
#import "NSString+Extras.h"
#import "NSDate+Extras.h"
#import "UIImage+Extras.h"
#import "NaviBarHandlerProtocol.h"
#import "BaseNaviController.h"
......
支持 Markdown 格式
你添加了 0 到此讨论。请谨慎行事。
Finish editing this message first!