我正在使用名为(p2/OAuth2)的cocoapod来登录 GitHub 的帐户。我正在玩游戏是因为我想知道OAuth2的工作原理。
以下是我到目前为止在视图控制器(UIViewController
)中拥有的内容。
import UIKit
import p2_OAuth2
class ViewController: UIViewController {
// MARK: - Variables
let oauth2 = OAuth2CodeGrant(settings: [
"client_id": "xxxxxx",
"client_secret": "xxxxxxxx",
"authorize_uri": "https://github.com/login/oauth/authorize",
"token_uri": "https://github.com/login/oauth/access_token", // code grant only
"redirect_uris": ["myapp://oauth/callback"], // register your own "myapp" scheme in Info.plist
"scope": "user repo:status",
"secret_in_body": true, // Github needs this
"keychain": false, // if you DON'T want keychain integration
] as OAuth2JSON)
// MARK: - IBOutlet
// MARK: - IBAction
@IBAction func loginTapped(_ sender: UIBarButtonItem) {
oauth2.logger = OAuth2DebugLogger(.trace)
oauth2.authorize() { authParameters, error in
if let params = authParameters {
print("Authorized! Access token is \(self.oauth2.accessToken ?? "")")
print("Authorized! Additional parameters: \(params)")
}
else {
print("Authorization was cancelled or went wrong: \(String(describing: error))")
}
}
}
// MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
}
}
我想知道的是我成功登录GitHub帐户后如何返回视图控制器。到目前为止,我将被重定向到我在GitHub的开发人员网站上注册的URL。我想我需要在Info
下注册一个回调URL方案。这整个事情是全新的。所以我不确定该怎么做。谢谢。
更新
我通过info.plist添加了一组URL types
。 URL方案设置为myapp。以下是我在AppDelegate
中所拥有的。
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
if url.scheme == "myapp" && url.host == "oauth" {
//oauth2.handleRedirectURL(url)
let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "HomeView") as! UINavigationController
let viewController = controller.topViewController as! ViewController
window?.rootViewController = viewController
}
window?.makeKeyAndVisible()
return true
}
但是应用程序从未调用上述内容。
答案 0 :(得分:0)
我今天学到了一些新东西。
最后,我将以下代码行添加到AppDelegate
。
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
if url.scheme == "myapp" && url.host == "oauth" {
let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "HomeView") as! UINavigationController
let viewController = controller.topViewController as! ViewController
window?.rootViewController = viewController
}
window?.makeKeyAndVisible()
return true
}
如果我登录,则会得到如下提示。
点击“打开”时,我将重定向到我的视图控制器。