快速使用almofire从字符串响应中获取数据

时间:2018-09-20 09:00:12

标签: swift

我尝试使用传入字符串的alamofire.response发布一些数据。现在我该如何从字符串响应中获取数据。

Alamofire.request(url, method: .post, parameters: ["API":"get_blog_list","user_id":"18","page":"1"], encoding: URLEncoding.default).responseString(completionHandler: { (response) in
    guard let datastring = response.result.value else { return }
    print(datastring)

我的回应(数据字符串)是

{
   "success" : "1",
   "totalpage" : "2",
   "blogdata" : [
             {
              "int_glocode" : "18",
              "var_blogtitle" : "ssss",
              "tblogdescription" : "ssssss",
              "var_images" : "http//url",
              "dt_creatdate" : "21-8-2017",
              "flag" : "false"
             }
            {
              "int_glocode" : "19",
              "var_blogtitle" : "ssss",
              "tblogdescription" : "ssssss",
              "var_images" : "http//url",
              "dt_creatdate" : "21-8-2017",
              "flag" : "false"
             }
          ]
}

现在我要获取“ var_blogtitle”,“ tblogdescription”,“ var_images”的数据 所以我为此创建了

struct Data:Decodable {
    var var_image: URL
    var tblogdescription : String
    var var_blogtitle: String

    init(blogdata:[String:Any]) {
        self.var_blogtitle = blogdata["var_blogtitle"] as! String
        self.tblogdescription = blogdata["tblogdescription"] as! String
        self.var_image = blogdata["var_image"] as! URL

    }
}

1 个答案:

答案 0 :(得分:-1)

使用此代码作为参考。但是请确保您的JSON有效。

Alamofire.request(url, method: .post, parameters ["API":"get_blog_list","user_id":"18","page":"1"], encoding: URLEncoding.default).responseString(completionHandler: { (response) in
        guard let datastring = response.result.value else { return }

        if let data = datastring as? [String: AnyObject] {
            if let data = data["blogdata"] as? NSArray {
                for data in data {
                    if let data = data as? [String: AnyObject] {
                        let var_blogtitle = data["var_blogtitle"] as? String
                    }
                }
            }
        }
    })