I am struggling to authenticate using a POST request to an API.
Documentation says that I need to pass in
"Request Headers: Content-Type: application/x-www-form-urlencoded, Request Body: client_id=CLIENT_ID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN."
I cannot get it to work on the iOS app however trying with Postman works fine.
let headers: HTTPHeaders = [
"Contenty-Type": "application/x-www-form-urlencoded"
]
let params = [
"client_id": "123",
"refresh_token": "123"
]
private func getAccess() {
Alamofire.request(getRequest ,method: .post, parameters: params, headers: headers)
.responseJSON { (response) in
switch response.result {
case .success(let json):
print(json)
DispatchQueue.main.async {
}
case .failure(let error):
print(error)
}
}
You are not passing grant_type parameter. Try changing your params dictionary to this:
let params = [
"client_id": "123",
"grant_type": "refresh_token",
"refresh_token": "123"
]
Related
I'm new to Alamofire and now using Alamofire 5. I want to create a POST request with multipart form data, but there's a specific requirement for the JSON body. Here it is:
"item": [
{
"name": "Upload image",
"request": {
"method": "POST",
"header": [],
"body": {
"mode": "formdata",
"formdata": [
{
"key": "files[]",
"type": "file",
"src": []
},
{
"key": "mode",
"value": "public",
"type": "text"
}
]
},
"url": {
"raw": "https://jsonplaceholder.typicode.com/api/image/upload",
"protocol": "https",
"host": [
"jsonplaceholder",
"typicode",
"com"
],
"path": [
"api",
"image",
"upload"
]
}
},
"response": []
},
]
Anyone can help me how to post the data but with multipart form data? Please help.
(It's okay if the POST request is using URLSession)
Whatever I understand from your question and comments, I have created a method from your previous question.
func postImage(images: [UIImage],imgName : [String]) {
var arrFormData = [[String:Any]]()
var imgDataArray: [Data] = []
for image in images {
guard let imgData = image.jpegData(compressionQuality: 0.50) else { return }
imgDataArray.append(imgData)
}
let param1: [String: Any] = [
"key":"files[]",
"type": "file",
"src": imgName
]
let param2: [String: Any] = [
"key": "mode",
"value": "public",
"type": "text"
]
var arrParam = [[String:Any]]()
arrParam.append(param1)
arrParam.append(param2)
arrFormData.append(contentsOf: arrParam)
var param : [String:Any] = [:]
if let theJSONData = try? JSONSerialization.data(
withJSONObject: arrFormData,
options: []) {
let theJSONText = String(data: theJSONData,
encoding: .ascii)
print("JSON string = \(theJSONText!)")
param = ["formData" : theJSONText ?? ""]
}
print(param)
Alamofire.upload(multipartFormData: {
multipartFormData in
for i in 0..<images.count{
if let imageData = images[i].jpegData(compressionQuality: 0.6) {
multipartFormData.append(imageData, withName: "file", fileName: "name.png", mimeType: "image/png")
}
}
for (key, value) in param {
multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
}
}, usingThreshold: 10 * 1024 * 1024,to: apiurl, method: .post, headers: headers, encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON {
response in
print(response.result)
}
case .failure(let encodingError):
print(encodingError)
}
})
}
Image upload along with parameters not working with the below code i tried.
let testImage = UIImage(named: "sayHi")
let headers: HTTPHeaders = [
"Content-type": "multipart/form-data",
"Content-lenth" : "\(testImage?.pngData()?.count ?? 0)",
"Accept": "application/json",
]
AF.upload(
multipartFormData: { multipartFormData in
multipartFormData.append("10".data(using: .utf8)!, withName: "pickerId")
multipartFormData.append("100".data(using: .utf8)!, withName: "walkerRfid")
multipartFormData.append(testImage!.pngData()!, withName: "photo" , fileName: "file.png", mimeType: "image/png")
},
to: "https://zb9.amazonaws.com/data/savePickerData", method: .post , headers: headers)
.validate(statusCode: 200..<300)
.response { resp in
switch resp.result{
case .failure(let error):
print(error)
case.success( _):
print("🥶🥶Response after upload Img: \(resp.result)")
}
}
Response :
responseValidationFailed(reason: Alamofire.AFError.ResponseValidationFailureReason.unacceptableStatusCode(code: 502))
I'm fairly new to the swift and I'm facing a problem with Alamofire what I'm trying to do is sending a get request with json body but I'm stuck heres my code:
struct request {
func getMessage(message:String){
let parameters: [String:Any] = [
"message" : [
"text": message,
"type":"text"
],
"type":"message",
"recipentId":"",
"info": [
"token":""
]
]
makeRequest(parameters: parameters)
}
func makeRequest(parameters:[String:Any]){
AF.request("https://bot.ortus4c.com/api/botController/token/5cc1f42e66d0ba0001dbf944",method: .post,parameters: parameters).response{
response in
debugPrint(response)
}
}
after executing this code i get:
[Request]: POST https://bot.ortus4c.com/api/botController/token/5cc1f42e66d0ba0001dbf944
[Request Body]:
info%5Btoken%5D=&message%5Btype%5D=text&message%5Btext%5D=Karakter&recipentId=&type=message
[Response]:
[Status Code]: 415
[Headers]:
Accept: application/json
Content-Length: 0
Date: Sat, 07 Mar 2020 19:10:23 GMT
Server: cloudflare
cf-cache-status: DYNAMIC
cf-ray: 57069dc3eaccad06-OTP
expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
x-b3-traceid: b10ba988c0249901
[Response Body]:
None
[Data]: None
[Network Duration]: 0.3303520679473877s
[Serialization Duration]: 0.0s
[Result]: success(nil)
i dont get any result body compared to what expect when i send this request over postman:
"result": {
"messages": [
{
"type": "text",
"text": "Karakter Analizine Hoşgeldiniz. Analize başlamak için \"karakter\" yazınız"
},
{
"type": "text",
"text": "Test"
}
],
"tag": [
"start",
"finish"
],
"conversation_id": "5e63f302dc4bec0001883f01",
"intent_name": "Default Karakter",
"intent_id": "5ccb46ef66d0ba0001dbfcdf",
"intent_score": null,
"current_flow_id": "ee52db21-dae1-4587-80cd-7649798dddce1583608578222"
}
so how can i send this post request with this given body below:
let parameters: [String:Any] = [
"message" : [
"text": message,
"type":"text"
],
"type":"message",
"recipentId":"",
"info": [
"token":""
]
]
Now i have sent the request and got a body looking like this:
"result": {
"messages": [
{
"extra": {},
"question": "Adınız ?",
"type": "text",
"values": [
{
"text": ""
}
],
"askCount": 1,
"text": "Adınız ?",
"waitUserInput": true
}
],
"tag": [
"start",
"p_firstName",
1
],
"conversation_id": "5e63ffa0dc4bec0001883f10",
"intent_name": "Karakter Analizi",
"intent_id": "5cc20ae266d0ba0001dbf946",
"intent_score": "62.0",
"current_flow_id": "62ac3ac8-0cd7-43e5-b92b-f119d49c40d41583611808850"
}
how can i print the question variable to a label on my screen ?
Response code 415 means Unsupported Media Type and the Accept header of the response lets you know that the sever expects data to be sent as JSON. All you have to do is to let Alamofire know that it should encode parameters as JSON in the request body
AF.request("https://bot.ortus4c.com/api/botController/token/5cc1f42e66d0ba0001dbf944",
method: .post,
parameters: parameters,
encoding: JSONEncoding.default).response { response in
debugPrint(response)
}
you need to mention the encoding type as well while sending request. since your parameters data is json add encoding parameter as encoding: JSONEncoding.default
for example i have used as:
manager.request(url, method: httpMethod,
parameters: parameters,
encoding: JSONEncoding.default,
headers: configuredHeader)
.validate(statusCode: 200..<300)
.responseJSON(completionHandler: { [weak self] response in
self?.handleNetworkResponse(response: response, networkCompletionHandler: networkCompletionHandler)
})
I found some thread the same problem but their answers not works for me.
I have a post request to check user login.
Url form :
"http://support.xxx.xx:8031/serpapi/login/checkLogin"
Parameters :
["contextInfo" :
["clientId": "1000000", "orgId": "1000001",
"warehouseId": "1000002", "roleId": "0"],
"userName": "hanoiaUser", "password": "hanoiaUser"]
Request :
Alamofire.request(url!, method: .post, parameters: params).responseJSON { (response) in
print(response)
}
Error response :
FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))
Why am i getting this error? and how to solve it ?
Edit : i'm tried with POSTMAN and it return response :
Content-Type : application/json
Body : raw - json
{
"contextInfo" : {
"clientId":1000000,
"orgId": 1000001,
"warehouseId": 1000002,
"roleId": 0
},
"userName": "hanoiaUser",
"password": "hanoiaUser"
}
RESPONSE :
{
"success": true,
"data": [
{
"userId": 1000003,
"userName": "hanoiaUser",
"token": "b7e804d25065e5c3ac97d765180b7986"
}
],
"error": null
}
Ok, finally I solved the problem
Here's new request :
Alamofire.request(url!, method: .post,encoding : JSONEncoding.default, headers: headers, parameters: params).responseJSON { (response) in
print(response)
}
With Headers :
let headers = [
"Content-Type": "application/json"
]
Set the request header like :
request.allHTTPHeaderFields = ["Content-Type":"application/json"]
I'm having hard time doing something simple. The data I want to send is the following:
{
"nickname":"Rado",
"social": {
"data: {
"accesstoken":"xx",
"applicationId":"xx",
"userId":"xx"
},
"type":"whatever"
}
}
Currently I'm doing that:
let params = [
"nickname": userName,
"social": [
"type": "whatever",
"data": [
"userId": accessToken.userID,
"accesstoken": accessToken.tokenString,
"applicationId": accessToken.appID
]
]
]
Alamofire.request(.POST, "url/users", parameters: params, headers: nil)
.responseJSON { response in
}
As a response I get this:
{
"nickname":"Rado",
"social[data][userId]":"xx",
"social[data][applicationId]":"xx",
"social[data][accesstoken]":"xx",
"social[type]":"something"
}
Any advice will be appreciated!
The solution turned out to be really simple. I was missing encoding: .JSON
Alamofire.request(.POST, "url/users", parameters: params, headers: nil, encoding: .JSON)
.responseJSON { response in
}