简体   繁体   中英

How to send json object in swift without “key - value” pair format

Hey so I have to send aa token string to the Django-server and it only accepts one string. I am trying to use alamo fire to do this, however I cant send a key-value pair to resolve this problem. Is there an alternative solution for this. I am new IOS developer and this is my first project and I am new to the community. Thank you.

Convert your dictionary into a JSON string and ship it off that way:

func jsonStringify(data: AnyObject) -> NSData? {
    var error: NSError?

    if let json = NSJSONSerialization.dataWithJSONObject(
        data,
        options: NSJSONWritingOptions(0),
        error: &error
        ) {
            return json
    } else {
        return nil
    }
}

Depending on how you need to send the token (POST vs GET vs HTTP Body vs Query String)... you might need to change the below. But it should get you started with NSURLSession . This will send the token 189E23FL2 to the server with POST as a HTTP Body parameter.

let url = NSURL(string: "http://some-server/endpoint")

var request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.HTTPBody = "189E23FL2".dataUsingEncoding(NSUTF8StringEncoding)

// if you need a csrf token, add something like this as well:
// request.addValue("the-csrf-token", forHTTPHeaderField: "X-CSRFToken")

var sessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
var session = NSURLSession(configuration: sessionConfiguration)
var task = session.dataTaskWithRequest(request, completionHandler: { (data : NSData!, response : NSURLResponse!, error : NSError!) -> Void     in

    if (error == nil) {
        println("Done!")
    } else {
        println("Errorororororor")
    }
})

// start the task
task.resume()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM