gpt4 book ai didi

ios - 代码将在 Playground 上运行,但在应用程序模拟器中执行时失败

转载 作者:行者123 更新时间:2023-11-30 13:57:37 24 4
gpt4 key购买 nike

我正在尝试使用 NSURL 函数获取 URL 的 HTML。代码运行良好,并且在从 Playground 执行时正确返回 HTML,但是当我将其实现为 Storyboard中的按钮时,应用程序崩溃了。我更改了 Info.plist 文件中的应用程序传输安全性,但仍然遇到崩溃。这是我的 Info.plist:http://imgur.com/a/BB3KF 。错误消息还说有一个 nil 值,但是我测试了函数中的变量,一切似乎都是 != nil。

Playground 代码:

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)

最佳答案

出现此错误是因为 iOS9 与服务器的连接必须是安全的 (https ) 才能允许使用 http 将以下内容添加到 info.plist

<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>

关于ios - 代码将在 Playground 上运行,但在应用程序模拟器中执行时失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33417228/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com