【问题标题】:No data coming in from parsing JSON with Alamofire Swift 3 and Xcode 8 beta使用 Alamofire Swift 3 和 Xcode 8 beta 解析 JSON 没有数据
【发布时间】:2016-11-07 11:10:32
【问题描述】:

我正在尝试使用 Alamofire 从 Swift 3 中的 url 获取数据。没有数据通过单元格。我知道我在某个地方搞砸了,但我对 swift 3 还很陌生,看不到问题,代码如下:

JSON 结构。

{
        posts: 
    [
        
    {
        id: “000000”,
        url: "/content/interview",
        date: "2016-11-03 09:01:41",
        modified: "2016-11-03 09:03:47",
        title: "An interview",
        summary: 
    {
        value: "<p>Lorem ipsum is simply dummy text</p> ",
        format: "filtered_html"
        }
    ]   
}   

斯威夫特:

import UIKit
import Alamofire


class TableViewController: UITableViewController {


var titles = [String]()

var mainURL = "https://www.testapi.com"

typealias JSONstandard = [String : AnyObject]

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    callAlamo(url: mainURL)
}

func callAlamo(url : String){
    Alamofire.request(url).responseJSON(completionHandler: {
        response in

        self.parseData(JSONData: response.data!)


    })

}

func parseData(JSONData : Data) {
    do {
        var readableJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as! JSONstandard

         print(readableJSON)
        if let post = readableJSON["posts"] as? JSONstandard {
            if let posts = post["posts"] {
                for i in 0..<posts.count {
                    let post = posts[i] as! JSONstandard

                    let title = post["title"] as! String
                    titles.append(title)

                    self.tableView.reloadData()

                }
            }

        }

    }


    catch {
        print(error)
    }


}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return titles.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")

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

    return cell!
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}

上面没有将数据带入“单元格”。任何帮助,将不胜感激。

【问题讨论】:

    标签: ios json swift xcode


    【解决方案1】:

    首先,Swift 3 中的 JSON 字典是 [String:Any]

    typealias JSONstandard = [String : Any]
    

    本教程的作者应将其命名为JSONdictionary,以使其更清晰。

    posts的值是一个数组,JSON集合对象很容易识别:

    • [] 是数组
    • {} 是字典

      ...
      if let posts = readableJSON["posts"] as? [JSONstandard] {
         for post in posts { // don't use ugly C-style loops 
            let title = post["title"] as! String
            titles.append(title)
         }
         self.tableView.reloadData() // reload the table view after the loop
      }
      ...
    

    PS : 在 Swift (1-3) 中传递 .mutableContainers 非常没用。

    【讨论】:

    • 谢谢,效果很好!我想引入其他数据的原理几乎相同。
    【解决方案2】:

    添加UITableViewDataSource方法:

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1 
    }
    

    不要reloadData()太频繁:

    func parseData(JSONData : Data) {
        do {
            var readableJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as! JSONstandard
    
            print(readableJSON)
            if let post = readableJSON["posts"] as? JSONstandard {
                if let posts = post["posts"] {
                    for i in 0..<posts.count {
                        let post = posts[i] as! JSONstandard
                        let title = post["title"] as! String
                        titles.append(title)               
                    }
                    self.tableView.reloadData() // moved out of loop
                }
            }
        }
        catch {
            print(error)
        }
    }
    

    如果问题仍然存在:

    • 日志:titles.count

    【讨论】:

    • 问题依旧
    【解决方案3】:

    你的问题可能在这里

         if let posts = post["posts"] {
                    ---
                }
    

    在上一行中,您通过 readableJSON["posts"] 获得帖子。 Post 没有名为“posts”的节点。

    试试这个代码:

         if let allPost = readableJSON["posts"] {
                 var posts = allPost as! NSArray
                    for post in posts {
                        let title = post["title"] as! String
                        titles.append(title)
                        self.tableView.reloadData()
                    }
                }
    

    【讨论】:

    • 在这种情况下,请不要在 Swift 中建议 NSArray
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-20
    • 2018-11-12
    • 1970-01-01
    • 1970-01-01
    • 2016-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多