调用API更新用户资料时用户未上传头像的处理方法(Alamofire+AWSS3)
问题根源
你当前的逻辑仅在用户选择了新头像(profileImageData 不为空)时才会触发资料保存操作,若用户未修改头像,uploadImage 方法内的分支判断会直接跳过,不会执行后续的文本信息更新逻辑。
修复方案
按以下步骤修改代码即可同时支持「修改头像+修改文本」、「仅修改文本」两种场景:
- 将
saveProfile方法的imagename参数改为可选类型,未传值时默认读取本地存储的旧头像地址提交 - 给
uploadImage方法加else分支,没有新头像数据时直接调用保存接口提交文本信息
修改后的完整代码如下:
修改后的saveProfile方法
func saveProfile(imagename: String? = nil) { if self.firstNameTxt.text!.isEmpty || self.lastNameTxt.text!.isEmpty || self.birthDateTxt.text!.isEmpty { let alertController = UIAlertController(title: "错误", message: "请填写所有必填字段", preferredStyle: .alert) let defaultAction = UIAlertAction(title: "确定", style: .cancel, handler: nil) alertController.addAction(defaultAction) present(alertController, animated: true, completion: nil) } else { // 优先用新上传的头像名,无新头像则取本地存储的旧头像名 let finalProfilePic = imagename ?? (Utility.getModelObject(forKey: ProfileData) as? LoginModel)?.profile_pic ?? "" let parameter : Parameters = [ "first_name": self.firstNameTxt.text!, "last_name": self.lastNameTxt.text!, "birth_date" : self.birthDateTxt.text!, "profile_pic" : finalProfilePic ] SVProgressHUD.show() MVCServer().serviceRequestWithURL(reqMethod: .patch, withUrl: "user-profile", withParam: parameter, diplayHud: true, includeToken: true) { responseCode, response in SVProgressHUD.dismiss() if responseCode == 1 { if let dataResponse = response.value(forKey: "result") as? Bool , let payload = response.value(forKey: "payload") as? NSDictionary{ if dataResponse == true { if let userData = LoginModel.init(dictionary: payload) { Utility.setModelObject(userData , forKey: ProfileData) self.view.makeToast("资料更新成功", duration: 3.0, position: .top) } } } } else { Utility.showMessage("错误", withTitle: "数据上传失败", on: self) print(response.value(forKey: "message") as? String ?? "") } } } }
修改后的uploadImage方法
func uploadImage() { if let profileImageData = profileImageData { let imageName:Int64 = Int64(Date().timeIntervalSince1970) let randomString = Utility.getAlphaNumericRandomNumber() // 修正Int64类型格式化符,避免32位设备溢出问题 let imageNameStr = String(format:"%@%lld.jpg",randomString,imageName) let stringUploadPath = String(format:"%@/%@",AmazonAWS3.S3UploadPathProfile,imageNameStr) Utility.showLoadingView() AmazonAWS3().uploadFileToAWS3(filePath: stringUploadPath, data: profileImageData) { result in Utility.hideLoadingView() switch result { case .success(_): self.saveProfile(imagename: imageNameStr) case .failure(_): print("头像上传失败") Utility.showMessage("错误", withTitle: "头像上传失败", on: self) } } } else { // 无新头像直接提交文本信息 self.saveProfile() } }
附加优化说明
- 补充了成功回调里的加载框关闭逻辑,避免加载框一直显示
- 修正了Int64类型时间戳的格式化符,避免32位设备出现数值溢出
- 上传头像失败时增加了用户可见的提示,避免用户无感知
你的UI界面参考:
内容的提问来源于stack exchange,提问作者iFateh
相关产品推荐
相关产品推荐

