Cannot display value in UITableView

时间:2016-02-03 04:14:02

标签: json swift uitableview

I am getting an error saying "NSString does not have member 'subscript'" on the following line.

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

Here is the code (error line is at the bottom).

 func makeGetRequest(){

        var url : String = "http://apiairline.yome.vn/api/get-airport"
        var request : NSMutableURLRequest = NSMutableURLRequest ()
        request.URL = NSURL(string: url)
        request.HTTPMethod = "GET"
        request.setValue("1454310830", forHTTPHeaderField: "TIMESTAMP")
        request.setValue("f8675bfb33f792eeef665da66848623539978204b3b1b036c79aa38218dd7061", forHTTPHeaderField: "HASH")

        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in
            var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
            let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary

            var _names: NSMutableArray = NSMutableArray()
            if (jsonResult != nil) {
                let dataArray = jsonResult["airport_list"] as NSArray;        
                var _names: NSMutableArray = NSMutableArray()
                for item :AnyObject in dataArray{
                    let obj = item as NSDictionary
                    let airport_name = obj["airport_name"] as NSString
                    let alias = obj["alias"] as NSString
                    let code = obj["code"] as NSString
                    let iata = obj["iata"] as NSString
                    let location = obj["location"] as NSString
                    let type = obj["type"] as NSString

                    _names.addObject(airport_name)
                    _names.addObject(alias)
                    _names.addObject(code)
                    _names.addObject(iata)
                    _names.addObject(location)
                    _names.addObject(type)

                     self.congchuoi = airport_name + alias + code + iata + location + type
                    println(self.congchuoi)
                    self.TableData = _names                                   
                }                                     
            } else {
                println("Failed")
            }

        })
    }


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell


        var airport_list = TableData[indexPath.row].valueForKey("airport_list") as NSDictionary
       var objname = airport_list.valueForKey("airport_name") as NSString
       cell.textLabel?.text = objname[indexPath.row]



        return cell
    }

2 个答案:

答案 0 :(得分:3)

您的代码存在一些问题。第一个是sendAsynchronousRequest在后​​台运行,并且一旦显示tableView就没有完成。因此,即使您没有编译错误,它也无法正常工作。您需要在完成处理程序中调用reloadData ...

func makeGetRequest(){

    var url : String = "http://apiairline.yome.vn/api/get-airport"
    var request : NSMutableURLRequest = NSMutableURLRequest ()
    request.URL = NSURL(string: url)
    request.HTTPMethod = "GET"
    request.setValue("1454310830", forHTTPHeaderField: "TIMESTAMP")
    request.setValue("f8675bfb33f792eeef665da66848623539978204b3b1b036c79aa38218dd7061", forHTTPHeaderField: "HASH")

    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in
        var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
        let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary

        if (jsonResult != nil) {
            dataArray = jsonResult["airport_list"] 
            _names = [NSDictionary]()
            for item: AnyObject in dataArray {
                let obj = item as NSDictionary
                _names.addObject(item)
            }
            self.TableData = _names
            dispatch_async(dispatch_get_main_queue()) {
                self.tableView.reloadData()
            }                                 
        } else {
            println("Failed")
        }

    })
}

然后:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
       let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
       let airport = self.TableData[indexPath.row]
       let airport_name = airport["airport_name"] as String
       cell.textLabel?.text = airport_name 
  }

答案 1 :(得分:0)

使用makeGetRequest函数

                _names.addObject(airport_name)
                _names.addObject(alias)
                _names.addObject(code)
                _names.addObject(iata)
                _names.addObject(location)
                _names.addObject(type)

- &GT; self.TableData是NSString数组,在cellforrowatindexpath中:

var airport_list = TableData[indexPath.row].valueForKey("airport_list") as NSDictionary
       var objname = airport_list.valueForKey("airport_name") as NSString

airport_list不是字典

您更新:

for item :AnyObject in dataArray{
        let obj = item as NSDictionary
        let airport_name = obj["airport_name"] as NSString
        let alias = obj["alias"] as NSString
        let code = obj["code"] as NSString
        let iata = obj["iata"] as NSString
        let location = obj["location"] as NSString
        let type = obj["type"] as NSString

        _names.addObject(item)

        self.congchuoi = airport_name + alias + code + iata + location + type
        println(self.congchuoi)
        self.TableData = _names
    }

并在cellForRowAtIndexPath中使用:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell


    if let airport_list = TableData[indexPath.row] as? NSDictionary{
        var objname = airport_list.valueForKey("airport_name") as NSString
        cell.textLabel?.text = objname[indexPath.row]
    }
    return cell
}

(hoặcmìnhnghĩlàbạnmuốnhiểnthịhếtnhữngvaluelấyvềtừservernêncóthểgiữnguyênhàmmakeGetRequest) Trong cellForRowAtIndexPath更新:

        override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell


        if let str = TableData[indexPath.row] as? NSString{
            cell.textLabel?.text = str
        }
        return cell
    }