0

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

1 Answers1

0

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.

Andriy Gordiychuk
  • 6,163
  • 1
  • 24
  • 59
  • The label is connected properly. I am able to alter it's content by replacing the NSURL code with testLabel.text = "Text changed". Do you have any other ideas as to why this does not work? Thanks – Nick Pitoniak Oct 28 '15 at 01:39
  • @NickPitoniak in that case "data" must be nil. Check this with print() – Andriy Gordiychuk Oct 28 '15 at 01:41
  • print(data) returns a large pool of 8 character alpha numeric strings, so I do not think it is nil. If you have any other ideas to fix this problem please let me know. Thank you for the help – Nick Pitoniak Oct 28 '15 at 01:51
  • @NickPitoniak check my updated answer - I have ran your code and print() returns nil for data. Most likely App Transport Security blocks opening of http which is why it is nil – Andriy Gordiychuk Oct 28 '15 at 01:57
  • Thank you for the help. I attempted to add code to the info.plist file to bypass this problem, however I was not able to type any code as it is all options. Here is a screenshot of my info.plist: http://i.imgur.com/mZYOGLZ.png . As you can see, there is no place (that I see) to add this code: NSAppTransportSecurity NSAllowsArbitraryLoads – Nick Pitoniak Oct 28 '15 at 13:18
  • @NickPitoniak select last row in your Info.plist and hit Enter – Andriy Gordiychuk Oct 28 '15 at 13:45
  • Thank you for the help. I made the changes to the Info.plist (http://i.imgur.com/wwix43u.jpg), however am still getting a crash. Here is my error report if you get a change to look at it: 2015-10-28 12:42:48.772 testProject[58771:519590] 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) – Nick Pitoniak Oct 28 '15 at 16:47