Swift 2 How do you add authorization header to POST request - post

When making a particular POST request, Firefox (FF) dev tools shows a req. header named "Authorization" with a value of "Bearer X" where X is the access token received upon login. When I edit this request in FF and remove the "Authorization" line, I get a 400 error. When I put it back in, 200 and all is well. I haven't yet, however, figured out how to set this request header programmatically without getting 400.
Also, FF tools as a "Request Body" of {"source":"desktop - profile 2015"}. I'm assuming this is JSON. I've tried posting this in several ways (see code) but have had no success.
// the following fields are set in the object "Request"'s initialization
let accessToken = "1,2,3456789012,3x4f560fa7a89e01a2;33ab4b4e5e67e8e9b9f0e1a23db45678f9a9a0ff" // replaced some characters for this StackOF posting
let authorization = "Bearer \(accessToken)"
let method = "POST"
let userID = "1234567"
let URL = NSURL(string: "https://www.somesite.com/apitun/profile/\(userID)hide")
// tried setting params to all of the following 4:
let params = ""
let params = "&_json={}"
let params = "&_json={\"source\":\"desktop profile - 2015\"}
let params = "&_json=%7B%22source%22%3A%22desktop%2Dprofile%202015%22%7D"
func execute() {
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: URL)
if authorization != "" {
request.addValue(authorization, forHTTPHeaderField: "Authorization")
}
request.HTTPMethod = self.method
request.HTTPBody = self.params.dataUsingEncoding(NSUTF8StringEncoding)
self.task = session.dataTaskWithRequest(request) {
(data, response, error) in
NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookies(self.cookies, forURL: self.URL, mainDocumentURL: nil)
if error == nil {
do {
self.responseHeaders = response as! NSHTTPURLResponse
self.cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookiesForURL(self.URL)!
self.statusCode = self.responseHeaders.statusCode
switch self.statusCode {
case 200:
self.contentsOfURL = try NSString(contentsOfURL: self.URL, encoding: NSUTF8StringEncoding)
case 400:
print("400: page not found")
case 404:
print("404: page not found")
case 407:
print("407: failed authenticate proxy credentials")
default:
print("unable to get statusCode")
}
} catch {
}
self.isRequesting = false
} else {
print(error)
}
}
self.task.resume()
}

let request = NSMutableURLRequest(URL: NSURL(string: fullURL)!)
let accessToken = "your access token"
request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")

Related

Retrieve cookies from HTTP request response in Swift

First time working on an apple swift project. I am building a library where I send an HTTP request to an API and I need to retrieve the cookies that are returned in the response but for some reason they are not being retrieved.
Below is the code that I have.
let url = URL(string: "http://192.168.1.118:500/initialise")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let parameters: [String: String] = [
"ApplicationID": app_id,
"DeviceID": "123456",
"AppVersion": app_version
]
request.setValue(api_key, forHTTPHeaderField: "authorisation-token")
//request.httpBody = parameters.percentEscaped().data(using: .utf8)
let postString = self.getPostString(params: parameters)
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) {data, response, error in
guard let data = data,
let response = response as? HTTPURLResponse,
error == nil else {
print("error", error ?? "Unknown Error")
return
}
guard(200...299) ~= response.statusCode else {
print("statusCode should 2xx, but is \(response.statusCode)")
print("response = \(response)")
return
}
print ("HTTP Status Code: " + String(response.statusCode))
print ("-------Cookies--------")
let cookieStorage = HTTPCookieStorage.shared
let cookies = cookieStorage.cookies(for: URL(string:"192.168.1.118:500")!) ?? []
for cookie in cookies {
if cookie.name == "SESSIONID" {
MyClass.SESSIONID = cookie.value
}
else if cookie.name == "DO-LB" {
MyClass.DOLB = cookie.value
}
}
I've tried changing the cookieStorage.cookies URL to include and the port number 500 and exclude it but unfortunately neither of which has worked.

Swift-4 : How to fetch data using POST request with Parameters in URLSession with "Content-Type" : "application/x-www-form-urlencoded"

Friends, I've gone through lot's of examples, which are available on S.O. Though I haven't received proper answer, and still I'm facing issue in getting data via api request using URLSession with Post request & passing parameters with it.
First, I'ld like to show you, what I have. tried till now...
func requestApiCall(){
let renewal_id = ""
let policy_no = ""
let client_name = ""
let client_id = ""
let product_name = ""
let created_date_from = ""
let created_date_to = ""
let policy_expiry_from = ""
let policy_expiry_to = ""
self.parameters = ["renewal_id":renewal_id,"policy_no":policy_no,"client_name":client_name,"client_id":client_id,"product_name":product_name,"created_date_from":created_date_from,"created_date_to":created_date_to,"policy_expiry_from":policy_expiry_from,"policy_expiry_to":policy_expiry_to]
let config = URLSessionConfiguration.default
config.httpAdditionalHeaders = [
"Accept" : "application/json",
"Content-Type" : "application/x-www-form-urlencoded"
]
let session = URLSession(configuration: config)
let Url = String(format: "http://myapi-url");
let serviceUrl = URL(string: Url)
var request = URLRequest(url: serviceUrl!)
print(request.url!)
request.httpMethod = "POST"
request.timeoutInterval = 60
request.httpBody = try! JSONSerialization.data(withJSONObject: parameters!, options: [])
let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
if error == nil{
print(response!)
}
else {
print(error?.localizedDescription as Any)
}
print(response!)
guard let httpResponse = response as? HTTPURLResponse, let receivedData = data
else {
print("error: not a valid http response")
return
}
switch (httpResponse.statusCode)
{
case 200: //The request was fulfilled
let response = NSString (data: receivedData, encoding: String.Encoding.utf8.rawValue)
if response == "SUCCESS"
{
print("Network - HandShaking Successfull...!!!")
}
else{
print("Network - HandShaking is not successfull...!!!")
}
case 400:
print("response-status - 400 : The request had bad syntax or was inherently impossible to be satisfied.")
case 500:
print("\nresponse-status - 500 : Internal Server Error...!!!")
default:
print("response-status - Unknown : Received Response => \(httpResponse.statusCode)")
}
})
task.resume()
}
After running above function, I'm getting httpResponse.statusCode = 500
But when I run this in postman, I get response properly, as aspected.
Postman Api-Request
Also I have tried to generate code-snippets through postman...which are as follow...
func postmanSnippetApiCall(){
let headers = [
"Content-Type": "application/x-www-form-urlencoded",
"cache-control": "no-cache",
"Postman-Token": "5d571157-86c5-4eac-ba6d-b00779ae5dbd"
]
let postData = NSMutableData(data: "renewal_id=".data(using: String.Encoding.utf8)!)
postData.append("&policy_no=".data(using: String.Encoding.utf8)!)
postData.append("&client_name=".data(using: String.Encoding.utf8)!)
postData.append("&client_id=".data(using: String.Encoding.utf8)!)
postData.append("&product_name=".data(using: String.Encoding.utf8)!)
postData.append("&created_date_from=".data(using: String.Encoding.utf8)!)
postData.append("&created_date_to=".data(using: String.Encoding.utf8)!)
postData.append("&policy_expiry_from=".data(using: String.Encoding.utf8)!)
postData.append("&policy_expiry_to=".data(using: String.Encoding.utf8)!)
postData.append("&undefined=undefined".data(using: String.Encoding.utf8)!)
let request = NSMutableURLRequest(url: NSURL(string: "http://myapiurl")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse)
}
})
dataTask.resume()
}
But in postman generated code snippet, I'm receiving error on this line i.e request.httpBody = postData as Data and error is this one : Cannot convert value of type 'NSMutableData' to type 'Data' in coercion
If I use thirdParty Library i.e Alamofire, then I'm able to get data very easily.
Alamofire code snippet...runs perfectly..& gives proper response.
func apiRequestByAlamofire(){
let urlString = "http://myapiurl"
let params: [String: Any]? = ["renewal_id":"","policy_no":"","client_name":"","client_id":"","product_name":"","created_date_from":"","created_date_to":"","policy_expiry_from":"","policy_expiry_to":""]
Alamofire.request(urlString, method: .post, parameters: params).responseJSON { response in
print(response) //Here getting perfect response successfully...!!!
}
}
But still I'm struggling this via URLSession...!!!
And still I doubt, that why I'm getting too much problems, while doing with URLSession.
Friends for above my doubt, please I'm open to your suggestions, as well as please help me out to understand it.
Don't know, where am I going wrong. please help me out here.
After searching and fighting a lot with this I have come up with this solution:
guard var components = URLComponents(url: URL(string: "http://example.com")!, resolvingAgainstBaseURL: true)
else { fatalError("Couldn't create URLComponents") }
components.queryItems = params.map { k, v in URLQueryItem(name: k, value: v) }
var request = URLRequest(url: baseUrl.appendingPathComponent(path.rawValue))
request.httpBody = Data(components.query!.utf8)
request.httpMethod = "POST"
The "example.com" can literally be that, because I'm just using URLComponents to encode the parameters.
I am giving you simple function, You can edit this function as per your requirement. You can change your URL and params as well. And in the response, I have written two-line if you are taking JSON array from the server then use the first one if you are taking object then second one else remove Both lines.
func abc() {
let request = NSMutableURLRequest(url: URL(string: "Your URL")!)
request.httpMethod = "POST"
let postString = "param_name_one=\( value_1 )&param_name_two=\(value_2)&........."
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if(error != nil){
// Show Error Message
} else{
do {
//For JSON ARRAY
let jsonItem = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSArray
let json = jsonItem[0] as AnyObject
//For JSON object
let json_object = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as AnyObject
print(json_object)
} catch {
}
}
}
task.resume();
}

iOS curl -X POST integration in swift

Hi I want to integrate the Curl POST api in my code I don't have any idea about this could any please guide me how to integrate this in swift language
The below web service call I have integrate in my code, Have tried but didn't get the result
curl -X POST http://stf.rortechnologies.com/api/session.js --data '{"user": {"email":"XXXXXX", "password":"XXXXXX"}}' -H "Content-Type:application/json"
let parameters = ["email":"admin.test#stf.com", "password":"password"]
let header = ["user": parameters]
//create the url with URL
let url = URL(string: "http://stf.rortechnologies.com/api/session.js")! //change the url
//create the session object
let session = URLSession.shared
//now create the URLRequest object using the url object
var request = URLRequest(url: url)
request.httpMethod = "POST" //set http method as POST
do {
request.httpBody = try JSONSerialization.data(withJSONObject: header, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
} catch let error {
print(error.localizedDescription)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
//create dataTask using the session object to send data to the server
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
guard error == nil else {
return
}
guard let data = data else {
return
}
do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
print(json)
// handle json...
}
} catch let error {
print(error.localizedDescription)
}
})
task.resume()
here am getting the null response
App Transport Security (ATS)
You are calling a http url and not a https url. In production always https should be used. This is enforced by iOS.
For testing purposes one can declare exceptions in the info.plist, the documentation can be found here:
https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW33
JSON Encoding/Decoding
In Swift there is a convenient way to encode/decode JSON with JSONEncode/JSONDecoder. A simple solution might look like the one below.
Define Parameter Structs
struct Login: Encodable {
let user: User
}
struct User: Encodable {
let email: String
let password: String
}
Define Return Struct
struct Result: Decodable {
//add expected JSON fields here
}
Rest Call
private func makeRestCall() {
let login = Login(user: User(email: "admin.test#stf.com", password: "password"))
guard let loginJson = try? JSONEncoder().encode(login) else { return }
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
guard let url = URL(string: "<add some valid url here>") else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = loginJson
let dataTask = session.dataTask(with: request) { (data, response, error) in
if let response = response as? HTTPURLResponse {
if response.statusCode == 200 {
guard let data = data else {
print ("call failed - no data returned")
return
}
guard let result = try? JSONDecoder().decode(Result.self, from: data) else {
print ("json decoding failed")
return
}
print ("call succesfully returned \(result)")
} else {
print ("call failed with status \(response.statusCode)")
}
} else {
print ("call failed: no http response")
}
}
dataTask.resume()
}
Check in a HTTPS Proxy
To make sure that you send the correct data, you could use a HTTPS proxy software. There it would look like this:

IOS url request issue

I want to send mobile number and password to the server in the ios app. Backend team has given postman API like below image.
Success when sent as form-data
Below Swift URL request failing, What I'm doing wrong here?
func sendReq() {
let Url = String(format: "http://xxxxxxx/mobile/request_otp")
guard let serviceUrl = URL(string: Url) else { return }
let parameterDictionary = ["mobile_number" : "xxxxxxxxxx", "password" : "12345678"]
var request = URLRequest(url: serviceUrl)
request.httpMethod = "POST"
request.cachePolicy = .useProtocolCachePolicy
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
// params dict as data
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameterDictionary, options: []) else {
return
}
request.httpBody = httpBody
// session
let session = URLSession.shared
//data task
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
}
catch {
print(error)
}
}
}.resume()
}
But above API call throwing error like
{
error = TRUE;
message = "All fields Required!";
}
Set the Content-Type HTTP header:
request.allHTTPHeaderFields = ["Content-Type": "application/json"]
This way you inform the server that you are sending JSON.
Can you try:
{\"mobile_number\":xxxxxxxxxx,\"password\":12345678}
and select Application/Json instead of text.

Uber Invalid OAuth 2.0 credentials provided Uber Authentication In ios Swift

I'm implementing the Uber's Request Endpoint in my iOS (Swift) App. The Request API/Endpoint requires the user authentication with the app, here is the doc.
For this I'm using this Oauth2.0 library
What I did is
successfully integrated the Library in my project (xCode) with the help of given installation instructions.
In My AppDelegate
let uber_OAuth_Settings = [
"client_id": "XXXXXXX9vtKzobvXXXXXX",
"client_secret": "EXXXXXXXXyFUNCa_Wez6AXXXXXXXnrXtxus",
"authorize_uri": "https://login.uber.com/oauth/authorize",
"token_uri": "https://login.uber.com/oauth/token",
"redirect_uris": ["jamesappv2://oauth/callback"], // don't forget to register this scheme
] as OAuth2JSON
var oauth:OAuth2CodeGrant!
in my method didFinishLaunchingWithOptions of Appdelegate
oauth = OAuth2CodeGrant(settings: uber_OAuth_Settings)
oauth.viewTitle = "Uber Login Service" // optional
oauth.verbose = true // For Logs
Don't forget to register url scheme i.e ("redirect_uris": ["jamesappv2://oauth/callback"])
goto your app's Target -> info Tab -> Url Types -> Click (+), image attached
In AppDelegate add method given Below and Handle the Callback Url
func application(application: UIApplication,
openURL url: NSURL,
sourceApplication: String?,
annotation: AnyObject?) -> Bool {
// you should probably first check if this is your URL being opened
var splitUrl = url.absoluteString!.componentsSeparatedByString(":")
if splitUrl[0] == ("jamesappv2") {
oauth.handleRedirectURL(url)
}
return true
}
Now in my viewController I did like this on myBtnClick
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let url = appDelegate.oauth.authorizeURL()
UIApplication.sharedApplication().openURL(url)
appDelegate.oauth.onAuthorize = { parameters in
println("Did authorize with parameters: \(parameters)")
self.navigationController?.pushViewController(self.PersonalDriverUber_VC, animated: true)
//On Authorization Goto another ViewController using pushViewController of navigationcontroller Method
}
appDelegate.oauth.onFailure = { error in // `error` is nil on cancel
if nil != error {
println("Authorization went wrong: \(error!.localizedDescription)")
}
}
Here is my debug log, I'm getting the valid response:
OAuth2: Handling redirect URL jamesappv2://oauth/callback?state=4B0EB812&code=0sXXXXXXTX7yEbS1XXXXXHuw
OAuth2: Successfully validated redirect URL
OAuth2: Authorizing against https://login.uber.com/oauth/token?state=38158941&grant_type=authorization_code&code=0sXXXXXXXX1jxTrdFQT9Huw&client_secret=EIXXXXXXXNCa_Wez6XXXXXw0BlnrXtxus&client_id=fXXXXXXXy2LOUo9vtKXXXXXQ1nUDO&redirect_uri=jamesappv2%3A%2F%2Foauth%2Fcallback
OAuth2: Exchanging code 0swNXXXXX7yXXXXXXdFQT9Huw with redirect jamesappv2://oauth/callback for token at Optional("https://login.uber.com/oauth/token")
OAuth2: Did receive access token: Dfq3XXXXXXuWgpaqFXXXXXXXgXW, refresh token: EmStT7FEXHRMlS8odPzs1nsha0ObjK
Did authorize with parameters: [token_type: Bearer, expires_in: 2592000, access_token: XXXXXXOZuWgXXXXXXXXuJYOmgXW, refresh_token: EXXXXXHRMlS8oXXXXXXXa0ObjK, scope: profile, last_authenticated: 1430121470]
Notice I'm getting the valid access_token
Here I'm stuck
As per DOCs says in STEP4 *USE BEARER TOKEN
Pass the access_token returned in the response in the Authorization header with the type Bearer to make requests on behalf of a user.*
curl -H 'Authorization: Bearer YOUR_ACCESS_TOKEN' 'https://api.uber.com/v1/products?latitude=37.7759792&longitude=-122.41823'
I am not getting the point. How should I pass the access_token in Header with type Bearer? I have done like below
func callRequestAPI(url:String){
let request = appDelegate.oauth.request(forURL: NSURL(string:url)!)
request.HTTPMethod = "POST"
let postString = "product_id="+selectedUberProductId+"&start_latitude="+start_lat+"&start_longitude="+start_lng+"&end_latitude="+end_lat+"&end_longitude="+end_lng
println(postString)
let tempData: NSData = appDelegate.oauth.accessToken.dataUsingEncoding(NSUTF8StringEncoding)!
let base64LoginString = tempData.base64EncodedStringWithOptions(nil)
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("Bearer \(base64LoginString)", forHTTPHeaderField: "Authorization")
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { data, response, error in
if error != nil {
println("error=\(error)")
return
}
println("response = \(response)")
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("responseString = \(responseString)")
}
task.resume()
}
but I'm getting following response
response = <NSHTTPURLResponse: 0x1a284b50> { URL: https://sandbox-api.uber.com/v1/requests } { status code: 401, headers {
"Content-Length" = 75;
"Content-Type" = "application/json";
Date = "Mon, 27 Apr 2015 10:22:01 GMT";
Server = nginx;
"Strict-Transport-Security" = "max-age=31536000; includeSubDomains; preload";
"x-uber-app" = "uberex-sandbox";
"x-xss-protection" = "1; mode=block";
} }
responseString = Optional({"message":"Invalid OAuth 2.0 credentials provided.","code":"unauthorized"})
Finally I have done it :)
I changed the method like below and it Worked
func callRequestAPI(url:String){
var configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
var session = NSURLSession(configuration: configuration)
let params:[String: AnyObject] = [
"product_id" : selectedUberProductId,
"start_latitude" : start_lat,
"start_longitude" : start_lng,
"end_latitude" : end_lat,
"end_longitude" : end_lng]
let request = appDelegate.oauth.request(forURL: NSURL(string:url)!)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.allZeros, error: &err)
let task = session.dataTaskWithRequest(request) {
data, response, error in
if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode != 202 {
println("response was not 202: \(response)")
return
}
}
if (error != nil) {
println("error submitting request: \(error)")
return
}
// handle the data of the successful response here
var result = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: nil) as! NSDictionary
println(result)
if let request_id: String = result["request_id"] as? String{
println(request_id)
}
if let driver: String = result["driver"] as? String{
println(driver)
}
if let eta: Int = result["eta"] as? Int{
println(eta)
}
if let location: String = result["location"] as? String{
println(location)
}
if let status: String = result["status"] as? String{
println(status)
}
if let surge_multiplier: Int = result["surge_multiplier"] as? Int{
println(surge_multiplier)
}
if let vehicle: String = result["vehicle"] as? String{
println(vehicle)
}
}
task.resume()
}
here is the Response I Got, Parsing is also given in my above method
{
driver = "<null>";
eta = 15;
location = "<null>";
"request_id" = "ea39493d-b718-429f-8710-00a34dcdaa93";
status = processing;
"surge_multiplier" = 1;
vehicle = "<null>";
}
Enjoy
Updated for Swift 2. I used the same setup and library for oauth that Qadir describes in his question. I updated his request to work in Swift 2. Hope this helps others.
uberRequest:
let params:[String:AnyObject] = [
"product_id" : uberProduct,
"start_latitude" : userLat,
"start_longitude" : userLng,
"end_latitude" : barLat,
"end_longitude" : barLng]
let urlPath = "https://sandbox-api.uber.com/v1/requests"
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
var session = NSURLSession(configuration: configuration)
guard let endpoint = NSURL(string: urlPath) else { print("Error creating endpoint");return }
let request = appDelegate.oauth.request(forURL: NSURL(string:urlPath)!)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField:"Content-Type")
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.PrettyPrinted)
request.HTTPMethod = "POST"
print("Prepare to make request -> \(request)")
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in
if error != nil{
print("Error -> \(error)")
return
}
do {
let result = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
print("Result -> \(result)")
} catch {
print("Error -> \(error)")
}
}
task.resume()
It returns:
Result -> Optional(["driver": <null>, "request_id": 5834384c-7283-4fe6-88a7-e74150c6ab30, "surge_multiplier": 1, "location": <null>, "vehicle": <null>, "status": processing, "eta": <null>])
To use the token just follow step 5 of the instructions in the OAuth2 library, like you did before you started to try to sign it yourself a second time. The request has already been signed and has the Bearer token set up, there is nothing left to do for you:
let url = NSURL(string: "https://api.uber.com/v1/products?latitude=37.7759792&longitude=-122.41823")
let req = appDelegate.oauth.request(forURL: url)
// customize your request, if needed. E.g. for POST:
req.HTTPMethod = "POST"
// send the request
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(req) { data, response, error in
if nil != error {
// something went wrong
}
else {
// check the response and the data
// you have just received data with an OAuth2-signed request!
}
}
task.resume()

Resources