ios - swift 3/ Alamofire 4 : Fetching data with the ID on a TableView

标签 ios swift xcode swift3 alamofire

我正在尝试使用 ViewController 上的 ID 获取数据。我有两个 View Controller ,当我按下单元格(来自 ViewController 1)时,它有一个 ID 并转到 ViewController 2 并获取分配给该 ID 的所有记录。例如,在 ViewController 1 上,我有一个 UITableView 并且有 20 个单元格。每个单元都有一个从数据库动态分配的 ID。当我按下单元格时,假设我按下了第 9 个单元格,其 ID 为 99,那么它会转到 ViewController 2 并获取外键 ID 为 99 的所有记录。

请在下面找到我的 ViewController 2 代码:

import UIKit
import Alamofire
import SwiftyJSON


class CategoryViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, NSURLConnectionDelegate {

var tableData = Array<Category>()
var arrRes = [[String:AnyObject]]() //Array of dictionary
var category = [Category]()
var catTitle = ""
var id = ""



@IBOutlet weak var catTitleRec: UILabel!

@IBOutlet weak var tableview: UITableView!




override func viewDidLoad() {
    super.viewDidLoad()

    catTitleRec.text = catTitle
    loadCategories()
}

func loadCategories(){

    let testhappyhour:Category = Category(tempName: "category.NAME", tempID: "category.id",  tempgbcount: "TOTAL")
    self.category.append(testhappyhour)

    let postID = "id="+id

    print("Response ID-is: \(postID)") // Able to get the ID here

    Alamofire.request("http://www.URL.com.au/database/results.php").responseJSON
        { response in switch response.result {
        case .success(let JSON):
            let response = JSON as! NSArray
            print("Response: \(response)")
            for item in response { // loop through data items
                let obj = item as! NSDictionary
                let happyhour = Category(tempName:obj["category.NAME"] as! String, tempID:obj["category.id"] as! String,  tempgbcount:obj["TOTAL"] as! String)
                self.category.append(happyhour)
                self.arrRes.append(obj as! [String : AnyObject]) // ADD THIS LINE
            }
            self.tableview.reloadData()

        case .failure(let error):
            print("Request failed with error: \(error)")
            }
    }
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    tableview.reloadData()
}

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

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    //return myarray.count
    return arrRes.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "groupCell") as! GroupCellTableViewCell
    var dict = arrRes[indexPath.row]

    cell.nametextlabel.text = dict["category.NAME"] as? String
    cell.totaltextlabel?.text = dict["TOTAL"] as? String

    return cell
}



}

感谢您的时间和精力:)

最佳答案

func loadCategories(id : String) {


    let userDic : [String : AnyObject] = ["id":id as AnyObject]

      Alamofire.upload(multipartFormData: { multipartFormData in

        for (key, value) in userDic {
            multipartFormData.append(value.data(using: String.Encoding.utf8.rawValue)!, withName: key)
        }

    },to: "http://www.URL.com.au/database/results.php" , method: .post, headers: nil ,
      encodingCompletion: { encodingResult in
        switch encodingResult {
        case .success(let upload, _, _):
            upload.response { [weak self] response in
                guard self != nil else {
                    return
                }
                debugPrint(response)

            }

            upload.responseJSON {  response in

                print(response)
                let responseJSON = response.result.value as! NSDictionary


                print(responseJSON)



            }

        case .failure(let encodingError):
            print("error:\(encodingError)")
        }


    })

使用 ViewDidLoad 中的 ID 调用此函数

loadCategories(id:id)

关于ios - swift 3/ Alamofire 4 : Fetching data with the ID on a TableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44838031/

相关文章:

ios - 将 JSON 数据与单元格一起使用

iphone - uitableviewcell 交替背景单元格颜色,即使对于没有数据的单元格也是如此

swift - 从完成处理程序中断循环

swift - 有没有办法在 VStack 中放置两个图像并调整图像大小和缩放到填充? swift 用户界面

objective-c - 在其他 View 中调用时,使用 Interface Builder 创建的自定义 View 不会呈现

ios - 来自 iOS 的 Firebase 云消息传递和多主题订阅失败

android - 在我的网络上使用 Mac 运行 Xamarin 应用程序时找不到文件 : Error for Contents. json

ios - 动画递增 UILabel

ios - Xcode/Objective-C - 通过prepareForSegue传递数据

objective-c - .h 文件未找到