在NSURL会话期间添加NSMutableArray()会话后无法识别

时间:2015-11-13 16:33:26

标签: ios scope swift2


我正在使用NSURL来获取网站页面的源代码。我通过URL传递MySQL查询指令以与数据库交互以获取用户朋友的列表。一切正常,直到将返回的数据添加到数组,将它们归档到表视图中。网站的响应打印到终端,但是如果我将它添加到要添加到表视图的数组中,则在NSURl会话完成后无法识别。
代码:

//
//  viewFriendsViewController.swift
//  collaboration
//
//  Created by nick on 11/12/15.
//  Copyright © 2015 Supreme Leader. All rights reserved.
//

import UIKit

class viewFriendsViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!

    var textArray: NSMutableArray! = NSMutableArray()

    func tableView(tableView: UITableView, numberOfRowsInSection Section: Int) -> Int {
        return self.textArray.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell: UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell")! as UITableViewCell
        cell.textLabel?.text = self.textArray.objectAtIndex(indexPath.row) as? String
        return cell
    }

    override func viewWillAppear(animated: Bool) {
        let username = NSUserDefaults.standardUserDefaults().stringForKey("username")
        if username != nil {
            let myUrl = NSURL(string: "http://www.casacorazon.org/ios.html")
            let request = NSMutableURLRequest(URL: myUrl!)
            request.HTTPMethod = "POST"
            let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
                data, response, error in
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
                    let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
                    if error != nil {
                        print("Error: \(error)")
                    }
                    self.textArray.addObject(responseString as! String)
                }
            }
            task.resume()
        } else {
            self.textArray.addObject("Error")
            self.textArray.addObject("You are not logged in")
        }
        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.tableView.estimatedRowHeight = 44.0
    }
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }
}


谢谢你的帮助

1 个答案:

答案 0 :(得分:1)

您必须重新加载表格视图数据。添加

self.tableView.reloadData()

之后

self.textArray.addObject(responseString as! String)

我建议将textArray声明为非可选的Swift数组

var textArray = [String]()

然后所有出现的addObject都必须替换为append 并更改cellForRowAtIndexPath中的行以获取索引路径的值

cell.textLabel?.text = self.textArray[indexPath.row] // no type casting needed