打开 url 尝试从 oauth url 获取令牌时未在 AppDelegate 中调用的函数

open url function not called in AppDelegate when trying to grab token from oauth url

我正在尝试在 iOS - Swift 3 上实施 OAuth 流程,以便查询 REST API (Strava).

我在 VC 处理身份验证流程时这样做:

@IBAction func tappedStartAuth(_ sender: Any) {

    let authUrlStr = "http://www.strava.com/oauth/authorize?client_id=12345&response_type=code&redirect_uri=http://localhost/exchange_token&approval_prompt=force&scope=view_private,write"

    // but instead 12345 I have my real cientID of course

    UIApplication.shared.openURL(URL(string:authUrlStr)!)

    // Did not work with SFVC either:
    //safariViewController = SFSafariViewController(url: URL(string: authUrlStr)!)
    //safariViewController?.delegate = self
    //present(safariViewController!, animated: true, completion: nil)

}

在我的 AppDelegate 中:

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {

    print("opened url, [code] checking should follow, but this won't get called")

    // would do some stuff here...

    return true
}

然后我在 plist 中添加了我的 url 方案:

<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLName</key>
        <string>org.my.bundle.id</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>localhost</string>
        </array>
    </dict>
</array>

但是,我无法调用 AppDelegate 中的 application(_:open:options:) 函数。

(浏览器弹出,我可以登录 Strava,我看到返回了有效的 URL,包括 "code=..." 块中的访问令牌,我想摘录,但我无法继续该部分。)

我试过:

有什么我可能遗漏的想法吗?

干杯

所以它实际上是我没有注意到的东西的混合物...

  1. 我尝试使用的URL错误:不应该 http://yourApp:// 因为您希望您的应用程序处理 打回来。在一些论坛上我读到 Strava 只允许 http 重定向 uris,这让我尝试那样做,但这实际上是错误的,因为 the documentation 状态:

URL to which the user will be redirected with the authorization code, must be to the callback domain associated with the application, or its sub-domain, localhost and 127.0.0.1 are white-listed.

我们进入下一件事,即:

  1. 您应该在 Settings/My Api 应用程序的 Strava 管理页面上检查您对应用程序的命名。 按照 yourApp 示例,它应该是这样的:

(我的错误是,我没有提供 valid/matching 回调域。)

  1. 最后,你的 plist 文件也应该进行相应的设置:
        <key>CFBundleURLTypes</key>
        <array>
            <dict>
                <key>CFBundleURLName</key>
                <string>com.yourdomain.yourApp</string>
                <key>CFBundleURLSchemes</key>
                <array>
                    <string>yourApp</string>
                </array>
            </dict>
        </array>

它就像魅力一样:它是 iOS 9 还是 11 实际上并不重要,或者你使用 SFSafariViewController VS 你离开应用程序 UIApplication.shared.openURL() 等...

祝你好运;)