Created
August 6, 2016 05:15
-
-
Save niwatako/eb55a9fd5ed1403aa29b55df364694cf to your computer and use it in GitHub Desktop.
TwitterのAPIを使ってタイムラインを取得する処理 func getHomeTimeline() を作成 #CodePiece #realm_swift #realm_jp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import Accounts | |
import Social | |
import RealmSwift | |
class TimelineViewController: UITableViewController { | |
var account: ACAccount? | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
} | |
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