【问题标题】:Uploading an image into a Web Service from an ImageView将图像从 ImageView 上传到 Web 服务
【发布时间】:2017-09-01 04:46:44
【问题描述】:

我正在尝试上传由设备相机拍摄的图像,或从设备库中选择的图像,稍后使用 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 的最佳方法吗?

【问题讨论】:

    标签: swift rest uiimageview uiimagepickercontroller


    【解决方案1】:

    @Zita Noriega 埃斯特拉达 此代码将删除您的所有错误。

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

    【讨论】:

      【解决方案2】:

      使用 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?因为在我的代码中抱怨这一点,告诉我我的班级没有该名称的成员。
      • 我添加了一个新代码,可以帮助您消除所有错误。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-11
      • 2013-04-07
      • 2011-12-31
      • 1970-01-01
      相关资源
      最近更新 更多