ios - 根据输入从服务器端检索数据

标签 ios json swift

我正在做一个学校项目,它有多个表和 tabBarController。现在,我想根据所选行显示从服务器端返回的数据。我设法将选定的行从 View 传递到另一个 View ,并且我相信将其传递到服务器端也没有任何问题。问题是从服务器检索数据时。

这是类(class) View

    // This array is to hold data coming from server side
var course: NSArray = []

// Assign data that come from DepartmentView
public var department: String? = nil

var myURL = URL(string: "http://localhost/masterProject/scripts/courses.php")

override func viewDidLoad()
{
    super.viewDidLoad()

    self.title = "Courses"
}

override func viewWillAppear(_ animated: Bool)
{
    super.viewWillAppear(animated)

    // This is just to make sure it gets data and not nil
    let vDepartment = department!

    // Create a request
    var request = URLRequest(url: myURL!)
    request.httpMethod = "POST";

    // Create a parameter to be sent to server side and based on this
    // data I want to get data back that belong to it.
    let postParameter = "department=\(vDepartment)";

    request.httpBody = postParameter.data(using: String.Encoding.utf8)

    // Here I Create and send dataTask
    let task = URLSession.shared.dataTask(with: request)
    { (data: Data?, response: URLResponse?, error: Error?) in

        DispatchQueue.main.async
        {
            if(error != nil)
            {
                self.alertMessage(message: (error?.localizedDescription)!)
                return
            }

           // This is supposed to read data from server side and display it
           // in Course table view.
            self.course = try! JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! NSArray
        }
    }
    task.resume()
}

// MARK: - Table view data source

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

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    let cell = tableView.dequeueReusableCell(withIdentifier: "courseCell", for: indexPath) as! CourseTableViewCell
    let main = course[indexPath.row] as! NSDictionary

    cell.courseName.text = (main["name"] as! String)
    cell.courseNumber.text = (main["number"] as! String)


    return cell
}

func alertMessage(message: String)
{
    let alert = UIAlertController(title: "Alert", message: message, preferredStyle: .alert)
    let action = UIAlertAction(title: "Ok", style: .default, handler: nil)
    alert.addAction(action)
    self.present(alert, animated: true, completion: nil)
}

部门 View

  var departments: NSArray = []
var myURL = URL(string: "http://localhost/masterProject/scripts/department.php")


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

override func viewWillAppear(_ animated: Bool)
{
    self.title = "Departments"

    super.viewWillAppear(animated)
    let data = NSData(contentsOf: myURL!)

    departments = try! JSONSerialization.jsonObject(with: data! as Data, options: .mutableContainers) as! NSArray
}


// MARK: - Table view data source

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    // #warning Incomplete implementation, return the number of rows
    return departments.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    let data = departments[indexPath.row] as! NSDictionary
    cell.textLabel?.text = (data["name"] as! String)

    return cell
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
    if segue.identifier == "showDepCourses"
    {
        if let indexPath = tableView.indexPathForSelectedRow
        {
            let courseVC = segue.destination as! CourseTableViewController
            let data = departments[indexPath.row] as! NSDictionary
            courseVC.department = (data["name"] as! String)
        }
    }
}

}

这是两个 View 的图片

department view

course view

我应该根据所选行获取正确的数据,但它什么也没显示。

最佳答案

self.tableView.reloadData() 一直缺失。

这是问题的答案:

override func viewWillAppear(_ animated: Bool)
{
    super.viewWillAppear(animated)

    // Just to make sure "Optional" keyword not send as POST PERAMETER
    let selectedDep = department!

    // Create a request
    var request = URLRequest(url: myURL!)
    request.httpMethod = "POST";

    // Create a parameter to be sent to server side and based on this
    // data I want to get data back that belong to it.
    let postParameter = "department=\(selectedDep)";

    request.httpBody = postParameter.data(using: String.Encoding.utf8)

    // Here I create and send dataTask
    let task = URLSession.shared.dataTask(with: request)
    { (data: Data?, response: URLResponse?, error: Error?) in

        DispatchQueue.main.async
            {
                if(error != nil)
                {
                    self.alertMessage(message: (error?.localizedDescription)!)
                    return
                }

                // This is supposed to read data from server side and display it
                // in Course table view.
                self.courses = try! JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! NSArray
                self.tableView.reloadData()
        }
    }
    task.resume()
}

关于ios - 根据输入从服务器端检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43129137/

相关文章:

ios - 将 .cer 转换为 .p12

java - 如何从嵌套在多个数组中的 JSON 读取值

json - JSP 发起 http get 请求并获取 json 响应

ios - Swift 中的 AFNetworking 可达性管理器

ios - 核心数据终止错误

ios - 如何将属性数据从实体加载到单个 (1) UIViewController 中?

ios - 使用基于图像的光照在 3D 模型上应用 PBR 纹理

ios - 在 Cocoa 中以编程方式创建 NSView

json - 以不区分大小写的方式使用 json_populate_recordset

ios - 将目标添加到 UIButton 不起作用