ios - 如何使用 alamofire 通过基本身份验证上传图像?

标签 ios swift alamofire

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

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




    }

似乎触发了case.success

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

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

这是来自调试区域的错误日志

enter image description here

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

最佳答案

像这样更改您的授权:

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

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

var headers: HTTPHeaders = [:]

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

关于ios - 如何使用 alamofire 通过基本身份验证上传图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50342214/

相关文章:

ios - Azure ios应用程序身份验证错误

macos - 如何在 Mac OS X 中创建我自己的 "shell"命令行程序

swift - GoogleSignIn 不适用于 YouTube API (Swift)

ios - 在 objective-c 中抛出自定义异常

ios - xcode: ios 动态框架在提交时显示 "Entitlements 0"

ios - 从 TableView 中选择时在多个详细 View 之间切换

swift - 如何以编程方式从搜索栏转到显示屏幕

Swift:无法链接 DispatchGroup

ios - 在 Swift 中从 json 解析我的数据有什么问题?

ios - AlamoFireObjectMapper 无法在对象数组中保存数据响应