3

我正在一个项目中实现 OAuthSwift 库以连接到同时使用 OAuth1 和 OAuth2 的几个不同的社交网站。

我已将应用程序设置为加载将我带到我的社交网站的 Web 视图,但我无法让应用程序重定向回来。一旦我加载了我的凭据,它就会要求我授予对应用程序的授权,但是一旦我这样做了,它就会加载我的社交网站主页。

我可以导航回该应用程序,但它没有注册它已获得访问我的帐户的权限。

这是我第一次使用 OAuth,我发现回调 URL 令人困惑。

我会很感激一些帮助解释如何让 web 视图重定向回我的应用程序以及如何设置应用程序的 URL。

类视图控制器:UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func postToTumblr(sender: AnyObject) {
    let oauthSwift = OAuth1Swift(
        consumerKey: "consumerKey",
        consumerSecret: "secretKey",
        requestTokenUrl: "https://www.tumblr.com/oauth/request_token",
        authorizeUrl: "https://www.tumblr.com/oauth/authorize",
        accessTokenUrl: "https://www.tumblr.com/oauth/access_token"
    )

    oauthSwift.authorizeWithCallbackURL(NSURL(string: "com.myCompany.sampleApp")!,
        success: { credential, response in
            // post to Tumblr
            print("OAuth successfully authorized")
        }, failure: {(error:NSError!) -> Void in
            self.presentAlert("Error", message: error!.localizedDescription)
    })
}


func presentAlert(title: String, message: String) {
    let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
    alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
    self.presentViewController(alert, animated: true, completion: nil)
}

}

4

1 回答 1

7

在与我公司的一些人交谈并让他们查看图书馆后,我们能够通过以下方式解决问题:

OAuthSwift 库删除了 URL 方案的“com.myCompany”部分。在查找回调 URL 时,它正在查找应用程序的名称,后跟“://oauth-callback”。

所以而不是:

oauthSwift.authorizeWithCallbackURL(NSURL(string: "com.myCompany.sampleApp")!

它正在寻找:

oauthSwift.authorizeWithCallbackURL(NSURL(string: "tumblrsampleapp://oauth-callback")!

我还必须在 info.plist 中将 URL 方案注册为:

<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>tumblrsampleapp</string>
        </array>
    </dict>
</array>

最后,我必须在 App Delegate 中添加以下方法:

func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool {
    OAuth1Swift.handleOpenURL(url)
    return true
}

这已经解决了问题,应用程序现在可以正确验证并返回到我的应用程序。

我希望这对尝试使用 OAuthSwift 库实现 OAuth1 的其他人有用。

于 2015-11-19T19:44:49.880 回答