如何用新的Apple Swift语言发布JSON
我(试图)学习Swift的苹果语言。 我在Playground并使用Xcode 6 Beta。 我试图做一个简单的JSON发布到本地的NodeJS服务器。 我已经在Google上search过,主要的教程解释了如何在一个项目中做到这一点,而不是在PLAYGROUND,而不是写愚蠢的想法,如:“谷歌它”或“显而易见”或“看这个链接”testing – 和 – 不官能码
这就是我想要的:
var request = NSURLRequest(URL: NSURL(string: "http://localhost:3000"), cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 5) var response : NSURLResponse? var error : NSError? NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)
我曾尝试过:
var dataString = "some data" var request = NSMutableURLRequest(URL: NSURL(string: "http://posttestserver.com/post.php")) request.HTTPMethod = "POST" let data = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding) var requestBodyData: NSData = data request.HTTPBody = requestBodyData var connection = NSURLConnection(request: request, delegate: nil, startImmediately: false) println("sending request...") connection.start()
谢谢! 🙂
Nate的答案很好,但我不得不改变它的request.setvalue在我的服务器上工作
// create the request & response var request = NSMutableURLRequest(URL: NSURL(string: "http://requestb.in/1ema2pl1"), cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 5) var response: NSURLResponse? var error: NSError? // create some JSON data and configure the request let jsonString = "json=[{\"str\":\"Hello\",\"num\":1},{\"str\":\"Goodbye\",\"num\":99}]" request.HTTPBody = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) request.HTTPMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") // send the request NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error) // look at the response if let httpResponse = response as? NSHTTPURLResponse { println("HTTP response: \(httpResponse.statusCode)") } else { println("No HTTP response") }
它看起来像你有所有正确的作品,只是不正确的顺序:
// create the request & response var request = NSMutableURLRequest(URL: NSURL(string: "http://requestb.in/1ema2pl1"), cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 5) var response: NSURLResponse? var error: NSError? // create some JSON data and configure the request let jsonString = "json=[{\"str\":\"Hello\",\"num\":1},{\"str\":\"Goodbye\",\"num\":99}]" request.HTTPBody = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) request.HTTPMethod = "POST" request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") // send the request NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error) // look at the response if let httpResponse = response as? NSHTTPURLResponse { println("HTTP response: \(httpResponse.statusCode)") } else { println("No HTTP response") }
这里是使用asynchronous请求的一些不同的方法。 你也可以使用这种同步方法,但是因为上面的每个人都使用了同步请求,所以我想反过来显示asynchronous请求。 另一件事是这样看起来更干净更简单。
let JSONObject: [String : AnyObject] = [ "name" : name, "address" : address, "phone": phoneNumber ] if NSJSONSerialization.isValidJSONObject(JSONObject) { var request: NSMutableURLRequest = NSMutableURLRequest() let url = "http://tendinsights.com/user" var err: NSError? request.URL = NSURL(string: url) request.HTTPMethod = "POST" request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.HTTPBody = NSJSONSerialization.dataWithJSONObject(JSONObject, options: NSJSONWritingOptions(rawValue:0), error: &err) NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) {(response, data, error) -> Void in if error != nil { println("error") } else { println(response) } } }