我正在使用名为 ( p2/OAuth2) 的 cocoapod 来登录 GitHub 的帐户。我只是在玩,因为我想知道 OAuth2 是如何工作的。
以下是目前我的 View Controller (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登录成功后如何回到view controller。到目前为止,我将被重定向到我在 GitHub 开发者网站上注册的 URL。我想我需要在 Info
下注册一个回调 URL 方案。这整件事是全新的。所以我不确定该怎么做。谢谢。
更新
我通过info.plist 添加了一组URL 类型
。 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
}
但应用程序从不调用上述内容。
最佳答案
我今天学到了一些新东西。
- 在 GitHub 的开发者网站上,我将回调 URL 设置为 myapp://oauth/callback。 (见下文。)
- 我已经通过 Info.plist 创建了一组 URL 方案。标识符是用我的反向域+唯一名称制作的。 URL Schemes 项是 myapp。 (见下文。)
最后,我将以下代码行添加到
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 }
如果我登录,我会得到如下提示。
当我点击打开时,我被重定向到我的 View Controller 。
关于ios - OAuth2 : Returning to App After Logging in,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55628446/