0

Ever since the change in Swift syntax for URL requests after the update to 9.1, I've been getting an error making requests to my API. For example, this POST request which simply tries to login. I can log in just fine directly in the API (Strongloop Loopback) Explorer interface but not from Swift. I get this error:

The operation couldn’t be completed. No such file or directory

Here's what my code looks like:

func performLoginRequestWithURL(url: NSURL, email: String, password: String) {
            let bodyData = "email=\(email)&password=\(password)"
            let request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
            let session = NSURLSession.sharedSession()
            request.HTTPMethod = "POST"
            request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding)

            let task = session.dataTaskWithRequest(request, completionHandler: {
                data, response, error -> Void in
                if let error = error {
                    let errString = error.localizedDescription
                    NSNotificationCenter.defaultCenter().postNotificationName(self.lh, object: nil, userInfo: ["Result": errString])
                    print(error.localizedDescription)

                } else if data != nil {
                    let json = NSString(data: data!, encoding: NSUTF8StringEncoding) as! String

                    if let dictionary = JSON().parseJSON(json) as [String: AnyObject]? {
                        let accesstoken = dictionary["id"] as! String
                        let id = dictionary["userId"] as! Int

                        // MARK: - Store UID & AccessToken
                        NSUserDefaults.standardUserDefaults().setBool(true, forKey: "userLoggedIn")
                        NSUserDefaults.standardUserDefaults().setInteger(id, forKey: "userId")
                        NSUserDefaults.standardUserDefaults().setObject(accesstoken, forKey: "accessToken")
                        NSUserDefaults.standardUserDefaults().synchronize()
                        NSNotificationCenter.defaultCenter().postNotificationName(self.lh, object: nil, userInfo: ["Result": "Success"])
                    }
                }

            })
            task.resume()
        }

Here's what it used to look like back when it worked, but they depreciated the sendAsynchronousRequest method:

func performLoginRequestWithURL(url: NSURL, email: String, password: String) {
        let bodyData = "email=\(email)&password=\(password)"
        var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
        request.HTTPMethod = "POST"
        request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding)
        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()){
            response, data, error in

            if let error = error {
                let errString = error.localizedDescription
                NSNotificationCenter.defaultCenter().postNotificationName(self.lh, object: nil, userInfo: ["Result": errString])

            } else if data != nil {
                let json = NSString(data: data, encoding: NSUTF8StringEncoding) as! String

                if let dictionary = JSON().parseJSON(json) as [String: AnyObject]? {
                    let accesstoken = dictionary["id"] as! String
                    let id = dictionary["userId"] as! Int
                    var results = [String: AnyObject]()
                    results = ["at": accesstoken, "id": id]

                    // MARK: - Store UID & AccessToken
                    NSUserDefaults.standardUserDefaults().setBool(true, forKey: "userLoggedIn")
                    NSUserDefaults.standardUserDefaults().setInteger(id, forKey: "userId")
                    NSUserDefaults.standardUserDefaults().setObject(accesstoken, forKey: "accessToken")
                    NSUserDefaults.standardUserDefaults().synchronize()
                    NSNotificationCenter.defaultCenter().postNotificationName(self.lh, object: nil, userInfo: ["Result": "Success"])
                }
            }

        }
    }
Nathan McKaskle
  • 2,926
  • 12
  • 55
  • 93

1 Answers1

0

Turns out this problem has nothing to do with the new syntax and everything to do with iOS 9 and the way requests are made to localhost from the Simulator. I was able to make requests to my local IP 10.x.x.2 and that no longer works, I have to use 127.0.0.1 instead. This will make it difficult when connecting via the phone. I'll have to change the IP every time now...

Nathan McKaskle
  • 2,926
  • 12
  • 55
  • 93