Swift 2.0 url发布请求

我一直在弄清楚什么是错我的代码,但我不断收到这个错误在迅速2.0

Errors thrown from here are not handled because the enclosing catch is not exhaustive 

XCode自动转换为我做了很多工作(也给了很多错误),但是这仍然不起作用。 我不明白什么是工作,所以也许你们可以对案件进行点亮。 提前致谢

这是我的代码

 if config.isConnected() { let post:NSString = "postID=\(postID)" //NSLog("PostData: %@",post); let url:NSURL = NSURL(string:"https://www.example.com/json/index.php")! let postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)! let postLength:NSString = String( postData.length ) let request:NSMutableURLRequest = NSMutableURLRequest(URL: url) request.HTTPMethod = "POST" request.HTTPBody = postData request.setValue(postLength as String, forHTTPHeaderField: "Content-Length") request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.setValue("application/json", forHTTPHeaderField: "Accept") var reponseError: NSError? var response: NSURLResponse? var urlData: NSData? do { urlData = try NSURLConnection.sendSynchronousRequest(request, returningResponse:&response) // gives error } catch let error as NSError { print(reponseError) reponseError = error urlData = nil } if ( urlData != nil ) { Webiew.loadRequest(request) } else { let alert: UIAlertView = UIAlertView(title: "OOPS", message: "There is nothing here!", delegate: nil, cancelButtonTitle: "OK"); alert.show() } } else { // not connected } 

试试这个代码*解释里面*

  let parameters = ["userId":"1", "userName":"2"] as Dictionary<String, String> //create the url with NSURL let url = NSURL(string: "URL") //change the url //create the session object let session = NSURLSession.sharedSession() let request = NSMutableURLRequest(URL: url!) request.HTTPMethod = "POST" //set http method as POST //request.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameters, options: nil, error: &err) // pass dictionary to nsdata object and set it as request body request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.setValue("application/json", forHTTPHeaderField: "Accept") request.setBodyContent(parameters) //create dataTask using the session object to send data to the server let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in // println("Response: \(response)") let strData = NSString(data: data!, encoding: NSUTF8StringEncoding) print("Body: \(strData)") let json = try!NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as! NSDictionary print("account data") completion(result: json as NSDictionary?) // Did the JSONObjectWithData constructor return an error? If so, log the error to the console if(error != nil) { print(error!.localizedDescription) let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding) print("Error could not parse JSON: '\(jsonStr)'") } else { // The JSONObjectWithData constructor didn't return an error. But, we should still // check and make sure that json has a value using optional binding. if let parseJSON = json as NSDictionary! { // Okay, the parsedJSON is here, let's get the value for 'success' out of it _ = parseJSON["success"] as? Int //println("Succes: \(success)") } else { // Woa, okay the json object was nil, something went worng. Maybe the server isn't running? _ = NSString(data: data!, encoding: NSUTF8StringEncoding) // println("Error could not parse JSON: \(jsonStr)") } } }) task.resume() 

添加这个扩展名:

 extension NSMutableURLRequest { func setBodyContent(contentMap: Dictionary<String, String>) { var firstOneAdded = false var contentBodyAsString = String() let contentKeys:Array<String> = Array(contentMap.keys) for contentKey in contentKeys { if(!firstOneAdded) { contentBodyAsString = contentBodyAsString + contentKey + "=" + contentMap[contentKey]! firstOneAdded = true } else { contentBodyAsString = contentBodyAsString + "&" + contentKey + "=" + contentMap[contentKey]! } } contentBodyAsString = contentBodyAsString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! self.HTTPBody = contentBodyAsString.dataUsingEncoding(NSUTF8StringEncoding) } } 

这是我的解决scheme,我不需要使用你所做的扩展。 这样的请求是同步的,它直接给我的回应,我parsing它来获取值。 它采取了一些search和试验和错误,但它解决了:)我粘贴下面的代码是为了别的东西,但原则是一样的

  let request:NSMutableURLRequest = NSMutableURLRequest(URL: NSURL(string: config.versionURL() as String)!) request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.setValue("application/json", forHTTPHeaderField: "Accept") var response: NSURLResponse? if config.isConnected() { var urlData: NSData? do { urlData = try NSURLConnection.sendSynchronousRequest(request, returningResponse:&response) } catch _ { urlData = nil } if ( urlData != nil ) { let myJSON = try! NSJSONSerialization.JSONObjectWithData(urlData!, options: .MutableLeaves) as? NSDictionary if let parseJSON = myJSON { onlineVersion = parseJSON["version"]?.integerValue if onlineVersion > prefs.integerForKey("offlineVersion") { showActivityIndicator(self.view) self.structureSetup() } else if onlineVersion == prefs.integerForKey("offlineVersion") { if (fileExistance) { let jsonStringData = NSDictionary(contentsOfFile: jsonFilePath) fullStructure = JSON(jsonStringData!) numCats = fullStructure["posts"].count self.homeTable.reloadData() hideActivityIndicator(self.view) } else { if config.isConnected() { self.structureSetup() } else { // alert, nothing here } } } } } } else { if (fileExistance) { let jsonStringData = NSDictionary(contentsOfFile: jsonFilePath) fullStructure = JSON(jsonStringData!) numCats = fullStructure["posts"].count self.homeTable.reloadData() } else { if config.isConnected() { self.structureSetup() } else { // alert, nothing here } } }