Reputation: 499
Finding a simple answer to this has me finally asking.
What do I need to do/add to this to send the authentication with the url call? I'm all about it but just can't see the solution.
Set up the url with the necessary info, and make the call. This is the Curl call:
curl -v -X GET https://api.jsecoin.com/v1.7/balance/auth/0/ \
-H "Content-Type: application/json" \
-H "Authorization: JSE API Key"
Sample response:
{
"success": 1,
"notification": "Your balance is 99 JSE",
"balance": 99
}
This is my code snippet to do this in Swift 4, XCode 9.xx iOS 11.4, but I can't work out how to add in the authorization.
func makeGetCall() {
// Set up the URL request
//let todoEndpoint: String = "https://jsonplaceholder.typicode.com/todos/1"
let todoEndpoint: String = "https://api.jsecoin.com/v1.7/balance/auth/0/"
//-H \"Content-Type: application/json\" -H \"Authorization: xxxxxxxxxxxxxxxxx\""
guard let url = URL(string: todoEndpoint) else {
print("Error: cannot create URL")
return
}
let urlRequest = URLRequest(url: url)
// set up the session
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
config.httpAdditionalHeaders = [
"Content-Type": "application/json",
"Authorization": "xxxxxxxxxxxxxxxxxxxxx"
]
// make the request
let task = session.dataTask(with: urlRequest) {
(data, response, error) in
// check for any errors
guard error == nil else {
print("error calling GET on /todos/1")
print(error!)
return
}
This returns,
The todo is: ["notification": API Balance Failed: User API key credentials could not be matched, "fail": 1]
Could not get todo title from JSON
Upvotes: 0
Views: 988
Reputation: 3016
You need to set Header parameter in URLRequest not in URLSessionConfiguration
Here is your solution
func makeGetCall() {
// Set up the URL request
//let todoEndpoint: String = "https://jsonplaceholder.typicode.com/todos/1"
let todoEndpoint: String = "https://api.jsecoin.com/v1.7/balance/auth/0/"
//-H \"Content-Type: application/json\" -H \"Authorization: xxxxxxxxxxxxxxxxx\""
guard let url = URL(string: todoEndpoint) else {
print("Error: cannot create URL")
return
}
let urlRequest = URLRequest(url: url)
urlRequest.setValue(signature, forHTTPHeaderField: "Authorization")
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
// set up the session
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
// make the request
let task = session.dataTask(with: urlRequest) {
(data, response, error) in
// check for any errors
guard error == nil else {
print("error calling GET on /todos/1")
print(error!)
return
}
Upvotes: 2