URL 在包含 JSON 对象的 UIWebView 中显示为 [Object%20Object]
URL in UIWebView containing JSON object shown as [Object%20Object]
我正在尝试访问 UIWebView 内 URL 中的 JSON 对象。这是我的代码 -
func webView(myWebView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
let requestUrl:NSURL = request.URL!
let url:String = requestUrl.absoluteString
if url.rangeOfString("token") != nil {
print("exists")
let index = url.rangeOfString("token=", options: .BackwardsSearch)?.endIndex
let tokenValue = url.substringFromIndex(index!)
if let data = tokenValue.dataUsingEncoding(NSUTF8StringEncoding) {
do {
let json: AnyObject? = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary
print(json)
} catch {
print("Something went wrong")
}
}
self.tokenField.text = "\(tokenValue)"
}
'request URL' 来自以下 JS -
var tokenObj = {"accessToken":"abc123"};
window.location.href = "didtap://LoginButton?token=" + tokenObj;
这里的问题是当我尝试使用 Swift 访问 JSON 对象时,我看到 URL 以 didtap://LoginButton?token=[object%20Object]
的形式出现
这也是我的调试器的截图。
我正在按原样查找 JSON 对象,因此我可以在我的应用程序中需要时使用该令牌。
您可以使用substring.stringByRemovingPercentEncoding来解决您的问题
我正在尝试访问 UIWebView 内 URL 中的 JSON 对象。这是我的代码 -
func webView(myWebView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
let requestUrl:NSURL = request.URL!
let url:String = requestUrl.absoluteString
if url.rangeOfString("token") != nil {
print("exists")
let index = url.rangeOfString("token=", options: .BackwardsSearch)?.endIndex
let tokenValue = url.substringFromIndex(index!)
if let data = tokenValue.dataUsingEncoding(NSUTF8StringEncoding) {
do {
let json: AnyObject? = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary
print(json)
} catch {
print("Something went wrong")
}
}
self.tokenField.text = "\(tokenValue)"
}
'request URL' 来自以下 JS -
var tokenObj = {"accessToken":"abc123"};
window.location.href = "didtap://LoginButton?token=" + tokenObj;
这里的问题是当我尝试使用 Swift 访问 JSON 对象时,我看到 URL 以 didtap://LoginButton?token=[object%20Object]
这也是我的调试器的截图。
我正在按原样查找 JSON 对象,因此我可以在我的应用程序中需要时使用该令牌。
您可以使用substring.stringByRemovingPercentEncoding来解决您的问题