Skip to content

Instantly share code, notes, and snippets.

@ayn
Created September 17, 2015 18:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ayn/4ac59f17fd529c4829e2 to your computer and use it in GitHub Desktop.
Save ayn/4ac59f17fd529c4829e2 to your computer and use it in GitHub Desktop.
Twitter accounts picker, Garmin Connect devs need this shit.
//
// ViewController.swift
// TwitterAccountsDemo
//
import UIKit
import Accounts
class ViewController: UIViewController {
var twitterAccount: ACAccount? = nil {
didSet {
print("Twitter username = \(twitterAccount?.username)")
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
loadTwitterAccounts()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loadTwitterAccounts() {
let accountStore = ACAccountStore()
let twitterAccountType = accountStore.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierTwitter)
accountStore.requestAccessToAccountsWithType(twitterAccountType, options: nil) { (granted, _) -> Void in
if (granted) {
let accounts = accountStore.accountsWithAccountType(twitterAccountType)
switch accounts.count {
case 0:
break
case 1:
guard let account = accounts.first as? ACAccount else { return }
self.twitterAccount = account
default:
self.chooseAccount(accounts)
}
} else {
// User declined permission
}
}
}
func chooseAccount(accounts: [AnyObject]) {
let alert = UIAlertController.init(title: "You have multiple Twitter accounts", message: "Please pick one", preferredStyle: .ActionSheet)
for account in accounts {
guard let account = account as? ACAccount else { return }
let action = UIAlertAction.init(title: account.username, style: .Default, handler: { (action) -> Void in
self.twitterAccount = account
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
})
})
alert.addAction(action)
}
alert.addAction(UIAlertAction.init(title: "Cancel", style: .Cancel, handler: { (action) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
})
}))
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.showViewController(alert, sender: self)
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment