Swift: Filter a POST http request answer

感情迁移 提交于 2020-01-07 07:38:10

问题


On swift, I am querying a server by an HTTP Post request, with:

let myUrl = NSURL(string: "http://****.*****.***.***/****.php"); 
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST"
let session = NSURLSession.sharedSession()

var getDefaults = NSUserDefaults.standardUserDefaults();
var password = getDefaults.valueForKey("password") as! String;
var id = getDefaults.valueForKey("login") as! String;

var err: NSError?

let postString = "Method=Tasks.getTasksByFolder" + "&Identifiant=" + id + "&Password=" + password + "&data={\"folder\":\"" + folder + "\"}" // filter = {"folder":"INBOX"}

request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
    data,response,error in

    if error != nil{
        println("error=\(error)")
        return
    }

println("**** response = \(response)")


let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("**** response data = \(responseString)")


var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &err) as? NSDictionary


}
task.resume()

It works and this is an example of what it returns to me:

**** response data = Optional({"result":true,"data":"[{\"id\":\"b43bd766295220b23279899d025217d18e98374a\",\"container_id\":\"6658\",\"created_by\":\"76bbfe695318d471a541bc3333e58eea28acae54\",\"creation_time\":\"2015-05-26 15:20:32\",\"last_modified_by\":null,\"last_modified_time\":null,\"is_deleted\":\"0\",\"deleted_by\":null,\"deleted_time\":null,\"percent\":\"0\",\"completed\":null,\"due\":null,

etc......

I'm trying to filter this JSON encoded answer, indeed, I only want a few informations, not all of them. For example, I only want to get "container_id", "creation_time" and "last_modified_by" to print them on a UITableView. How am I supposed to get them? Is it on the POST request, is it a filter on the answer ? I've searched for a while on the net and I haven't found anything, excerpt the use of JSON parser, like https://github.com/owensd/json-swift but I have one problem with.. I haven't the JSON datas written on my code, it's obtained by an HTTP Post Request.. As consequence,

if let last_modified_by = json["last_modified_by"].string{
    println("last_modified_by = '\(last_modified_by)'")
}

got the error "Ambiguous use of 'string'"

Hope I am concise enough, I can edit my post if you need more code or explanations.

Regards,

fselva


回答1:


Your JSON string is wrong, there's a " that shouldn't be there before the array delimiter:

{"result":true,"data":"[{\"id\":\"b43bd766295
                      ^

Also, the " for result and data should be escaped, as they are later in the string. Example:

{\"result\":true,\"data\":[{\"id\":\"b43bd766295220b23279899d025217d18e98374a\", ...

After that, you're good to go:

var err: NSError?
let json = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: &err) as? [String:AnyObject]
// we cast `json!["data"]` as an array of dictionaries
if let dataDic = json!["data"] as? [[String:AnyObject]] {
    if let firstID = dataDic[0]["id"] as? String {
        println(firstID) // "b43bd766295220b23279899d025217d18e98374a"
    }
}


来源:https://stackoverflow.com/questions/30569960/swift-filter-a-post-http-request-answer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!