I am new in programming and in iOS development. I need to upload an image using Alamofire multipart form data, but I also need to input basic authentication header.
in this thread Alamofire 4.0 Upload MultipartFormData Header, it seems similar to my problem, the code is like this to upload
Alamofire.upload(multipartFormData:{ multipartFormData in
multipartFormData.append(unicornImageURL, withName: "unicorn")
multipartFormData.append(rainbowImageURL, withName: "rainbow")},
usingThreshold:UInt64.init(),
to:"https://httpbin.org/post",
method:.post,
headers:["Authorization": "auth_token"],
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
}
case .failure(let encodingError):
print(encodingError)
}
})
but I am confused how to put the basic authentication (i.e username & password) header. and I also confused where I should place my image data.
I find another thread that seems similar to my problem. here it is... How to upload MultipartFormData with authentication using Alamofire, the proposed solution is this code :
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)
}
}
)
but after fixing to the swift 4.1 it gives an error :
could you please help my problem? Thanks in advance :)
I have created this function: Hope it works for you:-
i finally found the answer, kindly please use my code below