我正在尝试使用NSURL函数获取URL的HTML。代码运行良好,从操场上执行时正确返回HTML,但是当我将它实现到故事板中的按钮时,应用程序崩溃了。我在Info.plist文件中更改了App Transport Security,但是我仍然遇到崩溃。这是我的Info.plist:http://imgur.com/a/BB3KF。错误消息还说有一个零值,但是我测试了函数中的变量,一切似乎都是!= nil。
游乐场代码:
let myUrl = NSURL(string: "http://www.google.com")
let request = NSMutableURLRequest(URL: myUrl!)
request.HTTPMethod = "POST"
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
self.testLabel.text = "\(responseString)"
if error != nil {
print("Error: \(error)")
}
}
task.resume()
XCode代码:
import UIKit
import Foundation
class ViewController: UIViewController {
@IBOutlet weak var testLabel: UILabel!
@IBAction func testButton(sender: UIButton) {
let myUrl = NSURL(string: "http://www.google.com")
let request = NSMutableURLRequest(URL: myUrl!)
request.HTTPMethod = "POST"
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
self.testLabel.text = "\(responseString)"
if error != nil {
print("Error: \(error)")
}
}
task.resume()
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
错误讯息:
2015-10-29 10:20:36.127 testProject [1263:49414] App Transport Security阻止了明文HTTP(http://)资源加载,因为它不安全。可以通过应用程序的Info.plist文件配置临时例外。 致命错误:在展开Optional值时意外发现nil (LLDB)
答案 0 :(得分:0)
发生错误是因为iOS9与服务器的连接必须是安全的(https)以允许使用http将以下内容添加到info.plist中
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
答案 1 :(得分:0)
您需要在NSAppTransportSecurity
中设置info.plist
值,如下所示:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>localhost</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSTemporaryExceptionMinimumTLSVersion</key>
<string>TLSv1.1</string>
</dict>
</dict>
</dict>
将localhost
更改为您的实际服务器
App Transport Security has blocked a cleartext HTTP resource