Показать данные в табличном виде из MySQL, используя alamofire и swiftyjson - PullRequest
0 голосов
/ 28 октября 2018

У меня есть php-скрипт на моем сервере, который является простым SQL-оператором SELECT, который получает некоторые данные из базы данных mysql и возвращает количество строк.

Я использовал alamofire и swiftyjson для печати данных на консоль, но я хочу показать их в виде таблицы.

Из-за того, что вызов не находится в той же области, что и код tableView (я думаю, именно поэтому я получаю сообщение об ошибке «Использование неразрешенного идентификатора»)

Я не являюсьВы знаете, как сделать его глобальным, но я думаю, что мне нужно создать переменную глобального массива, но не уверен, должен ли он быть просто пустым?

global:

 let serviceURL = "http://example.com/service.php"

Я поместил это в функциювот так:

    func getUsers() {

    Alamofire.request(serviceURL, method: .get).validate().responseJSON { (response) in

        if response.result.isSuccess {

            let userJSON : JSON = JSON(response.result.value!)


            for (index,subJson):(String, JSON) in userJSON  {
                let firstName = subJson["first_name"].string 
                let lastName = subJson["last_name"].string
                print(firstName)
            }

        } else {

            print("Could not get results")
        }
    }
}

Мне нужно как-то подсчитать возвращаемые строки

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

   return firstName.count

}

И затем фактически отобразить в ячейке

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "userCell", for: indexPath)

    cell.textLabel?.text = names[indexPath.row]

    return cell
}

ОБНОВЛЕНИЕ

import UIKit
import Alamofire
import SwiftyJSON

struct User {
    var firstName: String
    var lastName: String

    private enum CodingKeys: String, CodingKey {

        case firstName = "first_name"
        case lastName = "last_name"
    }
}

class UserTableViewController: UITableViewController {

    var users = [User]()

    let serviceURL = "http://example.com/service.php"


    override func viewDidLoad() {
        super.viewDidLoad()
        getUsers()

    }


    func getUsers() {
        Alamofire.request(serviceURL, method: .get).validate().responseJSON { (response) in
            if response.result.isSuccess {
                let userJSON : JSON = JSON(response.result.value!)

                for (index,subJson):(String, JSON) in userJSON  {
                    let firstName = subJson["first_name"].string
                    let lastName = subJson["last_name"].string
                    let user = User(firstName: firstName!, lastName: lastName!)
                    self.users.append(user)

                }
            } else {
                print("Could not get results")
            }
        }
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return users.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "userCell", for: indexPath)
        let user = users[indexPath.row]
        cell.textLabel?.text = "\(user.firstName) \(user.lastName)"

        return cell
    }
}

1 Ответ

0 голосов
/ 28 октября 2018

Прежде всего вам нужна структура для хранения ваших данных

struct User {
    var firstName: String
    var lastName: String
}

Затем вам нужен массив для хранения пользователей из сообщения json, объявите его как атрибут в вашем контроллере представления

var users = [User]()

А затем используйте это в своем коде

func getUsers() {
    Alamofire.request(serviceURL, method: .get).validate().responseJSON { (response) in
        if response.result.isSuccess {
            let userJSON : JSON = JSON(response.result.value!)

            for (index,subJson):(String, JSON) in userJSON  {
                let firstName = subJson["first_name"].string 
                let lastName = subJson["last_name"].string
                let user = User(firstName: firstName, lastName: lastName)
                users.append(user)
            }
        } else {
            print("Could not get results")
        }
    }
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
   return users.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "userCell", for: indexPath)
    let user = users[indexPath.row]
    cell.textLabel?.text = "\(user.firstName) \(user.lastName)"

    return cell
}
...