Created
August 6, 2016 06:06
-
-
Save niwatako/c980287fc569511f4a3531e11ed392db to your computer and use it in GitHub Desktop.
TimelineViewControllerは 1−6.タイムラインを表示 まで行くと多分こうなる #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 timeline: Results<Tweet>? | |
var notificationToken: NotificationToken? | |
var account: ACAccount? | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// アカウントを取得してメンバ変数 var account: ACAccount? に格納 | |
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") | |
} | |
} | |
// TableViewにTimelineCellを表示する準備 | |
tableView.registerNib(UINib(nibName: "TimelineCell", bundle: nil), forCellReuseIdentifier: "timelineCell") | |
tableView.rowHeight = 90 | |
tableView.estimatedRowHeight = 90 | |
// RealmからcreatedAtでソートしたタイムラインを取得するクエリを発行 | |
let realm = try! Realm() | |
// RealmからTweetクラスのオブジェクトを検索 | |
timeline = realm.objects(Tweet).sorted("createdAt", ascending: false) | |
// クエリに変更があった場合に通知を受けて実行したい処理を登録 | |
notificationToken = timeline?.addNotificationBlock { [weak self] (change) in | |
switch change { | |
case .Initial(_): | |
self?.tableView.reloadData() | |
case .Update(_, deletions: _, insertions: _, modifications: _): | |
self?.tableView.reloadData() | |
case .Error(_): | |
return | |
} | |
} | |
} | |
// MARK: - Twitter API | |
// メンバ変数 var account: ACAccount? をつかってAPIからタイムラインを取得 | |
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) | |
} | |
} | |
} | |
// MARK: - Alert (TwitterAPIのエラー、OSに設定されたTwitterアカウントの取得エラーを表示) | |
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) | |
} | |
} | |
// MARK: - UITableViewDataSource | |
override func numberOfSectionsInTableView(tableView: UITableView) -> Int { | |
return 1 | |
} | |
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { | |
return timeline?.count ?? 0 | |
} | |
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { | |
let cell = tableView.dequeueReusableCellWithIdentifier("timelineCell", forIndexPath: indexPath) as! TimelineCell | |
let tweet = timeline![indexPath.row] | |
cell.nameLabel.text = tweet.name | |
cell.tweetTextView.text = tweet.text | |
NSURLSession.sharedSession().dataTaskWithRequest(NSURLRequest(URL: NSURL(string: tweet.iconURL)!)) { (data, response, error) -> Void in | |
if let _ = error { | |
return | |
} | |
dispatch_async(dispatch_get_main_queue()) { | |
let image = UIImage(data: data!)! | |
cell.iconView.image = image | |
} | |
}.resume() | |
return cell | |
} | |
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { | |
return UITableViewAutomaticDimension | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment