ios - 从 Alamofire 和 SwiftyJSON 填充分组表

标签 ios json swift uitableview alamofire

我一直在尝试使用来自 Alamofire 请求的数据填充分组表。到目前为止,我已经成功地用数组中的静态数据填充了一个表(如图所示),但是经过数小时的尝试、查找和试验,我仍然不知道如何使用 JSON 数据。它应该不会有太大的不同,但需要注意的是,这是在 Swift 3 中。

如有任何帮助,我们将不胜感激。谢谢。

Here's what the layout looks like

这是我的静态代码,效果很好。

import UIKit
import Alamofire
import SwiftyJSON

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    //static Data Here:
    var array = [ ["Clients", "John Doe", "Joe Bloggs"],["Departments", "HR", "Admin", "Finance"]]
    let cellReuseIdentifier = "cell"
    @IBOutlet var tableView: UITableView!

    override func viewDidLoad() {
        tableView.delegate = self
        tableView.dataSource = self
        super.viewDidLoad()
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return array.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return array[section].count - 1
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell:AreasCustomCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! AreasCustomCell

         cell.areasPreview.contentMode = .scaleAspectFit
        request(.GET, "https://url.here.com", parameters: ["file": "default.png"]).response { (request, response, data, error) in
            cell.areasPreview.image = UIImage(data: data!, scale:0.5)
            }

        cell.areasCellLabel.text = array[indexPath.section][indexPath.row + 1]
        return cell
    }
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return array[section][0]
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("You tapped cell number \(indexPath.row).")
        //More things planned here later!
    }
}

这也是我正在使用的 JSON 的格式。

content =     {
    clients =         (
                    {
            desc = "Description here";
            group = client;
            id = "group_7jsPXXAcoK";
            name = "John Doe";
        },
                    {
            desc = "Description here";
            group = client;
            id = "group_19MrV7OLuu";
            name = "Joe Bloggs";
        }
    );
    departments =         (
                    {
            desc = "Description here";
            group = department;
            id = "group_PhAeQZGyhx";
            name = "HR";
        },
                    {
            desc = "Description here";
            group = department;
            id = "group_RMtUqvYxLy";
            name = "Admin";
        },
                    {
            desc = "Description here";
            group = department;
            id = "group_T50mxN6fnP";
            name = "Finance";
        }
    );
};
state = success;

到目前为止,我已经添加了一个新类来保存 JSON 数据,我相信这是朝着正确的方向前进。

class Group {

    let id : String
    let name : String
    let desc : String
    let group : String

    init(dictionary : [String : AnyObject]) {
        id = dictionary["id"] as? String ?? ""
        desc = dictionary["desc"] as? String ?? ""
        name = dictionary["name"] as? String ?? ""
        group = dictionary["group"] as? String ?? ""
    }
}

最后这是我首先获取 JSON 数据的函数,它应该从 viewDidLoad 调用。

func getData()
{
    let defaults = UserDefaults.standard()
    let token = defaults.string(forKey: defaultsKeys.userToken)
    let email = defaults.string(forKey: defaultsKeys.userEmail)
    request(.POST, "https://url.here.com/api/v2.php", parameters: ["type": "areas", "uEmail": email!, "token": token!])
        .responseJSON { response in
            var json = JSON(response.result.value!)
            let state = json["state"].stringValue
            if(state == "error"){
                print(json["message"].stringValue)
            } else {
                print(response.result.value)
                //Send JSON data here to Table!
            }
    }
}

最佳答案

typealias APIResultHandler = ((response: Int, json: JSON) -> Void)

func performAPICall(url: NSURL, method: String, body: String?, resultHandler: APIResultHandler) {
    let session = NSURLSession(configuration: .defaultSessionConfiguration())
    let tokenRequest = NSMutableURLRequest(URL: url)
    tokenRequest.HTTPMethod = method
    if body != nil && method == Constant.POST {
        tokenRequest.HTTPBody = body!.dataUsingEncoding(NSUTF8StringEncoding)
    }
    let dataTask = session.dataTaskWithRequest(tokenRequest) {
        (let data, let response, let error) in
        if let httpResponse = response as? NSHTTPURLResponse {
            if error == nil {
                let json = JSON(data: data!)
                resultHandler(response: httpResponse.statusCode, json: json)
            } else {
                print("Error during \(method) Request to the endpoint \(url).\nError: \(error)")
            }
        }
    }
    dataTask.resume()
}

结构客户端{ 变量标识:字符串 变量描述:字符串 变量名:字符串

init() {
    id = ""
    desc = ""
    name = ""
}

var clientArray: [客户端] = [] 让 body = "key1=(value1)&key2=(value2)&key3=(value3)&key4=(value4)&key5=(value5)"等等... 重写 func viewDidLoad() { super.viewDidLoad()

   performAPICall(url, method: "POST", body: body) {
            json in
        //this will have your full response
        print(json)

        //put this as a class variable instead in the call
        var clientArray: [Client] = []

        let clients = json["clients"]
        for client in clients {
              var thisClient = Client()
              thisClient.id = json["id"].string
              thisClient.desc = json["desc"].string
              thisClient.name = json["name"].string
              clientArray.append(thisClient)
        }
        tableview.reloadData()
  }

func tableView(tableView: UITableView, cellForRowAtindexPath: IndexPath) -> UITableViewCell {

    if section == 0 {
      let cell:AreasCustomCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! AreasCustomCell

      cell.areasPreview.contentMode = .scaleAspectFit
      cell.areasCellLabel.text = clientArray[indexPath.row]
    }

    if section == 1 {
        //do stuff for the other cell
    }
}

关于ios - 从 Alamofire 和 SwiftyJSON 填充分组表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38000179/

相关文章:

javascript - 使用直接输出将 JSON 从 PHP 传递到 Javascript

javascript - 使用ajax获取json数组值

javascript - ng-repeat 用于显示对象列表中的嵌套对象

ios - 从 UIImagePickerController 获取 UIImage 的 URL

ios - 如何查询 Parse 以从自定义类获取信息并将其显示在 Swift 的文本字段中?

ios - 是否可以在为 Social.framework 设置社交帐户后自动返回我的应用程序?

iphone - UVIews 缩放 UIScrollview 时的比例

iphone - IOS中如何停止调用循环功能

ios - swift 4 : Download photo from Firebase

ios - 快速获取另一个 ViewController 中选定单元格的数据(以编程方式)