How to upload MultipartFormData
with authentication using Alamofire? The part that I don't understand is where to put .authenticate(user: username, password: password).
? This is how I usually upload pictures using MultipartFormData
:
Alamofire.upload(
.POST, "https://myExampleUrl/photo/upload", headers: headers, multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: "default".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"_formname")
multipartFormData.appendBodyPart(fileURL: fileUrl, name: "photo")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseString { response in
debugPrint(response)
}
case .Failure(let encodingError):
print(encodingError)
}
}
)
I think it's possible to add authentication process into headers?
Haven't had much time to explore the API for rilbits.com
. When I visited the address in Safari, I got the following error:
Please add 'Authorization' or 'X-Access-Token' header to your request
This suggests 2 options for you:
Authorization
header along with the upload request.Here's how you can send the Authorization
header (second option):
let username = "username"
let password = "password"
let credentialData = "\(username):\(password)".dataUsingEncoding(NSUTF8StringEncoding)!
let base64Credentials = credentialData.base64EncodedStringWithOptions([])
let headers = ["Authorization": base64Credentials]
Alamofire.upload(
.POST,
"https://rilbits.com/supersafe/photo/upload",
headers: headers,
multipartFormData: { multipartFormData in
let data = "default".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
multipartFormData.appendBodyPart(data: data, name: "_formname")
multipartFormData.appendBodyPart(fileURL: fileURL, name: "photo")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseString { response in
debugPrint(response)
}
case .Failure(let encodingError):
print(encodingError)
}
}
)
Full disclosure: