Skip to content

Instantly share code, notes, and snippets.

@niwatako
Created August 6, 2016 05:26
Show Gist options
  • Save niwatako/b55e4323941c48ad42559241a3125b19 to your computer and use it in GitHub Desktop.
Save niwatako/b55e4323941c48ad42559241a3125b19 to your computer and use it in GitHub Desktop.
ViewDidLoadでアカウントを取得して、getHomeTimeline()でそのアカウントを使う、エラーはアラートに #CodePiece #realm_swift #realm_jp
class TimelineViewController: UITableViewController {
var account: ACAccount?
override func viewDidLoad() {
super.viewDidLoad()
let accountStore = ACAccountStore()
let accountType = accountStore.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierTwitter)
accountStore.requestAccessToAccountsWithType(accountType, options: nil) { (granted, error) -> Void in
if granted {
let accounts = accountStore.accountsWithAccountType(accountType)
if let account = accounts.first as? ACAccount {
self.account = account
self.getHomeTimeline()
} else {
self.showAlert("No Twitter account")
}
} else {
self.showAlert("No account access")
}
}
}
func getHomeTimeline() {
let requestURL = NSURL(string: "https://api.twitter.com/1/statuses/home_timeline.json")
let request = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: .GET, URL: requestURL, parameters: nil)
request.account = account
request.performRequestWithHandler { (data, response, error) -> Void in
if let error = error {
self.showAlert(error.localizedDescription)
return
}
do {
let results = try NSJSONSerialization.JSONObjectWithData(data, options: [])
if let results = results as? NSDictionary {
let errors = results["errors"] as! [[String: AnyObject]]
let message = errors.last!["message"] as! String
self.showAlert(message)
return
}
let timeline = results as! [[String: AnyObject]]
let realm = try! Realm()
try! realm.write {
timeline.forEach { (tweetDictionary) -> () in
let tweet = Tweet(tweetDictionary: tweetDictionary)
realm.add(tweet)
}
}
} catch let error as NSError {
self.showAlert(error.localizedDescription)
}
}
}
func showAlert(message: String) {
dispatch_async(dispatch_get_main_queue()) {
let alertController = UIAlertController(title: "Error", message: message, preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment