Swift 3 / Alamofire 4:使用TableView上的ID获取数据

时间:2017-06-30 03:15:14

标签: ios swift xcode swift3 alamofire

我正在尝试使用ViewController上的ID获取数据。我有两个viewcontrollers,当我按下Cell(来自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
}



}

感谢您的时间和精力:)

2 个答案:

答案 0 :(得分:2)

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)

答案 1 :(得分:0)

制作一个Swift文件并将此代码放入APi.swift

APi.swift

    import Foundation

    import Alamofire


    class APIClient {

    internal typealias CompletionBlock = (_ data:NSDictionary?,_ error:NSError?) -> Void

         fileprivate class func executePostAPICallWithMethod(_ method:String ,withParameters parameters:AnyObject?, callback:@escaping CompletionBlock) {

                let str = method


                Alamofire.request(str, method: .post, parameters: parameters as? [String : AnyObject], encoding: JSONEncoding.default).responseJSON { response in
                    switch response.result {
                    case .success(let JSON):
                        //                    print("Success with JSON: \(JSON)")
                        print("Request failed with error: \(response.response?.statusCode)")

                        let response = JSON as! NSDictionary

                        callback(response,nil)
                        break

                    case .failure(let error):
                        print("Request failed with error: \(error)")
                        callback(response.result.value as? NSMutableDictionary,error as NSError?)
                        break
                    }
                    }
                    .responseString { response in
                        print("Response String: \(response.result.value)")
                }

            }

          class func loadCategories(_ detail : [String : AnyObject],completion:@escaping CompletionBlock){

                let strMethod = String(format : "http://www.URL.com.au/database/results.php" )
                self.executePostAPICallWithMethod(strMethod, withParameters: detail as AnyObject?) { (data, error) -> Void in
                    completion(data,error)
                }
            }

    }

在ViewController中2在ViewDidLoad中调用此函数

func loadCategories(id : String)
{
 let userDic : [String : AnyObject] = ["id":id as AnyObject]

        APIClient.loadCategories(userDic,completion:{ (data, error)->Void in
            if((error) != nil) {

                if((data) != nil){


                } else {

                }
            } else {

                print(data as Any)



                //self.tableview.reloadData()
            }

        })

}