2

I have an api in my swift app that needs some extra authorization. There are some examples provided by the service but none in swift.

My Code:

    let request = NSURLRequest(URL: NSURL(string: "https://www.kimonolabs.com/api/au4sl00w?apikey=iFotcJDm95fB6Ua7XiZRDZA0jl3uYWev")!)

Example in Python

import urllib2
request = urllib2.Request("https://www.kimonolabs.com/api/au4sl00w? apikey=iFotcJDm95fB6Ua7XiZRDZA0jl3uYWev", headers={"authorization" : "Bearer    A5ve02gq40itf0eoYfT5ny6drZwcysxx"})
contents = urllib2.urlopen(request).read()

Example in Ruby

require 'rest_client'
response = RestClient.get('https://www.kimonolabs.com/api/au4sl00w?apikey=iFotcJDm95fB6Ua7XiZRDZA0jl3uYWev', {'authorization' => 'Bearer A5ve02gq40itf0eoYfT5ny6drZwcysxx'});
print(response);

Example in R

library('RCurl')
library('rjson')
json <- getURL('https://www.kimonolabs.com/api/au4sl00w?apikey=iFotcJDm95fB6Ua7XiZRDZA0jl3uYWuc',
  httpheader = c(authorization='Bearer A5ve02gq40itf0eoYfT5ny6drZwcysxx'))
obj <- fromJSON(json)
print(obj)

So, how can I do this in Swift?

Ismael Padilla
  • 5,246
  • 4
  • 23
  • 35
Nathan Schafer
  • 273
  • 4
  • 15

1 Answers1

7

Modified answer from: "How to make an HTTP request + basic auth in Swift".

I believe it would look something like this (and assuming your API_ID is au4sl00w) :

let token = "yourToken"

// create the request
let url = NSURL(string: "https://www.kimonolabs.com/api/au4sl00w?apikey=iFotcJDm95fB6Ua7XiZRDZA0jl3uYWev")
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "GET"
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")

And be sure to create a new access token, now that this one is public :)

Community
  • 1
  • 1
Louis Tur
  • 1,303
  • 10
  • 16
  • I am not sure what you mean. I don't want a username and password. I need this token Bearer A5ve02gq40itf0eoYfT5ny6drZwcysxx as authorisation. Can you still help? – Nathan Schafer Jan 15 '15 at 06:08
  • Oh! Im sorry, I misread. But I think it's about the same steps, just update: `request.setValue("Bearer \(yourToken)", forHTTPHeaderField: "Authorization"` (I'll be sure to update my answer if this was in fact what you were looking for) – Louis Tur Jan 15 '15 at 06:14
  • Thanks for that. With my request (First code in question) what do I need to change. – Nathan Schafer Jan 15 '15 at 06:18
  • Hello, Don't worry. I figured it out. let request = NSMutableURLRequest(URL: NSURL(string: "https://www.kimonolabs.com/api/au4sl00w?apikey=iFotcJDm95fB6Ua7XiZRDZA0jl3uYW")!) – Nathan Schafer Jan 15 '15 at 06:29
  • Thanks for updating your question also. Very helpful! – Nathan Schafer Jan 15 '15 at 06:31