Dan M
Dan M

Reputation: 21

Swift, unable to read data in url

I ran this and nothing happens when I try to send the data. So I debugged this and the it can't read anything from the url. It says "unable to read data". I checked the url its correct, I checked this sever its good and my php code. I experience this problem only when I upgraded to swift 2 or Xcode7. Thanks for the help!

let myUrl = NSURL(string: "http://localhost/SwiftAppAndMySQL/scripts/registerUser.php");
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";

let postString = "userEmail=\(userEmail!)&userFirstName=\(userFirstName!)&userLastName=\(userLastName!)&userPassword=\(userPassword!)";

request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);

NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in

    dispatch_async(dispatch_get_main_queue())
        {

            //spinningActivity.hide(true)

            if error != nil {
                self.displayAlertMessage(error!.localizedDescription)
                return
            }

            do {
                let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary

                if let parseJSON = json {

                    let userId = parseJSON["userId"] as? String

                    if( userId != nil)
                    {
                        let myAlert = UIAlertController(title: "Alert", message: "Registration successful", preferredStyle: UIAlertControllerStyle.Alert);

                        let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default){(action) in

                            self.dismissViewControllerAnimated(true, completion: nil)
                        }

                        myAlert.addAction(okAction);
                        self.presentViewController(myAlert, animated: true, completion: nil)
                    } else {
                        let errorMessage = parseJSON["message"] as? String
                        if(errorMessage != nil)
                        {
                            self.displayAlertMessage(errorMessage!)
                        }

                    }

                }
            } catch{
                print(error)
            }    

        }

    }).resume()

Upvotes: 1

Views: 4446

Answers (2)

ifau
ifau

Reputation: 2120

I experience this problem only when I upgraded to swift 2 or Xcode7.

Xcode 7 contains iOS Simulator with iOS 9. iOS 9 has a new feature – App Transport Security (ATS), which prevents non-secured connections (http). More information:

Upvotes: 2

Alexander Khitev
Alexander Khitev

Reputation: 6861

I show you my example of work with JSON

   let mainString = "http://api.mymemory.translated.net/get?q=\(sendWord)&langpair=\(langpair)".stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLFragmentAllowedCharacterSet())!
    Alamofire.request(.POST, mainString).responseJSON { (response) -> Void in

        let mainDictionary = response.result.value as! [String : AnyObject]
        print(mainDictionary)
        let arrayDictionary = mainDictionary["matches"] as! [AnyObject]
        let matchesDictionary = arrayDictionary[0] as! [String : AnyObject]
        let segment = matchesDictionary["segment"] as! String
        print(segment)
        let translation = matchesDictionary["translation"] as! String
        print(translation)

The second example

  let url = NSURL(string: "http://api.mymemory.translated.net/get?q=Hello%20World!&langpair=en%7Cit")!
  let dataData = NSData(contentsOfURL: url)!
  let main = try! NSJSONSerialization.JSONObjectWithData(dataData, options: NSJSONReadingOptions.AllowFragments)
  print(main)

Upvotes: 0

Related Questions