Skip to content

Instantly share code, notes, and snippets.

@bright23
Created September 24, 2017 08:33
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 bright23/206786d7207ccef7dea0d5bcb324d5b8 to your computer and use it in GitHub Desktop.
Save bright23/206786d7207ccef7dea0d5bcb324d5b8 to your computer and use it in GitHub Desktop.
twitter連携 #swift #CodePiece
import UIKit
import Accounts
import Social
class SNSLinkManager: NSObject {
static func linkTwitterAccount(viewController: UIViewController, completion: @escaping (ACAccount?) -> ()) {
let accountStore = ACAccountStore()
let accountType = accountStore.accountType(withAccountTypeIdentifier: ACAccountTypeIdentifierTwitter)
accountStore.requestAccessToAccounts(with: accountType, options: nil) { (succes, error) in
if error != nil {
Logger.d("error::\(String(describing: error))")
completion(nil)
return
}
guard let accounts = accountStore.accounts(with: accountType) as? [ACAccount] else {
completion(nil)
return
}
if accounts.count == 0 {
completion(nil)
}
self.showAccountSelectSheet(viewController: viewController, accounts: accounts, completion: { (account) in
completion(account)
})
}
}
private static func showAccountSelectSheet(viewController: UIViewController, accounts: [ACAccount], completion: @escaping (ACAccount?) -> ()) {
let alert = UIAlertController(title: "Twitter",
message: "連携するアカウントを選択してください",
preferredStyle: .actionSheet)
for account in accounts {
alert.addAction(UIAlertAction(title: account.username, style: .default, handler: { (action) -> Void in
Logger.d("your select account is \(account)")
UserDefaultsUtil.setLinkedTwitterAccount(account)
completion(account)
}))
}
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action) -> Void in
completion(nil)
}))
viewController.present(alert, animated: true, completion: nil)
}
static func postTweet(viewController: UIViewController, account: ACAccount, message: String) {
let url = URL(string: "https://api.twitter.com/1.1/statuses/update.json")
let params = ["status" : message]
let request = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: .POST, url: url, parameters: params)
request?.account = account
request?.perform { (responseData, urlResponse, error) -> Void in
if error != nil {
Logger.d("error is \(String(describing: error))")
self.showAlert(viewController: viewController, message: "twitterへの投稿に失敗しました")
}
else {
if let responseData = responseData {
do {
let result = try JSONSerialization.jsonObject(with: responseData, options: .allowFragments)
Logger.d("result is \(result)")
} catch {
}
}
}
}
}
static func showAlert(viewController: UIViewController, message: String) {
let alert = UIAlertController(title: "Error",
message: message,
preferredStyle: .alert)
viewController.present(alert, animated: true, completion: nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment