如何使用新的Apple Swift语言发布JSON

Tha*_*s P 9 post json ios swift

我(试图)学习Swift的Apple语言.我在Playground并使用Xcode 6 Beta.我正在尝试向本地NodeJS服务器执行简单的JSON Post.我已经开始搜索它了,主要的教程解释了如何在一个项目中进行,而不是在PLAYGROUND,而不是写愚蠢的想法:"谷歌它"或"它很明显"或"看这个链接"或从不 - 测试 - 和 - 不官能码

这就是我正在尝试的:

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)
Run Code Online (Sandbox Code Playgroud)

我试过了:

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()
Run Code Online (Sandbox Code Playgroud)

谢谢!:)

Nat*_*ook 12

看起来你有所有正确的部分,只是没有正确的顺序:

// 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")
}
Run Code Online (Sandbox Code Playgroud)

  • Nate,我尝试了你的代码并输出:"2014-07-05 12:05:24.125 PlaygroundStub_sim [1023:194623]***createStorageTaskManagerForPath:withIdentifier failed:Error Domain = NSCocoaErrorDomain Code = 4099"操作无法完成.(Cocoa error 4099.)"(名为com.apple.nsurlstorage-cache的服务连接无效.)UserInfo = 0x10bb2fb70 {NSDebugDescription =名为com.apple.nsurlstorage-cache的服务连接无效.}; {NSDebugDescription = "名为com.apple.nsurlstorage-cache的服务连接无效.";} HTTP响应:200" (2认同)

小智 12

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")
}
Run Code Online (Sandbox Code Playgroud)


Cod*_*ide 5

这是使用异步请求的一种不同的方法.您也可以这样使用同步方法,但由于上面的每个人都使用了同步请求,我认为显示异步请求.另一件事是这样看起来更干净,更容易.

    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) 

            }
        }
    }
Run Code Online (Sandbox Code Playgroud)