如何在swift中使用alamofire上传图库图片

Posted

技术标签:

【中文标题】如何在swift中使用alamofire上传图库图片【英文标题】:how to upload gallery image using alamofire in swift 【发布时间】:2018-07-10 08:23:39 【问题描述】:

我想使用Alamofire 快速上传来自imagePickerController 的图像。 我有两个函数,一个用于原始 api 调用,即ApplyLeave,另一个函数用于图像上传,即imageUploadrequestWith。在ApplyLeave 函数中,我要传递的图像参数之一是leave_certificate: gfg,这个leave_certificate 参数应该作为图像上传参数。我有用于图像上传的单独功能,如何将其用作ApplyLeave 函数中的参数,我在单独的类中有imagePickerController。我真的很困惑如何使用它以及如何合并所有东西。 请参阅我的以下代码。

class APIserviceprovider 

    static func ApplyLeave (
    startDate:String,
    endDate:String,
    description:String,
    reason:String,
    completion:@escaping (_ isSuccesfull :Bool, _ errorMessage :String?) ->()
    ) 
        guard let company_id = UserDefaults.standard.value(forKey: KeyValues.companyidKey) else return
        guard let user_id = UserDefaults.standard.value(forKey: KeyValues.userIdkey) else return
        guard let workspace_id = UserDefaults.standard.value(forKey: KeyValues.workspaceIdKey) else return

        let urlString = "\(ApiServiceProvider.BASE_URL + ApiServiceProvider.APPLY_LEAVE)"
        let parameters = [
            "leave_start_date": "\(startDate)",
            "leave_end_date": "\(endDate)",
            "leave_reason": "\(reason)",
            "leave_description": "\(description)",
            "user_id": "\(user_id)",
            "workspace_id": "\(workspace_id)",
            "company_id": "\(company_id)" ,
            "leave_certificate": "gfg"
        ]

    print(parameters)
    Alamofire.request(urlString, method:.post, parameters: parameters, encoding: URLEncoding.default).validate().responseJSON
        
        response in
            switch response.result 
            case .failure(let error):
                //completion(false, "Failed to Sign up")
                print(error)
                completion(false, "You failed to apply for leave.")
            case .success(let responseObject):
                //print("response is success:  \(responseObject)")
                completion(true, "You have successfully appplied for leave.")
                if let JSON = response.result.value 
                    let result = JSON as! NSDictionary
                    print(result)
                
            
        
    


    static func imageUploadrequestWith(
        endUrl: String,
        imageData: Data?,
        parameters: [String : Any],
        onCompletion: ((JSON?) -> Void)? = nil,
        onError: ((Error?) -> Void)? = nil
    ) 
        let url = "\(ApiServiceProvider.BASE_URL + ApiServiceProvider.APPLY_LEAVE)"

        let headers: HTTPHeaders = [
            /* "Authorization": "your_access_token",  in case you need authorization header */
            "Content-type": "multipart/form-data"
        ]

        Alamofire.upload(multipartFormData:  (multipartFormData) in
            for (key, value) in parameters 
                multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
            

            if let data = imageData
                multipartFormData.append(data, withName: "image", fileName: "image.png", mimeType: "image/png")
            

        , usingThreshold: UInt64.init(), to: url, method: .post, headers: headers)  (result) in
            switch result
            case .success(let upload, _, _):
                upload.responseJSON  response in
                    print("Succesfully uploaded")
                    if let err = response.error
                        onError?(err)
                        return
                    
                    onCompletion?(nil)
                
            case .failure(let error):
                print("Error in upload: \(error.localizedDescription)")
                onError?(error)
            
        
    



class ApplyLeaveController: UIViewController, UITextFieldDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate 

    func textFieldDidBeginEditing(_ textField: UITextField) 
        if textField == self.uploadFileButton 

            let myPickerController = UIImagePickerController()
            myPickerController.delegate = self;
            myPickerController.sourceType =  UIImagePickerControllerSourceType.photoLibrary
            self.present(myPickerController, animated: true, completion: nil)
        
    

    @objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
    
        let image_data = info[UIImagePickerControllerOriginalImage] as? UIImage
        let imageData:Data = UIImagePNGRepresentation(image_data!)!
        let imageStr = imageData.base64EncodedString()
        uploadFileButton.text = imageStr
        self.dismiss(animated: true, completion: nil)
    

【问题讨论】:

你不需要两个函数,一个就够了,从图库中挑选图像后将其存储在数组或uiimage中。 看看这个link 【参考方案1】:

选择图像后,像这样在 didFinishPickingMediaWithInfo 中调用 Api

   var currentSelectedImage = UIImage()
public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) 
     if let image = info[UIImagePickerControllerOriginalImage] as? UIImage 
         self.currentSelectedImage = image
         var parameters = [String:String]()
         let parameters = [
            "leave_start_date": "\(startDate)",
            "leave_end_date": "\(endDate)",
            "leave_reason": "\(reason)",
            "leave_description": "\(description)",
            "user_id": "\(user_id)",
            "workspace_id": "\(workspace_id)",
            "company_id": "\(company_id)" ,
            "leave_certificate": "gfg"
        ]
         Alamofire.upload(multipartFormData:  (multipartFormData) in
            multipartFormData.append(UIImageJPEGRepresentation(self.currentSelectedImage, 0.5)!, withName: "image", fileName: "image.png", mimeType: "image/jpeg")
          for (key, value) in parameters 
            multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
            
         , to: "your url",
           headers: nil)
         (result) in
            switch result 
            case .success(let upload, _, _):
                upload.uploadProgress(closure:  (Progress) in
                     print("Upload Progress: \(Progress.fractionCompleted)")
                )
                upload.responseJSON  response in
                    if let JSON = response.result.value 
                         print("JSON: \(JSON)")
                     
                
            case .failure(let encodingError):
                 print(encodingError)
            
        
     else 
    
    dismiss(animated: true, completion: nil)

【讨论】:

以上是关于如何在swift中使用alamofire上传图库图片的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Swift 4 中使用 Alamofire 上传具有其他参数的多个图像

如何使用 Alamofire (post) 上传图片?

如何使用 Alamofire 5.0.0-beta.3 (Swift 5) 上传图片(多部分)

Swift 4:如何使用 Alamofire 在参数中发布文件?

如何使用 alamofire 将多个 PDF 文件上传到服务器? #Swift 4 #IOS [重复]

如何在 Alamofire 中上传文件并在参数中传递数据 - swift 5