我跑了这个,当我尝试发送数据时没有任何反应。所以我调试了这个,它无法读取网址中的任何内容。它说"无法读取数据"。我检查了网址是否正确,我检查了这个服务器它的好和我的PHP代码。我只有在升级到swift 2或Xcode7时才遇到这个问题。谢谢你的帮助!
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()
答案 0 :(得分:2)
只有在升级到swift 2或Xcode7时才会遇到此问题。
Xcode 7包含iOS 9的iOS模拟器.iOS 9具有新功能 - App Transport Security(ATS),可防止非安全连接(http)。更多信息:
答案 1 :(得分:0)
我向您展示了使用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)
第二个例子
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)