我正在嘗試使用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 has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file. fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)
變化的布爾允許任意負載'YES ',之後您可能需要清理或清除派生數據。 –
@EricKenny非常感謝您的幫助。我添加了它,但它仍然不起作用。 http://imgur.com/a/n8aJ8我收到的錯誤消息:2015-10-29 11:14:26.368 testProject [1403:58840]應用傳輸安全已阻止明文HTTP(http://)資源加載自它是不安全的。臨時例外可以通過您的應用程序的Info.plist文件進行配置。 致命錯誤:意外發現零,同時展開一個可選值 (lldb) –
@EricKenny還收到此:http://imgur.com/Rg0TMsZ謝謝 –