1

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()
Lorenzo
  • 3,293
  • 4
  • 29
  • 56
Dan M
  • 21
  • 1
  • 5

2 Answers2

2

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:

Community
  • 1
  • 1
ifau
  • 2,100
  • 1
  • 21
  • 29
  • Yeah I got rid of the App transport security block, I don't know what else it would be. – Dan M Oct 14 '15 at 23:54
0

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)
Alexander Khitev
  • 6,417
  • 13
  • 59
  • 115