Uber Invalid OAuth 2.0 credentials provided Uber Authentication In ios Swift - ios

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()

Related

How to implement the Bearer Token to validate the API url

I set up the API and all, the only thing is Bearer Token I couldn't find any information about any code on how to implement it so it can validate the URL I am using as API.
do I need to create new swift file just for bearer token or I can write the code to the API swift file "the code below is api file"
static let shared = APICaller()
private let baseURL = "http://000.000.000.000:3030/api/"
private init() {}
var vehicles = [Vehicles]()
func getVehicles(for id: String, IMEI: Int, completed: #escaping (Result<[Vehicles],Errors>) -> Void ){
let endpoint = baseURL + "GetVehicle/?UserIdentificationValue=346HIU4623UIHG3I3I&IMEI=216216123612"
guard let url = URL(string: endpoint) else {
completed(.failure(.invalidURL))
return
}
let task = URLSession.shared.dataTask(with: url) { data, response, error in
if let _ = error {
completed(.failure(.unableToComplete))
return
}
guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
completed(.failure(.invalidResponse))
return
}
guard let data = data else {
completed(.failure(.invalidData))
return
}
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
self.vehicles = try JSONDecoder().decode([Vehicles].self, from: data)
DispatchQueue.main.async {
completed(.failure(.invalidData))
}
} catch {
completed(.failure(.invalidData))
}
}
task.resume()
Thanks In Advance
Also I am new to swift so I would appreciate if you can tell me my API code is correct or needs any fixes since its about receiving some car info and putting into a table view cell :)
I have attached the request including headers in which you need to pass Bearer token like did in below code
let headers = [
"content-type": "application/json",
"authorizetoken": "NjQzOPA2N0NDNDFAH4CNDk3R23F2FQUY0NjV3FFE=",
"cache-control": "no-cache",
]
let parameters = ["id":"123456789"] as [String : Any]
let postData = try? JSONSerialization.data(withJSONObject: parameters, options: [])
let request = NSMutableURLRequest(url: NSURL(string: "Your URL")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 120.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as? Data
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData

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 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.

Spotify API Authorization Error (Swift)

I've made a little App in Swift where a user can search the Spotify database for songs. I am using the Web API Console > Search for an Item. My problem is the new OAuth system where you have to sign-in and all that stuff. My authorization is ok, but when I'm trying to get an access token with the following code, it's returning me the following error: {"error":"server_error","error_description":"Unexpected status: 400"}. My code is:
let keys = "<MY_APPLICATION_KEYS>"
let url = NSURL(string: "https://accounts.spotify.com/api/token")
let session = URLSession.shared
let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "POST"
request.setValue("Basic \(keys)", forHTTPHeaderField: "Authorization")
request.setValue("client_credentials", forHTTPHeaderField: "grant_type")
let task = session.dataTask(with: request as URLRequest) { (data, response, error) in
guard let _: Data = data, let _: URLResponse = response, error == nil else {
print(error!)
return
}
let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("Data: \(dataString!)")
self.parseData(JSONData: data!)
}
task.resume()
}
var accessToken = ""
func parseData(JSONData : Data) {
do {
var readableJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as! JSONStandard
if let token = readableJSON["access_token"] as? String {
accessToken = token
}
print("Access Token: \(accessToken)")
updateTokenInFirebase()
}
catch{
print(error)
}
Any help would be very appreciated, thank you very much in advance!
Documentation of the Web API: Web API Link
I am using on the Client Credentials Flow the first method.
I know it's been ~1 year since you posted this but I had the same issue and after a few tries was able to get it. You can test this in Playground.
import Foundation
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
if let url = URL(string: "https://accounts.spotify.com/api/token") {
var postRequest = URLRequest(url: url)
postRequest.httpMethod = "POST"
let bodyParams = "grant_type=client_credentials"
postRequest.httpBody = bodyParams.data(using: String.Encoding.ascii, allowLossyConversion: true)
let id = "your client id"
let secret = "your secret"
let combined = "\(id):\(secret)"
let combo = "\(id):\(secret)".toBase64()
postRequest.addValue("Basic \(combo)", forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: postRequest) { (data, response, error) in
guard let data = data else {
return
}
print(String(data: data, encoding: String.Encoding.utf8)!)
}
task.resume()
}
extension String {
func fromBase64() -> String? {
guard let data = Data(base64Encoded: self) else {
return nil
}
return String(data: data, encoding: .utf8)
}
func toBase64() -> String {
return Data(self.utf8).base64EncodedString()
}
}
I know this is really late, but the issue is with this line:
request.setValue("client_credentials", forHTTPHeaderField: "grant_type")
According to the authorization guide, this should be in the body of the request, not the headers.

Swift 2 How do you add authorization header to POST request

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")

Resources