【问题标题】:How to post a JSON with new Apple Swift Language如何使用新的 Apple Swift 语言发布 JSON
【发布时间】:2014-08-25 07:32:06
【问题描述】:

我正在(尝试)学习 Swift 的 Apple 语言。我在 Playground 并使用 Xcode 6 Beta。我正在尝试对本地 NodeJS 服务器进行简单的 JSON 发布。我已经用谷歌搜索过了,主要教程解释了如何在项目中而不是在 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)

我试过了:

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()

谢谢! :)

【问题讨论】:

    标签: ios json post swift


    【解决方案1】:

    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")
    }
    

    【讨论】:

    • 在这一行我得到了例外声明 request.HTTPBody = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) 但它已经被声明了。
    【解决方案2】:

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

    // 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")
    }
    

    【讨论】:

    • Nate,我试过你的代码,它的输出是:“2014-07-05 12:05:24.125 PlaygroundStub_sim[1023:194623] ***createStorageTaskManagerForPath:withIdentifier failed: Error Domain=NSCocoaErrorDomain Code=4099 “手术无法完成。 (Cocoa 错误 4099。)“(与名为 com.apple.nsurlstorage-cache 的服务的连接已失效。) UserInfo=0x10bb2fb70 {NSDebugDescription=与名为 com.apple.nsurlstorage-cache 的服务的连接已失效。}; { NSDebugDescription = “与名为 com.apple.nsurlstorage-cache 的服务的连接已失效。”; } HTTP 响应:200”
    • @CodeWarrior 我遇到了同样的问题!你解决了吗?
    【解决方案3】:

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

        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) 
    
                }
            }
        }
    

    【讨论】:

    • 关于如何将 JSON 数组包含为数组的 hte JSON 对象之一的任何想法?我正在构建一个 JSON 字符串并将其添加为我的一个 JSON 对象的值,但这失败了(转义字符被解析)。我的服务器正在记录 \"[{\"Key\":\"Value\"}]\"
    猜你喜欢
    • 2014-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-23
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多