Skip to content

Instantly share code, notes, and snippets.

@willrichman
Created October 9, 2014 21:40
Show Gist options
  • Save willrichman/41a28da1d80185381079 to your computer and use it in GitHub Desktop.
Save willrichman/41a28da1d80185381079 to your computer and use it in GitHub Desktop.
fetch timeline
func fetchTimeLine (timelineType: String, userScreenname: String?, completionHandler: (errorDescription : String?, tweets : [Tweet]?) -> Void) {
let accountStore = ACAccountStore()
let accountType = accountStore.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierTwitter)
/* The following is asynchronous.
We will ask for account access, set up a twitter request, then call the home timeline */
accountStore.requestAccessToAccountsWithType(accountType, options: nil) { (granted: Bool, error: NSError!) -> Void in
if granted {
/* User gave access */
let accounts = accountStore.accountsWithAccountType(accountType)
self.twitterAccount = accounts.first as? ACAccount
/* Set up our twitter request, depending on which timeline is requested*/
var timelineURL : NSURL?
var parameters: Dictionary<String, String>?
switch timelineType {
case "HOME":
timelineURL = NSURL(string: "https://api.twitter.com/1.1/statuses/home_timeline.json")
case "USER":
timelineURL = NSURL(string: "https://api.twitter.com/1.1/statuses/user_timeline.json")
parameters = ["screen_name": userScreenname!]
println(userScreenname!)
default:
println("That timeline type doesn't work")
}
let twitterRequest = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: SLRequestMethod.GET, URL: timelineURL, parameters: parameters)
twitterRequest.account = self.twitterAccount
/* Make network call/request */
twitterRequest.performRequestWithHandler({ (timeLineJSONData, httpResponse, error) -> Void in
if error == nil {
switch httpResponse.statusCode {
case 200...299:
let tweets = Tweet.parseJSONDataIntoTweets(timeLineJSONData)
//var error : NSError?
//let JSONArray = NSJSONSerialization.JSONObjectWithData(timeLineJSONData, options: nil, error: &error) as? NSArray
//println(JSONArray)
//println(tweets?.count)
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
completionHandler(errorDescription: nil, tweets: tweets)
})
case 400...499:
println("error on the client")
println(httpResponse.description)
completionHandler(errorDescription: "The connection is having problems", tweets: nil)
case 500...599:
println("error on the server")
default:
println("something bad happened")
}
}
else {
println(error)
}
})
}
else {
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment