OGeek|极客世界-中国程序员成长平台

标题: ios - Swift 3.0 和网络服务 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 18:32
标题: ios - Swift 3.0 和网络服务

尝试将我们的 Web 服务读入 UITableViewController,它只将第一条记录返回给模拟器。所以希望有人能够查看代码并引导我走上正确的道路。最终目标是将它放入 UITableViewCell 中,这样我就可以很好地格式化但只是想获取所有记录。

这是将返回的部分 json 文件的 View 。

{
"Count":11518,
"Result":[
    {
     "cuName": "#1",
     "charter_Num": 
     "16328","City": 
     "Jonesboro",
     "State_id": "GA",
     "cuName_location": "#1 - Jonesboro, GA"
     },
     {
     "cuName": "@lantec Financial",
     "charter_Num": "7965",
     "City": "Virginia Beach",
     "State_id": "VA",
     "cuName_location": "@lantec Financial - Virginia Beach, VA"
     }]
}

这是读取 json web 服务并尝试解析并放入表中的代码。

func get_data_from_url(_ link:String)
   {
    let url:URL = URL(string: link)!
    let session = URLSession.shared

    let request = NSMutableURLRequest(url: url)
    request.httpMethod = "GET"
    request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData


    let task = session.dataTask(with: request as URLRequest, completionHandler: {
        (
        data, response, error) in

        guard let _ata = data, let _:URLResponse = response  , error == nil else {
             return
        }


        self.extract_json(data!)
    })

    task.resume()
}


func extract_json(_ data: Data)
{
    let json: Any?

    do
    {
        json = try JSONSerialization.jsonObject(with: data, options: [])
    }
    catch
    {
        return
    }

    //Commented out the following lines because it doesn't return anything when using the modified code that works
    //
    //        guard let data_list = json as? NSArray else
    //        {
    //            return
    //        }

    //This code works but only gives me the 1st record back
    if let cu_list = try? json as? [String:Any],
        let result = cu_list?["Result"] as? [[String:Any]],
        let charter_num = result[0]["charter_Num"] as? String,
        let value = result[0]["cuName_location"] as? String, result.count > 0 {
        TableData.append(value + " (" + charter_num + ")")
    } else {
        print("bad json - do some recovery")
    }

    DispatchQueue.main.async(execute: {self.do_table_refresh()})

}



Best Answer-推荐答案


您指的是 result 对象中的第 0 个索引元素,它只会返回 JSON 数据中的第 1 条记录。您需要通过循环运行并将数据附加到您需要用于在 UITableView 中填充数据的数组。

关于ios - Swift 3.0 和网络服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41552772/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://jike.in/) Powered by Discuz! X3.4