0

I am attempting to get the HTML of a URL with the NSURL function. The code runs well and the HTML is properly returned when executed from the playground, however when I implement it into a button from the storyboard the app crashes. I changed the App Transport Security in the Info.plist file, however I am still encountering a crash. Here is my Info.plist: https://i.stack.imgur.com/sMSv0.jpg. The error message also says that there is a nil value, however I have tested the variables in the function and everything seems to be != nil.

Playground code:

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 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 message:

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)

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
  • Change the boolean of Allow Arbitrary Loads to `YES`, you may need to clean or clear derived data afterwards. – Eric Murphey Oct 29 '15 at 14:44
  • @EricKenny Thank you very much for your help. I added it, but it still does not work. http://imgur.com/a/n8aJ8 Error message I am receiving: 2015-10-29 11:14:26.368 testProject[1403:58840] 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 29 '15 at 15:18
  • @EricKenny Also receiving this: http://imgur.com/Rg0TMsZ Thanks – Nick Pitoniak Oct 29 '15 at 15:20

2 Answers2

0

The error occurs because iOS9 connections to the servers must be secure (https ) to allow the use of http add the following into info.plist

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>
Manuel
  • 1,675
  • 12
  • 18
  • Thank you very much for your help. I added it, but it still does not work. http://imgur.com/a/n8aJ8 Error message I am receiving: 2015-10-29 11:14:26.368 testProject[1403:58840] 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 29 '15 at 15:18
  • The info.plist you musth change is in testProject, not in testProjectTest – Manuel Oct 29 '15 at 15:23
  • @NickPitoniak check my answer please – William Kinaan Oct 29 '15 at 15:32
  • Thank you for the help, now I've got it working! However, it takes forever to grab the HTML from the website (40 seconds). Is there any way to cut the load time, or is that just how long it takes to lead and retrieve the HTML? Thanks a lot. – Nick Pitoniak Oct 29 '15 at 15:33
  • @WilliamKinaan Thank you for your help. I see that you recommend changing the server to localhost. The idea I have is for users to access the MySQL through a PHP script to get data. How will I get the existing data if everyone's app is pointing to their own localhost, as opposed to a website of my choosing where I can compile data? If that doesn't make sense I will explain what I mean in more depth. Thank you very much for the help on this issue. – Nick Pitoniak Oct 29 '15 at 15:39
  • @NickPitoniak first if my answer helps you, kindly accept it :) secondly, explain please what do you need exactly so i can help you. i will do my best – William Kinaan Oct 29 '15 at 15:44
  • @WilliamKinaan How do I "accept" your answer? My problem at this point (after fixing the NSURL connection error) is that the time it takes to retrieve the contents of the URL is taking a very long time (40 seconds). Is there any way to trim the response time down? Am I doing something unintentionally that is slowing the program down? Thanks for the help. – Nick Pitoniak Oct 29 '15 at 16:27
  • @NickPitoniak you accept an answer like this http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work for your other question, it is an issue from the server, you need for example either to reduce the number of requests that you are doing or to make some caching or or ... so many solutions to this problem, you need to check . if there is something specific, ask a new question and i ll try to help – William Kinaan Oct 29 '15 at 16:30
  • How would I decrease the number of requests I am making? It seems like I am only making one request (to http://www.google.com). Thanks – Nick Pitoniak Oct 29 '15 at 16:40
  • @NickPitoniak there are too many users here that could give you ideas, kindly post a new question, explain your problem exactly – William Kinaan Oct 29 '15 at 16:41
  • @WilliamKinaan Thank you for all of your help. I will accept your answer in a few minutes – Nick Pitoniak Oct 29 '15 at 16:47
0

You need to set the NSAppTransportSecurity value in info.plist as the following:

<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSExceptionDomains</key>
        <dict>
            <key>localhost</key>
            <dict>
                <key>NSIncludesSubdomains</key>
                <true/>
                <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
                <true/>
                <key>NSTemporaryExceptionMinimumTLSVersion</key>
                <string>TLSv1.1</string>
            </dict>
        </dict>
    </dict>

change localhost to your actual server

App Transport Security has blocked a cleartext HTTP resource

Community
  • 1
  • 1
William Kinaan
  • 28,059
  • 20
  • 85
  • 118