我正在使用 NSURL 获取网站的 HTML,该网站在 Playground 中运行良好,但当我在应用程序中使用它时,模拟器会崩溃。 Playground 代码:
import Foundation
import XCPlayground
// Let asynchronous code run
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
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)
if error != nil {
print("Error: \(error)")
}
print("Response: \(response)")
print("Response String: \(responseString)")
}
task.resume()
应用程序代码:
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-27 20:14:54.105 testProject[51314:431730] 应用程序传输安全已阻止明文 HTTP (http://) 资源加载,因为它不安全。可以通过应用程序的 Info.plist 文件配置临时异常(exception)。
fatal error :在解包可选值时意外发现 nil
(LLDB)
谢谢,
尼克
最佳答案
我使用了以下代码:
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
print("hey \(data)")
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-28 02:54:49.284 trial[58972:2551861] 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.
hey nil
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)
如您所见,data
为零。这可能与由于应用程序传输安全性而阻止 http 的事实有关。
关于php - Swift:NSURL 正确地从 Playground 中的 URL 返回 HTML,但在应用程序中使用时会使模拟器崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33380776/