在iOS上使用Instagram验证用户:指定redirect_uri

Mat*_*ton 7 ios oauth-2.0 swift instagram-api

我正在开发一个iOS应用程序(使用Swift),允许用户使用OAuth 2.0通过Instagram进行身份验证

在过去,一切都运行正常,因为我能够指定授权URL: https://api.instagram.com/oauth/authorize/?client_id=xxx&redirect_uri=myiosapp://authorize&response_type=code

这里的关键点是redirect_uri myiosapp://authorize

我的问题是我无法再使用Instagram注册自定义网址方案,从而无法(?)通过我的应用程序专门处理重定向.如果我尝试在"有效重定向URI:"字段中添加这样的URI,我会收到以下错误:

You must enter an absolute URI that starts with http:// or https://

通过iOS本机应用程序专门处理Instagram身份验证的推荐方法是什么?

Mat*_*ton 9

搞清楚之后,我想我会为遇到同样问题的人发布我的解决方案.

首先,我只是接受Instagram不再允许"安全" - >"有效重定向URI"字段中的自定义模式.相反,我将输入一个我可以唯一识别的任意但有效的URI.例如:http://www.mywebsite.com/instagram_auth_ios

现在,当尝试使用Instagram进行授权时,我会将其用作重定向URI - 即使该URI上实际上不存在任何网页.例:https://api.instagram.com/oauth/authorize/?client_id=xxx&redirect_uri=http://www.mywebsite.com/instagram_auth_ios&response_type=code

最后,我将使用UIWebViewDelegate's shouldStartLoadWithRequest方法在运行之前拦截重定向请求,而是调用我原来的自定义uri(这样我就不必重写任何东西).以下是我编写该方法的方法:

func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    guard let url = request.URL where url.host == "www.mywebsite.com" && url.path == "/instagram_auth_ios" else { return true }
    guard let authUrl = NSURLComponents(URL: url, resolvingAgainstBaseURL: false) else { return true }

    // Customize the scheme/host/path, etc. as desired for your app
    authUrl.scheme = "myappschema"
    authUrl.host = "instagram"
    authUrl.path = ""
    UIApplication.sharedApplication().openURL(authUrl.URL!)

    return false
}
Run Code Online (Sandbox Code Playgroud)

在shouldStartLoadWithRequest方法中有一个小的警告,返回false,因为它总是会抱怨"Frame Load Interrupted"错误.这似乎不会对任何事情产生负面影响,并且可能(可能)被安全地忽略.