いそぎ要点だけまとめます.
Swifter
mattdonnelly/Swifter
TwitterへのOAuth認証をいい感じにやってくれるiOS/macOS向けのライブラリです.
やり方
1. Swifterの導入
- まずは,GitHubレポジトリに飛んでプロジェクトをダウンロードして
SwifterMac
をビルドしてフレームワークを作る. - 自分のプロジェクトの
TARGETS
のFrameworks, Libraries, and Embedded Content
にドラッグ&ドロップして追加する. - ソースの必要なところで
import SwifterMac
.
CocoaPodsとかCarthageの方法は調べてください.
2. App Sandboxの設定
Signing & Capabilities
> App Sandbox
> Network
> Outgoing Connections (client)
にチェックを入れる
3. Twitter Appsでアプリを登録してKeyを手に入れる
4. Twitter AppsでCallback URLを設定する
swifter-[生成されたConsumer API Key]://
をCallBack URLとして追加
5. URL Schemesの追加
TARGETS
> Info
> URL Types
にURLSchemesを追加する.
swifter-[生成されたConsumer API Key]
を入力する.
6. AppDelegate.swift実装
AppDelegate.swift
import Cocoa
import SwifterMac
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
NSAppleEventManager.shared().setEventHandler(self, andSelector: #selector(handleEvent),
forEventClass: AEEventClass(kInternetEventClass),
andEventID: AEEventID(kAEGetURL))
LSSetDefaultHandlerForURLScheme("swifter" as CFString, Bundle.main.bundleIdentifier! as CFString)
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
return true
}
@objc func handleEvent(_ event: NSAppleEventDescriptor!, withReplyEvent: NSAppleEventDescriptor!) {
guard let callbackUrl = URL(string: "swifter-[生成されたConsumer API Key]://") else { return }
guard let urlString = event.paramDescriptor(forKeyword: AEKeyword(keyDirectObject))?.stringValue else { return }
guard let url = URL(string: urlString) else { return }
Swifter.handleOpenURL(url, callbackURL: callbackUrl)
}
}
7. ViewControllerの実装
ViewController.swift
import Cocoa
import Accounts
import SwifterMac
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
let swifter = Swifter(consumerKey: "[生成されたConsumer API Key]",
consumerSecret: "[生成されたConsumer Secret Key]")
let callbackUrl = URL(string: "swifter-[生成されたConsumer API Key]://")!
swifter.authorize(withCallback: callbackUrl, success: { (_, _) in
Swift.print("Success Authorizing")
// この後はもう好き放題やってケロ
}) { (error) in
Swift.print(error.localizedDescription)
}
}
}
たぶんこれでいけるはずです.