0x7fs
4/3/2015 - 12:02 PM

Get Tweets for certain user in Swift

Get Tweets for certain user in Swift

let username = "myHandle" // Put Twitter handle without @ here.

let accountStore = ACAccountStore()
let accountType = accountStore.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierTwitter)

accountStore.requestAccessToAccountsWithType(accountType, options: nil) { granted, error in
    if granted == true {
        if let account = accountStore.accountsWithAccountType(accountType).first as? ACAccount {
            
            let finalURL = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=" + username + "&count=100"
            let request = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: .GET, URL: NSURL(string: finalURL)!, parameters: nil)
            
            request.account = account
            request.performRequestWithHandler { data, response, requestError in
                var parseError: NSError?
                if let parsedData = NSJSONSerialization.JSONObjectWithData(data, options: .allZeros, error: &parseError) as? [AnyObject] {
                    println(parsedData)
                } else {
                    // coundn't parse JSON.
                }
            }
        } else {
            // couldn't get logged in user
        }
    } else {
        // user wasn't logged in.
    }
}