从ImageView将图像上载到Web服务

时间:2017-09-01 04:46:45

标签: swift rest uiimageview uiimagepickercontroller

我尝试上传设备相机拍摄的图像,或者从设备图库中选择,然后在屏幕上显示ImageView,最后将其上传到Rest API。我已经在Rest API中存储了一个默认图像,我的应用程序已经加载了这个图像,但是当我尝试更改图像时,我遇到了问题。

这是Post 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的最佳方式吗?

2 个答案:

答案 0 :(得分:1)

使用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?)
            }
        })
    } 

答案 1 :(得分:1)

<@> @Zita Noriega Estrada 此代码将删除您的所有错误。

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)
    }