我正在尝试将个人资料图像上传到用户个人资料,但个人资料图像未显示在个人资料页面上,没有弹出错误,因此,我如何重组此代码以解决此问题?
if let ProfileImageUrl = dictionary?["photo"] as? String {
let url = URL(string: ProfileImageUrl)
URLSession.shared.dataTask(with: url!, completionHandler: { ( data, response, Error ) in
if Error != nil {
print(Error!)
return
}
DispatchQueue.main.async {
self.ProfileImage.image = UIImage(data: data!)
}
尾随闭包中的“错误”应为“错误”。这只是命名约定的问题,不一定会导致代码失败。
发现问题,您在数据任务上缺少“ .resume()”。以下代码有效:
if let imageUrl = urlString{
let url = URL(string: imageUrl)
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if let error = error{
print("Error : \(error)")
return
}
DispatchQueue.main.async {
self.image.image = UIImage(data: data!)
}
}.resume()
}
首先,您需要按按钮进行上传(浏览器已上传)所以只需创建按钮,然后创建按钮操作
@IBAction func doUplodPImg(_ sender: Any) {
let image = UIImagePickerController()
image.delegate = self
image.sourceType = UIImagePickerController.SourceType.photoLibrary
image.allowsEditing = false
self.present(image, animated: true)
{
//After it is complete
}
}
并且还添加一个功能
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any])
{
if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
{
profileImg.image = image
}
else
{
//Error message
}
guard let selectedImage = info[.originalImage] as? UIImage else {
fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
}
profileImg.image = selectedImage
self.dismiss(animated: true, completion: nil)
}
现在您可以在UIimageview中成功上传照片。请将您自己的名称profileImg更改为您的UIimageview名称
确保在顶部viewcontroller委托中添加了UIImagePickerControllerDelegate
并且如果要上传到服务器中,则只需使用alamofire方法
Alamofire.upload(
multipartFormData: { multipartFormData in
if let _image = self.profileImg.image {
if let imageData = _image.jpegData(compressionQuality: 0.7) {
multipartFormData.append(imageData, withName: "profile_image", fileName: "image.jpg", mimeType: "image/jpg")
}
}
for (key, value) in parameters {
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
}
}, to: url, method: .post)
{ (response) in
switch response {
case .success(let upload,_,_):
upload.responseJSON { res in
let response = res.result.value as? NSDictionary
print(response)
}
case .failure(_): break
}
}
使用此profile_image(服务器端参数)更改参数名称,即时消息
希望这会有所帮助。如果您遇到任何困难,请告诉我。