Using the Swift playground to make request with bearer token

Assuming you have a bearer token and you want to call a resource passing that bearer token from a Swift Playround, here is a simple example of how it is done. Note the import XCPlayground so you run this in the playground:


import UIKit
import Foundation
import XCPlayground


let token = "abcXKabclhpY1LLI123LzXfdsKlabcXKabclhpY1LLI123LzXfdsKabcXKabclhpY1LLI123LzXfdsKabcXKabclhpY1LLI123LzXfdsKabcXKabclhpY1LLI123LzXfdsKabcXKabclhpY1LLI123LzXfdsKabcXKabclhpY1LLI123LzXfdsKabcXKabclhpY1LLI123LzXfdsKabcXKabclhpY1LLI123LzXfdsKabcXKabclhpY1LLI123LzXfdsKabcXKabclhpY1LLI123LzXfdsKabcXKabclhpY1LLI123LzXfdsKabcXKabclhpY1LLI123LzXfdsKabcXKabclhpY1LLI123LzXfdsKabcXKabclhpY1LLI123LzXfdsKabcXKabclhpY1LLI123LzXfdsKabcXKabclhpY1LLI123LzXfdsKabcXKabclhpY1LLI123LzXfdsKabcXKabclhpY1LLI123LzXfdsKabcXKabclhpY1LLI123LzXfdsKabcXKabclhpY1LLI123LzXfdsK"

let url = NSURL(string: "http://api.yourwebsite.com/api/Test/itemsByType/1")


let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "GET"
request.setValue( "Bearer \(token)", forHTTPHeaderField: "Authorization")

//The following is so I can test in Playground:
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.currentQueue()) { response, maybeData, error in
    if let data = maybeData {
        let contents = NSString(data:data, encoding:NSUTF8StringEncoding)
        println(contents)
    } else {
        println(error.localizedDescription)
    }
}

XCPSetExecutionShouldContinueIndefinitely()
 //end Playground specific connection code...

One thought on “Using the Swift playground to make request with bearer token

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s