Reputation: 31
I am using NSURL to get the HTML of a website which works great in the Playground, but crashes the simulator when I use it in an app. Playground Code:
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()
App Code:
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()
}
}
Error upon crash:
2015-10-27 20:14:54.105 testProject[51314:431730] 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)
Thanks,
Nick
Upvotes: 0
Views: 261
Reputation: 6272
I have used the code below:
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()
}
}
And in my console the following is printed:
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)
As you can see data
is nil. It might be related to the fact that http is blocked due to App Transport Security.
Upvotes: 0