Tweet in iOS using Swift
First import `Accounts`, `Social` and get the account store
import Accounts
import Social
...
override func viewDidLoad() {
super.viewDidLoad()
accountStore = ACAccountStore()
}
Present the user a table view with all the Twitter account which are set in the Settings app
let accountType = accountStore!.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierTwitter)
println("accountType: (accountType)")
accountStore!.requestAccessToAccountsWithType(accountType, options: nil, completion: { [unowned self] (granted, error) in
println("granted: (granted)")
self.accounts = self.accountStore?.accounts
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
})
})
When the user selects an account she wants to user for tweeting, save the account id in
NSUserDefaults:
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let account = accounts![indexPath.row] as ACAccount
if activeAccountId == account.identifier {
activeAccountId = nil
} else {
activeAccountId = account.identifier
}
NSUserDefaults.standardUserDefaults().setObject(activeAccountId, forKey: kActiveAccountIdKey)
NSUserDefaults.standardUserDefaults().synchronize()
tableView.reloadData()
}
Now you are ready to tweet. Get the account and make a tweet request:
if let accountIdentifier = NSUserDefaults.standardUserDefaults().stringForKey(kActiveAccountIdKey) {
let parameters = ["status" : "Awesome Tweet!"]
let tweetRequest = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: .POST, URL: NSURL(string: "https://api.twitter.com/1.1/statuses/update.json"), parameters: parameters)
let account = accountStore?.accountWithIdentifier(accountIdentifier)
tweetRequest.account = account
tweetRequest.performRequestWithHandler { (tweetData, tweetResponse, tweetError) in
println("error: (tweetError)")
println("tweetResponse: (tweetResponse)")
}
}
Done.
If you have any comments about this post, you can find my on [Twitter](https://twitter.com/dasdom) or [App.net](https://app.net/dasdom).