如何使用带有基本身份验证的alamofire上传图像? [英] how to upload an Image using alamofire with basic authentication?

查看:108
本文介绍了如何使用带有基本身份验证的alamofire上传图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用带有此代码的alamofire 4.7.1上传图像,但是老实说,我怀疑我没有编写正确的代码来上传图像

I am trying to upload an image using alamofire 4.7.1 with this code, but to be honest I suspect that I didn't write a right code to upload the image

func uploadDefect(defectRemark: String, defectLocation: String, defectImage: UIImage, fileNameImage: String, completion: @escaping(_ errorMessage: String?) -> Void) {

        guard let imgData = defectImage.jpeg(.medium) else {return}

        let urlUpload = URLService.uploadDefect.endPoint

        let username = "admin"
        let password = "1234"

        let credentialData = "\(username):\(password)".data(using: String.Encoding.utf8)!
        let base64Credentials = credentialData.base64EncodedString(options: [])
        let headers = ["Authorization": base64Credentials]
        let parameters : [String:Any] = ["defect_remark" : defectRemark, "defect_location": defectLocation, "tenant_id" : tenantID]

        let url = try! URLRequest(url: URL(string: urlUpload)!, method: .post, headers: headers)

        Alamofire.upload(
            multipartFormData: { multipartFormData in
                multipartFormData.append(imgData, withName: "file", fileName: fileNameImage, mimeType: "image/jpeg")

                for (key, value) in parameters {
                    multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
                }
        },
            with: url,
            encodingCompletion: { encodingResult in

                switch encodingResult {
                case .success(let upload, _, _):
                    upload.responseJSON { response in

                        print("upload response: \(response)")

                        switch response.result {
                        case .failure(let error) :
                            let message : String
                            if let httpStatusCode = response.response?.statusCode {
                                switch(httpStatusCode) {
                                case 404:
                                    message = "File not found"
                                case 500 :
                                    message = "Internal Error"
                                default:
                                    message = "Connection issue, please make sure you have a good internet access, or please contact IT Support."
                                }
                            } else {
                                message = error.localizedDescription
                            }

                            completion(message)
                        case .success( _) :
                            completion(nil)
                        }
                    }

                case .failure(let encodingError):
                    let messageEncodingError = encodingError.localizedDescription
                    print(encodingError)
                    completion(messageEncodingError)
                    break
                }
        }
        )




    }

.success似乎被触发了

it seems that case .success is triggered

case .success( _) :
  completion(nil)
}

但似乎没有错误,但是我没有从服务器获得预期的JSON响应.

but seems no error, but I didn't get the expected JSON response from the server.

这是调试区域中的错误日志

here is the error log from the debugging area

我怀疑我没有编写正确的代码来使用通过基本身份验证的alamofire上传图像服务器.你能帮我这个吗?

I suspect that I didn't write a right code to upload the image server using alamofire using basic authentication. could you please help me with this one?

推荐答案

像这样更改您的Authorization:

let headers = ["Authorization": "Basic \(base64Credentials)"]

您还可以使用Alamofire来创建身份验证标头,例如:

You can also make use of Alamofire to create the authentication header like:

var headers: HTTPHeaders = [:]

if let authorizationHeader = Request.authorizationHeader(user: user, password: password) {
    headers[authorizationHeader.key] = authorizationHeader.value
}

这篇关于如何使用带有基本身份验证的alamofire上传图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆