简体   繁体   English

如何在没有“键 - 值”对格式的swift中发送json对象

[英]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. 嘿所以我必须向Django-server发送一个令牌字符串,它只接受一个字符串。 I am trying to use alamo fire to do this, however I cant send a key-value pair to resolve this problem. 我试图用alamo fire来做这件事,但我不能发送一个键值对来解决这个问题。 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. 我是新的IOS开发人员,这是我的第一个项目,我是社区的新手。 Thank you. 谢谢。

Convert your dictionary into a JSON string and ship it off that way: 将您的字典转换为JSON字符串并以此方式发送:

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. 这取决于你如何需要发送的令牌(POST VS GET VS HTTP身体VS查询字符串)......你可能需要改变以下。 But it should get you started with NSURLSession . 但它应该让你开始使用NSURLSession This will send the token 189E23FL2 to the server with POST as a HTTP Body parameter. 这将使用POST作为HTTP Body参数将令牌189E23FL2发送到服务器。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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