本文介绍了Swift 2.0网址发布请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在尝试找出我的代码有什么问题,但在Swift 2.0中我一直收到此错误
I've been trying to figure out what is wrong whit my code but i keep getting this error in swift 2.0
Errors thrown from here are not handled because the enclosing catch is not exhaustiveXCode的自动转换为我做了很多工作(也给出了很多错误),但这仍然行不通.我不知道什么在起作用,所以也许你们可以对这个案例有所了解.预先感谢
The automated conversion from XCode did a lot of work for me (also gave a LOT of errors) but this is still not working. I don't understand what is working so maybe you guys can throw some light on the case. Thanks in advance
这是我的代码
if config.isConnected() { let post:NSString = "postID=\(postID)" //NSLog("PostData: %@",post); let url:NSURL = NSURL(string:"www.example/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 }推荐答案
尝试使用此代码*内部说明*
Try this code *explained inside *
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) } }更多推荐
Swift 2.0网址发布请求
发布评论