当尝试获取当前 URL 时,带有 UIWebView 的 Swift 应用程序因 exc_bad_access 崩溃。它也仅在某些情况下崩溃(通常取决于用户在该 UIWebView 中执行的操作)。尝试加载代码中提供的网址,然后点击取消。如果我不实现 UIWebViewDelegate 协议(protocol)中的方法,它永远不会崩溃。
class AuthViewController: UIViewController, UIWebViewDelegate {
@IBOutlet var authWebView: UIWebView
init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
// Custom initialisation
}
override func viewDidLoad() {
super.viewDidLoad()
self.authWebView.delegate = self
var url = NSURL(string:"http://oauth.vk.com/authorize?client_id=4423823&scope=audio&display=mobile&v=5.21")
var urlRequest = NSMutableURLRequest(URL: url)
self.authWebView.loadRequest(urlRequest)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func webViewDidFinishLoad(webView:UIWebView) {
NSLog( webView.request!.URL!.absoluteString )
}
}
我还尝试实现此方法来在获取 URL 之前检查请求对象是否存在,但没有帮助。
func webView(webView: UIWebView!,
shouldStartLoadWithRequest request: NSURLRequest!,
navigationType navigationType: UIWebViewNavigationType) -> Bool {
if !self.authWebView.request {
return false
} else {
return true
}
}
最佳答案
我发现了错误:
某些URL包含特殊字符,例如%@或#,用于NSLog中的格式化。如果在字符串中使用这些字符中的任何一个,则 NSLog 的第一个参数将比格式化所需的参数更多。
EG
NSLog("http://someurl.com/") // this is fine (no special chars used)
NSLog("http://someurl.com/#somehash?x=%@") // this is not fine (%@ is used in URL, NSLog thinks that I'm formatting the string
var someURLString = "http://someurl.com/#somehash?x=%@"
NSLog("%@", someURLString) // this is fine and the way it has to be done
感谢所有看我问题的人!
关于ios - Swift 中的 UIWebView : exc_bad_access,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24502611/