Ian McKinnerney
Ian McKinnerney

Reputation: 33

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

Upvotes: 2

Views: 763

Answers (1)

Frankenstein
Frankenstein

Reputation: 16381

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
    //...

Upvotes: 3

Related Questions