简体   繁体   中英

Alamofire 5.0+ MultipartFormData upload bearer token

I have gotten everything to work on the alamofire multipart form data upload but adding the bearer token. We use Oauth 2.0 and our files need the token to authenticate in our systems. I have only found a way to pass the username and password which doesnt work in our current system. Is there a way to pass the bearer token to the php?

   AF.upload(multipartFormData: { multipartFormData in

    for (key, value) in parameters {
        multipartFormData.append(value.data(using: .utf8)!, withName: key)
    }

if let jpegData = image.jpegData(compressionQuality: 1.0) {
        multipartFormData.append(jpegData, withName: "file", fileName: "image", mimeType: "image/jpeg")
    }
}, to: "https:website" )
.uploadProgress{ progress in
//print("Upload Progress: \(self.progress.fractionCompleted)")
}
.response { response in
if response.response?.statusCode == 200 {
    print("OK. Done")
    print((NSString(data: response.data!, encoding: 
String.Encoding.utf8.rawValue)! as String))
}else if response.response?.statusCode == 406{
    print("error")
    DispatchQueue.main.sync{
        let alert = UIAlertController(title: "Error", message: 
"Person has not been set up.", preferredStyle: .alert)

        alert.addAction(UIAlertAction(title: "close", style: .default, handler: { action in
             DispatchQueue.main.async{
                self.progressUiView.isHidden = true
                self.dismiss(animated: true, completion: nil)
            }
        }))

        self.present(alert, animated: true)
    }
}else{
    print(response.response?.statusCode)
}
}

You need to add the Authorization token to the headers . Here's how:

let token = "your_token_here"
AF.upload(multipartFormData: { multipartFormData in
    //...
}, to: "https:website", headers: ["Authorization": "Bearer \(token)"])
    .response { response in
    //...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM