Convert Curl Command to swift using Alamofire
In your code you are using method: .post
, where it is not needed. Also there are some wrong parameter names (e.g. "ClientID": clientID
should be renamed to "client_id": clientID
). This might be a cause of 400 or 404 status codes.
At least this GET request worked for me without 400 or 404 status codes:
Alamofire
.request(
"https://api.everypixel.com/oauth/token",
parameters:[
"client_id" : clientID,
"client_secret" : clientSecret,
"grant_type" : "client_credentials"
]
)
.responseString { response in
switch response.result {
case .success(let value):
print("from .success \(value)")
case .failure(let error):
print(error)
}
}
How to convert CURL request to Swift using Alamofire?
It looks like you want to set header Authorization
to DirectLogin token="eyJhbGciOiJIUzI1NiIsInR5cCI6wkpeVeCJr.eyIiOiIifQ.MV-E150zMCrk6VrWv"
. You can do that like this:
let loginToken = "DirectLogin token=\"eyJhbGciOiJIUzI1NiIsInR5cCI6wkpeVeCJr.eyIiOiIifQ.MV-E150zMCrk6VrWv\""
...
@IBAction func callAPIAction(_ sender: Any) {
Alamofire
.request(
self.url,
headers: [
"Authorization": self.loginToken,
"Content-Type": "application/json"
]
)
.responseString {
response in
switch response.result {
case .success(let value):
print("from .success \(value)")
case .failure(let error):
print(error)
}
}
}
...
swift ios get convert curl to swift curl using alamofire
You should try using a Custom Per Request Header.
Create a dictionary for your custom headers:
let headers: HTTPHeaders = ["Accept": "application/json"]
HTTPHeaders is just a dictionary of strings:
public typealias HTTPHeaders = [String: String]
Then pass the headers as an argument in your call to create a request:
// In the empty quotes, enter you API url info.
let urlString = "" Alamofire.request(urlString, headers: headers).responseJSON { ... }
To make sure your headers are being sent, you can use debugPrint:
let headers: HTTPHeaders = ["Accept": "application/json"]
//In the empty quotes, enter you API url info.
let request = Alamofire.request("", headers: headers)
.responseJSON { response in
// ...
}
debugPrint(request)
From there, you are ready to create the POST call.
Convert cURL to HTTP request (Swift 3) using Alamofire
I got the solution, here it is:
//GET ACCESS TOKEN
let parameters = ["password" : K_CLIENT_SECRET, "username" : K_CLIENTID_SANDBOX, "grant_type":"client_credentials"]
let str = "\(K_CLIENTID_SANDBOX):\(K_CLIENT_SECRET)"
let utf8str = str.data(using: String.Encoding.utf8)
//let basic_auth_token = utf8str?.base64EncodedStringWithOptions(NSData.Base64EncodingOptions(rawValue:
0))
let basic_auth_token = utf8str?.base64EncodedString(options:
NSData.Base64EncodingOptions(rawValue: 0))
let headers = ["Accept" : "application/json", "Authorization" :"Basic "+basic_auth_token!]
Alamofire.request("https://api.sandbox.paypal.com/v1/oauth2/token",
method: .post, parameters: parameters, encoding:URLEncoding.default,
headers: headers)
.responseJSON { response in
SwiftLoader.hide()
print(response.request as Any) // original URL request
print(response.response as Any) // URL response
print(response.result.value as Any) // result of response serialization
}
Generate cURL output from Alamofire request?
I just did this and it works:
let someRequest = Alamofire.request(.POST, servicePath, parameters: requestParams, encoding: .JSON)
debugPrint(someRequest)
Convert cUrl command to HTTP Request in Swift
I know that this is not using Alamofire but this is how I would achieve it.
import PlaygroundSupport
import Foundation
let key = "2s7Ymz8gu7_8XuTEeMFVmxJBLmyNNL4n8"
let secret = "8XuXAs8K37ejtYqvsEue2p"
let url = URL(string: "https://api.ote-godaddy.com/v1/domains/available?domain=example.guru&checkType=FULL")
var request = URLRequest(url: url!)
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("sso-key \(key):\(secret)", forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard error == nil else {
print(error!)
return
}
guard let data = data else {
print("Data is empty")
return
}
let json = try! JSONSerialization.jsonObject(with: data, options: [])
print(json)
}
task.resume()
PlaygroundPage.current.needsIndefiniteExecution = true
ios swift 4 - Alamofire post parameter with UIimage file (convert curl to alamofire)
let data = UIImagePNGRepresentation(image)!
let headers = ["Authorization": "...",
"X-Storage-Id": "..."]
let parameters = ["fileItems[0].replacing": "true",
"fileItems[0].path": "/path/something"]
Alamofire.upload(multipartFormData: { form in
form.append(data,
withName: "fileItems[0]",
fileName: "file1.png",
mimeType: "image/png")
parameters.forEach({
form.append($0.value.data(using: .utf8)!, withName: $0.key)
})
}, to: "https://example.com/uploadfiles", method: .post, headers: headers) { result in
//switch result { ... }
}
Related Topics
Firebase Remove Snapshot Children Swift
Trying to Display Location Data from Firebase to Mapkit
Swift Use 'Is' for Function Type, Compiler Behavior Is Different with Runtime
Avplayer Won't Let Me Access Url
Cleanly Handling /Usr/Local/ with Swift Package Manager and Libevent
Arkit: How to Tell If User's Face Is Parallel to Camera
Error Is Value of Type 'Authdataresult' Has No Member 'Uid'
Swift Corebluetooth Reading a Float Array from Ble
Swift- Mkmapkit View Only One City
Swift Variable Declaration Meaning
Swift Pattern Match on Array<Any>
How to Programmatically Scroll iOS Wkwebview, Swift 4
Comparing Time Without Date Swift3
Preparing for Swift 4 - Unsafemutablepointer Migration to Unsafemutablebufferpointer
How Does Swift's Int Literal to Float Inference Work
How to Change Bordercolor When Button.Ishighlighted
Swift Running Code in Periodically Background
Swift Protocol That Is Using an Enum with Generic Associated Type