Last active
November 29, 2015 08:29
-
-
Save SatoshiKawabata/c73542cb164d0abfe2a1 to your computer and use it in GitHub Desktop.
SwiftでTwitterAPIを使う
This file contains 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
// iOSに登録されているアカウントを選択して、 | |
// プロフィール画像とバナー画像を表示させるサンプルです | |
import UIKit | |
import Accounts | |
import Social | |
class ViewController: UIViewController { | |
let myTwitter:TwitterController = TwitterController() | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
myTwitter.getAccounts { (accounts: [ACAccount]) -> Void in | |
self.showAccountSelectSheet(accounts) | |
} | |
} | |
private func showAccountSelectSheet(accounts: [ACAccount]) { | |
let alert:UIAlertController = UIAlertController(title: "Twitter", | |
message: "アカウントを選択してください", | |
preferredStyle: .ActionSheet) | |
for account in accounts { | |
alert.addAction(UIAlertAction(title: account.username, | |
style: .Default, | |
handler: { (action) -> Void in | |
// アカウントの選択 | |
self.myTwitter.twAccount = account | |
// ユーザ情報を取得 | |
self.myTwitter.getUser(self.onGetUser) | |
})) | |
} | |
alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)) | |
self.presentViewController(alert, animated: true, completion: nil) | |
} | |
private func onGetUser(data: NSMutableDictionary) { | |
print(data) | |
// 画像を取得 | |
print(data["profile_image_url"]) | |
let urlStr:String = data["profile_image_url_https"] as! String | |
let url: NSURL = NSURL(string: urlStr)! | |
let imgData:NSData = NSData(contentsOfURL: url)! | |
let img:UIImage = UIImage(data: imgData)! | |
let imgView:UIImageView = UIImageView(image: img) | |
imgView.frame = CGRect(x: 10, y: 10, width: img.size.width, height: img.size.height) | |
self.view.addSubview(imgView) | |
// バナーを取得 | |
self.myTwitter.getBanner(self.onGetBanner) | |
// タイムラインを取得 | |
self.myTwitter.getTimeline(self.onGetTimeline) | |
} | |
private func onGetTimeline(data: NSMutableArray) { | |
print(data) | |
} | |
private func onGetBanner(data: NSMutableDictionary) { | |
print(data) | |
print(data["profile_image_url"]) | |
let urlStr:String = data["sizes"]!["mobile_retina"]!!["url"] as! String | |
let url: NSURL = NSURL(string: urlStr)! | |
let imgData:NSData = NSData(contentsOfURL: url)! | |
let img:UIImage = UIImage(data: imgData)! | |
let imgView:UIImageView = UIImageView(image: img) | |
imgView.frame = CGRect(x: 10, y: 300, width: img.size.width, height: img.size.height) | |
self.view.addSubview(imgView) | |
self.myTwitter.postTweet("test tweet from app") | |
} | |
override func didReceiveMemoryWarning() { | |
super.didReceiveMemoryWarning() | |
// Dispose of any resources that can be recreated. | |
} | |
} | |
class TwitterController { | |
var accountStore:ACAccountStore = ACAccountStore() | |
var twAccount: ACAccount? | |
internal func getAccounts(callback: [ACAccount] -> Void) { | |
let accountType:ACAccountType = accountStore.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierTwitter) | |
accountStore.requestAccessToAccountsWithType(accountType, options: nil) { (granted: Bool, error: NSError?) -> Void in | |
if error != nil { | |
print("error! \(error)") | |
return | |
} | |
if !granted { | |
print("error! Twitterアカウントの利用が許可されていません") | |
return | |
} | |
let accounts = self.accountStore.accountsWithAccountType(accountType) as! [ACAccount] | |
if accounts.count == 0 { | |
print("error! 設定画面からアカウントを設定してください") | |
return | |
} | |
print("アカウント取得完了") | |
callback(accounts) | |
} | |
} | |
// タイムラインを取得する | |
internal func getTimeline(callbabk: NSMutableArray -> Void) { | |
let url:NSURL = NSURL(string: "https://api.twitter.com/1.1/statuses/user_timeline.json")! | |
sendRequest(url, requestMethod: .GET, params: nil) { (responseData, urlResponse) -> Void in | |
do { | |
let result:NSMutableArray = try NSJSONSerialization.JSONObjectWithData(responseData, options: .AllowFragments) as! NSMutableArray | |
callbabk(result) | |
} catch { | |
print("エラーが発生しました") | |
} | |
} | |
} | |
// ユーザの情報を取得 | |
internal func getUser(callback: NSMutableDictionary -> Void) { | |
let url:NSURL = NSURL(string: "https://api.twitter.com/1.1/users/show.json")! | |
let params = ["screen_name" : (twAccount?.username)!] | |
sendRequest(url, requestMethod: .GET, params: params) { (responseData, urlResponse) -> Void in | |
do { | |
let result:NSMutableDictionary = try NSJSONSerialization.JSONObjectWithData(responseData, options: .AllowFragments) as! NSMutableDictionary | |
callback(result) | |
} catch { | |
print("エラーが発生しました") | |
} | |
} | |
} | |
// ユーザのバナー画像を取得 | |
internal func getBanner(callback: NSMutableDictionary -> Void) { | |
let url:NSURL = NSURL(string: "https://api.twitter.com/1.1/users/profile_banner.json")! | |
let params = ["screen_name" : (twAccount?.username)!] | |
sendRequest(url, requestMethod: .GET, params: params) { (responseData, urlResponse) -> Void in | |
do { | |
let result: NSMutableDictionary = try NSJSONSerialization.JSONObjectWithData(responseData, options: .AllowFragments) as! NSMutableDictionary | |
callback(result) | |
} catch { | |
print("エラーが発生しました") | |
} | |
} | |
} | |
// 投稿 | |
internal func postTweet(msg:String) { | |
let url:NSURL = NSURL(string: "https://api.twitter.com/1.1/statuses/update.json")! | |
let params = ["status" : msg] | |
sendRequest(url, requestMethod: .POST, params: params) { (responseData, urlResponse) -> Void in | |
// 投稿完了ハンドラ | |
print(responseData) | |
} | |
} | |
// リクエスト | |
private func sendRequest(url: NSURL, requestMethod: SLRequestMethod, params: AnyObject?, responseHandler: (responseData: NSData!, urlResponse: NSHTTPURLResponse!) -> Void) { | |
let request:SLRequest = SLRequest( | |
forServiceType: SLServiceTypeTwitter, | |
requestMethod: requestMethod, | |
URL: url, | |
parameters: params as? [NSObject : AnyObject] | |
) | |
request.account = twAccount | |
request.performRequestWithHandler { (responseData: NSData!, urlResponse: NSHTTPURLResponse!, error: NSError!) -> Void in | |
if error != nil { | |
print("error is \(error)") | |
} else { | |
responseHandler(responseData: responseData, urlResponse: urlResponse) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment