UITableCell值没有传递给UIViewController Swift 3中的函数

时间:2017-08-16 17:02:01

标签: ios swift uitableview

我有一个由搜索功能填充的表格。单元格中有两个按钮,对用户说“是”和“否”表示“是”。有一个插入函数将选择插入数据库。不幸的是,表中的值没有传递给insert函数。在insert函数中,我使用的是guestusername.text,它是我单元格中标签的名称。我收到错误'使用未解析的标识符guestusername'。我已经尝试了我能想到的一切,代码如下。

class MyShotsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    var guest = [AnyObject]()
    var avas = [UIImage]()
    var valueToPass:String!
    var revieweduser:String!
    var age = [AnyObject]()
    var city = [AnyObject]()
    var state = [AnyObject]()
    @IBOutlet var tableView: UITableView!
    var cell: MyShotsCell?
    var index = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        doSearch("")
    }

    // cell numb
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return guest.count
    }

    // cell config
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! MyShotsCell

        // get one by one user related inf from users var
        let guest2 = guest[indexPath.row]
        let ava = avas[indexPath.row]        

        // shortcuts
        let guestname = guest2["username"] as? AnyObject
        let age = guest2["age"]
        let city = guest2["city"] as? String
        let state = guest2["state"] as? String

        // refer str to cell obj
        cell.guestusername.text = guestname as! String
        cell.ageLbl.text = (NSString(format: "%@", age as! CVarArg) as String)
        cell.cityLbl.text = city
        cell.stateLbl.text = state
        cell.avaImg.image = ava as? UIImage

        return cell
    }

    // search / retrieve users
    public func doSearch(_ guestusername : String) {
        // shortcuts
        let username = user?["username"] as! String        
        let url = URL(string: "http://www.xxxxx.com/xxxxx.php")!

        var request = URLRequest(url: url) // create request to work with users.php file

        request.httpMethod = "POST" // method of passing inf to users.php

        let body = "revieweduser=\(username)" // body that passes inf to users.php

        request.httpBody = body.data(using: .utf8) // convert str to utf8 str - supports all languages

        // launch session
        URLSession.shared.dataTask(with: request) { data, response, error in
            // getting main queue of proceeding inf to communicate back, in another way it will do it in background
            // and user will no see changes :)
            DispatchQueue.main.async(execute: {
                if error == nil {                        
                    do {
                        let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

                        // clean up
                        self.guest.removeAll(keepingCapacity: false)
                        self.avas.removeAll(keepingCapacity: false)
                        self.tableView.reloadData()

                        // delcare new secure var to store json
                        guard let parseJSON = json else {
                            print("Error while parsing")
                            return
                        }

                        guard let parseUSERS = parseJSON["users"] else {
                            print(parseJSON["message"] ?? [NSDictionary]())
                            return
                        }

                        self.guest = parseUSERS as! [AnyObject]
                        print(self.guest)

                        // for i=0; i < users.count; i++
                        for i in 0 ..< self.guest.count {
                            // getting path to ava file of user
                            let ava = self.guest[i]["ava"] as? String

                            let revieweduser = self.guest[i]["username"] as? String
                            let age = (NSString(format: "%@", self.guest[i]["age"] as! CVarArg) as String)
                            let city = self.guest[i]["city"] as? String
                            let state = self.guest[i]["state"] as? String

                        self.tableView.reloadData()
                    } catch {
                        DispatchQueue.main.async(execute: {
                            let message = "\(error)"
                            appDelegate.infoView(message: message, color: colorSmoothRed)
                        })
                        return
                    }
                } else {
                    DispatchQueue.main.async(execute: {
                        let message = error!.localizedDescription
                        appDelegate.infoView(message: message, color: colorSmoothRed)
                    })
                    return
                }
            })

            } .resume()
    }

    // custom body of HTTP request to upload image file
    func createBodyWithParams(_ parameters: [String: String]?, boundary: String) -> Data {
        let body = NSMutableData();

        if parameters != nil {
            for (key, value) in parameters! {
                body.appendString("--\(boundary)\r\n")
                body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
                body.appendString("\(value)\r\n")
            }
        }

        return body as Data
    }

    func insertShot(_ rating : String) {
        self.tableView.reloadData()

        let reviewer = user?["username"] as! String

        // url path to php file
        let url = URL(string: "http://www.xxxxxx.com/xxxxxxx.php")!
        var request = URLRequest(url: url)
        request.httpMethod = "POST"

        // param to be passed to php file
        let param = [
            "user" : reviewer,
            "revieweduser" : cell?.guestusername.text,
            "rating" : rating
            ] as [String : Any]

        // body
        let boundary = "Boundary-\(UUID().uuidString)"
        request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

        // ... body
        request.httpBody = createBodyWithParams(param as? [String : String], boundary: boundary)

        // launch session
        URLSession.shared.dataTask(with: request) { data, response, error in
            // get main queu to communicate back to user
            DispatchQueue.main.async(execute: {
                if error == nil {
                    do {
                        // json containes $returnArray from php
                        let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

                        // declare new var to store json inf
                        guard let parseJSON = json else {
                            print("Error while parsing")
                            return
                        }

                        // get message from $returnArray["message"]
                        let message = parseJSON["message"]
                        //print(message)

                        // if there is some message - post is made
                        if message != nil {

                            // reset UI
                            // self.msgTxt.text = ""

                            // switch to another scene
                            //self.tabBarController?.selectedIndex = 3
                            _ = self.navigationController?.popViewController(animated: true)
                        }
                    } catch {
                        // get main queue to communicate back to user
                        DispatchQueue.main.async(execute: {
                            let message = "\(error)"
                            appDelegate.infoView(message: message, color: colorSmoothRed)
                        })
                        return
                    }
                } else {
                    // get main queue to communicate back to user
                    DispatchQueue.main.async(execute: {
                        let message = error!.localizedDescription
                        appDelegate.infoView(message: message, color: colorSmoothRed)
                    })
                    return
                }
            })
            }.resume()
        return
    }

    @IBAction func yesBtn_clicked(_ sender: UIButton) {
        self.insertShot("Yes")
    }

    @IBAction func noBtn_clicked(_ sender: UIButton) {
        self.insertShot("No")
    }
}

0 个答案:

没有答案