从ImageView将图像上传到Web服务中
问题描述:
我试图上传设备摄像头拍摄的图像,或者从设备库中选择,稍后使用ImageView在屏幕上显示图像,最后将其上传到Rest API。我已经有一个存储在Rest API中的默认图像,我的应用程序已经加载了这个图像,但是当我尝试更改图像时,我遇到了问题。从ImageView将图像上传到Web服务中
这是邮政API调用后我的代码,我的JSON数据:
let defaultServiceResponse = data["defaultServiceResponse"] as! NSDictionary
self.idResponse = defaultServiceResponse["idResponse"] as! Int
let loginModel = LoginModel()
if self.idResponse == 0 {
let userInfo = data["userInfo"] as! NSDictionary
loginModel.imageProfileUrl = userInfo["imageProfileUrl"] as! String
let url = URL(string: loginModel.imageProfileUrl)
let data = try? Data(contentsOf: url!)
self.userImage.image = UIImage(data: data!)!
然后我在那里我要上传的图像的第二类:
class PhotoViewController: UIViewController, UIImagePickerControllerDelegate,
UINavigationControllerDelegate {
@IBOutlet weak var imagePicked: UIImageView!
@IBAction func openCameraButton(sender: AnyObject) {
if UIImagePickerController.isSourceTypeAvailable(.camera) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .camera;
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
}
}
@IBAction func openPhotoLibraryButton(sender: AnyObject) {
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .photoLibrary;
imagePicker.allowsEditing = true
self.present(imagePicker, animated: true, completion: nil)
}
}
private func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
imagePicked.image = image
dismiss(animated:true, completion: nil)
}
@IBAction func saveButt(sender: AnyObject) {
let imageData = UIImageJPEGRepresentation(imagePicked.image!, 0.6)
let compressedJPGImage = UIImage(data: imageData!)
UIImageWriteToSavedPhotosAlbum(compressedJPGImage!, nil, nil, nil)
let alert = UIAlertView(title: "Wow",
message: "Your image has been saved to Photo Library!",
delegate: nil,
cancelButtonTitle: "Ok")
alert.show()
}
当我点击openCamara按钮和openLibrary按钮时,它每次都会执行正确的功能,但是当我选择照片时(无论是来自相机还是图库),在ImageView中都不会显示任何内容,并且我收到的错误是:“创建未知类型的图像格式是错误 “ 而且我不会将图像发送回Rest API,因为我不知道该怎么做。
有人可以帮助我显示哪里的错误是不让我在ImageView上的屏幕上显示图片?
如果可行,有人可以告诉我将该图像返回到Rest API的最佳方法吗?
答
@Zita诺列加埃斯特拉达 这个代码将删除所有错误。
func isValidData(_ result: Result<Any>, completion: @escaping (_ : NSDictionary?, _ : Bool?, _ : NSError?) -> Void) {
self.getValidDict(result, completion: {(dict, error) in
var success = false
var errorNew = error
if dict != nil {
success = ((dict?["dataKey"] as AnyObject).boolValue)!
if !success {
errorNew = NSError(domain: "", code: 400, userInfo: [NSLocalizedDescriptionKey: dict?.value(forKey: "messageKey")! as Any])
}
}
completion (dict, success, errorNew)
})
}
func getValidDict(_ result: Result<Any>, completion: @escaping (_ : NSDictionary?, _ : NSError?) -> Void) {
var dict: NSDictionary!
let errorNew = result.error as NSError?
if let json = result.value {
dict = (json as AnyObject).value(forKey: "responseKey") as! NSDictionary
}
completion (dict, errorNew)
}
答
使用Alamofire将图像上传到服务器。
试试这个代码:
func uploadImage {
uploadImage(image: image, completion: { (success, error) in
if success! {
} else {
}
})
}
func uploadImage(_ image: UIImage!, completion: @escaping (_ : Bool?, _: NSError?) -> Void) {
let parameters: Parameters = ["image": image]
Alamofire.upload(multipartFormData: {
multipartFormData in
// For Image
for (key, value) in parameters {
if value != nil {
if let imageData = UIImageJPEGRepresentation(value!, 0.5) {
multipartFormData.append(imageData, withName: key, fileName: "file.png", mimeType: "image/png")
}
}
}
}, to: "apiName", method: .post, encodingCompletion: {
encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.response {
[weak self] response in
guard self != nil
else {
return
}
upload.responseJSON(completionHandler: { response in
self?.isValidData(response.result, completion: {(dict, success, error) in
completion (success, error)
})
})
}
case .failure(let encodingError):
print("error:\(encodingError)")
completion (false, encodingError as NSError?)
}
})
}
非常感谢,这是非常有用的,我很感激它! :D –
永远欢迎亲爱的:) –
我有一个问题,你在哪里声明isValidData?因为在我的代码中抱怨,告诉我我的班级没有这个名字的成员。 –