Error -1002 || Http-Request

Hallo,


I am trying to send a Http-Request to an ESP8266. The connection isn't secure (Cleartext/Http), but that isn't a problem for my Application.

let urlComp = NSURLComponents(string: urlString)!
        var urlRequest = URLRequest(url: urlComp.url!)
        urlRequest.httpMethod = "GET"
        let config = URLSessionConfiguration.default
        let session = URLSession(configuration: config)
        let task = session.dataTask(with: urlRequest, completionHandler: { (data, response, error) in
        })
        task.resume()

This is my code for doing this. But I get an error. I found out that I have to allow non-https connections, so I addet following lines to myInfo.plist:

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

Please tell me how I can solve this "ERROR 1002" or if ther is a other way for this http-request and what the code for it is.


Greetings from Germany

Steffen Rohwer (absolutely Noob)

Error -1002 is

NSURLErrorUnsupportedURL
. This indicates that the URL scheme is completely unknown to
URLSession
, so this isn’t an HTTP versus HTTPS thing but something else. You should double check that your URL is being built correctly. One way to do this is to log the URL just before you use it to construct your request:
let url = urlComp.url!
NSLog("%@", url.absoluteString)
let urlRequest = URLRequest(url: url)

Just as aside:

  • There is a Swift equivalent of

    NSURLComponents
    , namely
    URLComponents
    , and you should favour that over the NS type in general.
  • Line 3 of your code is not necessary because

    URLRequest
    defaults to the
    GET
    method.
  • That means that line 2 can be a

    let
    not a
    var
    , because you never modify the request.
  • It’s bad form to create a new session for every request you make. For simple testing you should use the shared session. That is, remove lines 4 and 5 and change line 6 to use

    URLSession.shared
    .

    Session management in a real app is more complex, but in many cases you can get away with creating a single session and holding on to it for the lifetime of your app.

  • For testing it’s fine to disable ATS completely via

    NSAllowsArbitraryLoads
    . In fact it’s what I recommend you do during your initial bring up because ATS is just one more complexity that you don’t need to deal with right now. However, in the long term I suspect you’ll be able to benefit from
    NSAllowsLocalNetworking
    .

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"
Error -1002 || Http-Request
 
 
Q