Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/clojure/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 用Alamofire响应填充表视图_Ios_Swift_Alamofire - Fatal编程技术网

Ios 用Alamofire响应填充表视图

Ios 用Alamofire响应填充表视图,ios,swift,alamofire,Ios,Swift,Alamofire,我试图用Alamofire得到的响应填充UITableView。JSON的url是。我只需要这个JSON中的response.result.value[“results”]字典数组。 我得到它没有问题,但当我试图在Alamofire外部打印此数据时,请求为空,并且我的单元格无法填充此数据,因为单元格数为0。 我在主线程中尝试了tableView.reloadData(),正如这里所说的,但没有得到积极的结果。你认为我做错了什么?我委托了表视图,并更新了框架,一切都应该正常 下面是一段代码: fu

我试图用Alamofire得到的响应填充UITableView。JSON的url是。我只需要这个JSON中的response.result.value[“results”]字典数组。 我得到它没有问题,但当我试图在Alamofire外部打印此数据时,请求为空,并且我的单元格无法填充此数据,因为单元格数为0。 我在主线程中尝试了tableView.reloadData(),正如这里所说的,但没有得到积极的结果。你认为我做错了什么?我委托了表视图,并更新了框架,一切都应该正常

下面是一段代码:

func retrieveRecentEntries() {
    let url = "https://api.themoviedb.org/3/movie/now_playing?api_key=a07e22bc18f5cb106bfe4cc1f83ad8ed"

    Alamofire.request(.GET, url, parameters: [:], encoding: .JSON, headers: [:]).responseJSON { (response) in
        self.entries = (response.result.value!["results"] as? [NSDictionary])!

        dispatch_async(dispatch_get_main_queue()) {
            print("OO")
            print("Entries1: \(self.entries)")//giving JSON


            self.tableView.reloadData()
        }
    }

    print("Entries2: \(self.entries)")//empty

}
UITableView委托方法:

   func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    //Sort entries by date and return amount of entries for each date section
    return entries.count ?? 0
}

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

    //Populate each indexPath.row with one entry
    let entryDict = entries[indexPath.row]

    let dateString = entryDict["release_date"] as! String
    formatter.dateFormat = "yyyy-MM-dd"

    let dateDate = formatter.dateFromString(dateString)
    formatter.dateFormat = "MMMM d, yyyy"

    let dateStr = formatter.stringFromDate(dateDate!)

    //Store entry details to show them as labels
    let projectName = entryDict["title"] as! String
    let description = entryDict["overview"] as! String
    let task = entryDict["original_title"] as! String
    let hours = entryDict["vote_average"] as! Double

    //Show cell labels
    cell.projectNameLabel.text = projectName
    cell.dateLabel.text = dateStr
    cell.taskLabel.text = task
    cell.descriptionLabel.text = description
    cell.hoursLabel.text = String(format: "%.2f", hours)

    print("HERE")//this isn't printed
    return cell
}

当您打印Entries2时,数组是空的,因为该代码在发送alamofire请求后立即执行,因此尚未收到响应

可能发生的情况是,当调用reloadData()时,条目不会更新。试着移动

self.entries = (response.result.value!["results"] as? [NSDictionary])!

发送到dispatch\u async块内部。

Jack确认您的行
打印(“Entries2:\(self.entries)”
为空,因为它是在发送
Alamofire
请求后立即执行的。
self.entries
的赋值放在
dispatch\u async
中不会有什么区别,但值得一试

您提到您已正确设置了
代理
。您是否也设置了
数据源

您在哪里调用
retrieverecentries()


关于它们的价值的一些建议。 虽然使用
NSDictionary
会起作用,但它来自
Objective-C.
而不是
[NSDictionary]
我建议使用更“快速”的方法并使用
[String:AnyObject]。

也有很多情况下,你是隐式的。如果您知道这些值永远不会为
nil,这没关系。
但是由于您正在解包的值来自服务器,因此最好处理这些值为
nil的可能性。
因为如果它们是,并且您隐式地解包它们,您的应用程序将崩溃。
我建议更新您的代码以使其更安全,并按如下操作

func retrieveRecentEntries() {
    let url = "https://api.themoviedb.org/3/movie/now_playing?api_key=a07e22bc18f5cb106bfe4cc1f83ad8ed"

    Alamofire.request(.GET, url, parameters: [:], encoding: .JSON, headers: [:]).responseJSON { (response) in

        guard let validResponse = response.result.value as? [String : AnyObject], validEntries = validResponse["results"] as? [String: AnyObject] else {
            return
        }

        // Now you can assign validEntries to self.entries because you know it is not nil
        self.entries = validEntries

        dispatch_async(dispatch_get_main_queue()) {
            print("OO")
            print("Entries1: \(self.entries)")//giving JSON
            self.tableView.reloadData()
        }
    }
}

我还将更新
cellForRowatingIndexPath
中隐式展开
entryDict
中的值的所有位置。只要这些值中的任何一个为零,你的应用程序就会崩溃。如果你还不熟悉它,我会问斯威夫特的
guard

这个问题都是关于编码的。我将参数编码为.JSON,这对于.GET函数是不必要的。应该是

Alamofire.request(.GET, url, parameters: [:], encoding: .URL, headers: [:]).responseJSON { (response) in


默认设置为使用URL编码。代码是正确的,是的,我使用了
guard
安全地打开接收到的数据

顺便说一句,在Alamofire 3(Swift 2.3)中,
response.result.value
在出现故障时为零,因此您不能再使用它:

guard let validResponse = response.result.value as? [String : AnyObject], validEntries = validResponse["results"] as? [String: AnyObject] else {
    return
}
无论响应是成功还是失败,您都需要解析数据,因为数据总是返回的:

guard let data = response.data,
                    let json = try? NSJSONSerialization.JSONObjectWithData(data, options: []),
                    let responseJSON = json as? [String:AnyObject] else {
    return 
}

嘿,尽管它没有解决我的问题,但感谢
guard
,如果。。。否则…在这里。不客气!我很高兴你能解决你的问题。
guard let data = response.data,
                    let json = try? NSJSONSerialization.JSONObjectWithData(data, options: []),
                    let responseJSON = json as? [String:AnyObject] else {
    return 
}