Created
July 11, 2014 15:59
-
-
Save tfrank64/af2b5d8a583a01bd329b to your computer and use it in GitHub Desktop.
Swift API Requests with SLRequest
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The following two functions are based on: https://dev.twitter.com/docs/ios/making-api-requests-slrequest | |
func userHasAccessToTwitter() -> Bool { | |
return SLComposeViewController.isAvailableForServiceType(SLServiceTypeTwitter) | |
} | |
func fetchTimelineForUser(username: String) { | |
if userHasAccessToTwitter() { | |
var twitterAccountType: ACAccountType = self.accountStore.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierTwitter) | |
self.accountStore.requestAccessToAccountsWithType(twitterAccountType, options: nil, completion: { finished, error in | |
if finished { | |
var twitterAccounts: NSArray = self.accountStore.accountsWithAccountType(twitterAccountType) | |
var url: NSURL = NSURL(string: "https://api.twitter.com/1.1/statuses/user_timeline.json") | |
var params: [String: String] = [ "screen_name" : username, | |
"include_rts" : "0", | |
"trim_user" : "1", | |
"count" : "3"] | |
var apiRequest: SLRequest = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: SLRequestMethod.GET, URL: url, parameters: params) | |
apiRequest.account = twitterAccounts.lastObject as ACAccount | |
apiRequest.performRequestWithHandler( { data, response, error in | |
if data { | |
if response.statusCode >= 200 && response.statusCode < 300 { | |
// Used SwiftyJson to parse: https://github.com/lingoer/SwiftyJSON | |
let twitterData = JSONValue(data) | |
if twitterData { | |
println("Timeline Response: \(twitterData)") | |
} else { | |
println("JSON Error") | |
} | |
} | |
else { | |
println("Status code: \(response.statusCode) and error: \(error)") | |
} | |
} | |
}) | |
} | |
else { | |
println(error.localizedDescription) | |
} | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment