因此在发送OAuth2令牌请求时(对我控制的服务器)有一个感兴趣的问题。服务器正常运行并返回302重定向到'com.myapp:// oauth / callback #diffal_type = Bearer& access_token = WPtSq5oFW0moitYabRmymbVxgZTGnc& expires_in = 3600& scope = register'但是我的应用程序抛出NSURLErrorDomain代码= -1002“不支持URL”。
是的,我在info.plist中注册了URL方案,其中包含:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>com.myapp</string>
</array>
<key>CFBundleURLName</key>
<string>com.mycompany.myapp</string>
</dict>
</array>
有没有人知道为什么这不能正确重定向并被发送到我的AppDelegate.swift?这让我有点生气!我很乐意将重定向网址放入Safari,它可以打开我的应用程序。我在控制台中看到的完整错误是:
Error: Optional(Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" UserInfo={NSUnderlyingError=0x1357e1c80 {Error Domain=kCFErrorDomainCFNetwork Code=-1002 "(null)"}, NSErrorFailingURLStringKey=com.myapp://oauth/callback#token_type=Bearer&access_token=WPtSq5oFW0moitYabRmymbVxgZTGnc&expires_in=3600&scope=anonymous_view, NSErrorFailingURLKey=com.myapp://oauth/callback#token_type=Bearer&access_token=WPtSq5oFW0moitYabRmymbVxgZTGnc&expires_in=3600&scope=anonymous_view, NSLocalizedDescription=unsupported URL})
我应该补充一下,我正在使用NSURLSession发送请求,如下所示:
let defaultSession = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
let url = NSURL(string: authoriseUrl)
let dataTask = defaultSession.dataTaskWithURL(url!) {data, response , error in
print("Data: \(data)")
print("Response: \(response)")
print("Error: \(error)")
}
dataTask.resume()
答案 0 :(得分:2)
管理以使其工作。事实证明,NSURLSession不像Safari那样使用info.plist中的注册URL方案。所以你需要编写一个NSURLProtocol子类来处理你的URL方案:
class MyUrlProtocol: NSURLProtocol {
override class func canInitWithRequest(request: NSURLRequest) -> Bool {
if request.URL?.scheme == "myapp" {
return true
}
return false
}
override class func canonicalRequestForRequest(request: NSURLRequest) -> NSURLRequest {
return request
}
override class func requestIsCacheEquivalent(aRequest: NSURLRequest,
toRequest bRequest: NSURLRequest) -> Bool {
return super.requestIsCacheEquivalent(aRequest, toRequest:bRequest)
}
override func startLoading() {
// Do your work here
}
override func stopLoading() {
}
然后在您的NSURLSession中,您需要在提出请求之前将其添加到您的配置中:
var protocolClasses = [AnyClass]()
protocolClasses.append(MyUrlProtocol)
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.protocolClasses = protocolClasses
let defaultSession = NSURLSession(configuration: configuration)
let url = NSURL(string: authoriseUrl)
let dataTask = defaultSession.dataTaskWithURL(url!) {data, response , error in
print("Data: \(data)")
print("Response: \(response)")
print("Error: \(error)")
}
dataTask.resume()