查询字符串中具有自定义方案的Swift URL失败-Redirect_URI



我正试图使用URLSession调用一个URL,以注销iOS应用程序中swift中的oauth2会话。

URL如下所示:请注意,有些参数是URL编码的

https://xxxxxx.auth.us-east-1.amazoncognito.com/logout?client_id=49jaf4a848hakh&logout_uri=myapp%3A%2F%2F&redirect_uri=myapp%3A%2F%2F&response_type=token

我在一个数据任务中使用这个URL时遇到一个运行时错误,上面写着:

Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" 
UserInfo={NSUnderlyingError=0x60000202ccf0 
{Error Domain=kCFErrorDomainCFNetwork Code=-1002 "(null)"}, 
NSErrorFailingURLStringKey=myapp://, NSErrorFailingURLKey=myapp://,
NSLocalizedDescription=unsupported URL}

我已经有了"myapp";在我的info.plist.

<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLName</key>
<string>com.xxx.yyy</string>
<key>CFBundleURLSchemes</key>
<array>
<string>myapp</string>
</array>
</dict>
</array>

下面是执行这个简单URLSession数据任务的代码

let s = URLSession.shared
let u = URL(string: "https://xxx.yyy.auth.us-east-1.amazoncognito.com/logout?client_id=49jaf4a848hakh&logout_uri=myapp%3A%2F%2F&redirect_uri=myapp%3A%2F%2F&response_type=token")!        

let t = s.dataTask(with: u) { (d: Data?, r: URLResponse?, e:Error?) in
if e != nil {
print("error: (e)")
}
let decoded = String(data: d!, encoding: .utf8)
print("Data: (decoded)")
print("url Response: (r)")
print("Breakpoint")
}.resume()

我已经尝试了下面的两个URL字符串,但仍然得到相同的错误

let u = URL(string: "https://xxx.yyy.auth.us-east-1.amazoncognito.com/logout?client_id=49jaf4a848hakh&logout_uri=myapp%3A%2F%2F&redirect_uri=myapp%3A%2F%2F&response_type=token")!        
let u = URL(string: "https://xxx.yyy.auth.us-east-1.amazoncognito.com/logout?client_id=49jaf4a848hakh&logout_uri=myapp://&redirect_uri=myapp://&response_type=token")!        

为什么swift不喜欢"myapp://";或者(myapp%3A%2F%2F(是查询字符串参数?

更新经过更多的实验,真正奇怪的是,如果我只有一个以scheme为值的查询字符串参数,那么就没有问题。它不支持超过1个以scheme为值的查询字符串参数,这似乎是一个错误。

这似乎是一个编码问题。你试过这样编码吗:

let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)

最新更新