How to post a JSON with new Apple Swift Language

前端 未结 3 1171
南方客
南方客 2021-01-12 01:00

I\'m (trying to) learn the Swift\'s Apple language. I\'m at Playground and using Xcode 6 Beta. I\'m trying to do a simple JSON Post to a local NodeJS server. I already had g

相关标签:
3条回答
  • 2021-01-12 01:33

    It looks like you have all the right pieces, just not in quite the right order:

    // 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")
    }
    
    0 讨论(0)
  • 2021-01-12 01:43

    Nate's answer was great but I had to change the request.setvalue for it to work on my server

    // 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")
    }
    
    0 讨论(0)
  • 2021-01-12 01:50

    Here is a little different approach using asynchronous request. You can use synchronous approach this way too but since everyone above used synchronous request, I thought show asynchronous request instead. Another thing is it seems cleaner and easier this way.

        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) 
    
                }
            }
        }
    
    0 讨论(0)
提交回复
热议问题