使用 Swift 3 和 Alamofire 从 JSON url 的应用程序中没有显示任何内容 [英] Nothing showing in app from JSON url with Swift 3 and Alamofire

查看:22
本文介绍了使用 Swift 3 和 Alamofire 从 JSON url 的应用程序中没有显示任何内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 Swift 3 和 Alamofire 的应用程序.数据连接到两个 cell?.viewWithTag(2)cell?.viewWithTag(1) 这是一个图像(来自 url)和文本.所以当我运行项目时,我的应用程序中没有显示任何内容.我已经使用 print(readableJSON) 测试了 JSON,并且 JSON 正在打印到控制台中.所以我真的有点困惑.我的 swift 看起来像这样:

I have an app that is using Swift 3 and Alamofire. The data is connected to two cell?.viewWithTag(2) and cell?.viewWithTag(1) which is an image (from url) and text. So when I run the project nothing is showing in my App. I have tested the JSON with print(readableJSON) and the JSON is getting printed into the console. So I am a little confused really. My swift looks like this:

SWIFT

import UIKit
import Alamofire

struct postinput {
    let mainImage : UIImage!
    let name : String!

}


class TableViewController: UITableViewController {

    var postsinput = [postinput]()

    var mainURL = "https://www.example.api.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 posts = readableJSON["posts"] as? [JSONstandard] {
                for post in posts { 
                    let title = post["title"] as! String
                    print(title)

                    if let imageUrl = post["image"] as? JSONstandard {
                        let mainImageURL = URL(string: imageUrl["url"] as! String)
                        let mainImageData = NSData(contentsOf: mainImageURL!)


                        let mainImage = UIImage(data: mainImageData as! Data)
                        postsinput.append(postinput.init(mainImage: mainImage, name: title))
                        self.tableView.reloadData()

                    }


                }

            }

        }


        catch {
            print(error)
        }


    }




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

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

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

        let mainImageView = cell?.viewWithTag(2) as! UIImageView

        mainImageView.image = postsinput[indexPath.row].mainImage

        let mainLabel = cell?.viewWithTag(1) as! UILabel

        mainLabel.text = postsinput[indexPath.row].name


        return cell!
    }

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


}

JSON

{
    "posts" : [{
        "id": "000000",
        "url": "/content/interview2",
        "date": "2016-11-03 09:01:41",
        "modified": "2016-11-03 09:03:47",
        "title": "An interview",
        "image": "https://www.example.com/sites/default/files/oregood.jpeg",
        "summary": {
            "value": "<p>Latin text here</p>",
            "format": "filtered_html"
        }
    }]
}

推荐答案

From your JSON response image key contains String not Dictionary 也是你不需要每次都在循环内重新加载您的 tableView for 循环外,所以尝试这样.

From your JSON response image key contains String not Dictionary also you need to reload your tableView outside for loop not every time inside the loop, so try like this.

if let posts = readableJSON["posts"] as? [JSONstandard] {
    for post in posts {
        let title = post["title"] as! String            
        if let imageUrl = post["image"] as? String {
            let mainImageURL = URL(string: imageUrl as! String)
            let mainImageData = NSData(contentsOf: mainImageURL!)
            let mainImage = UIImage(data: mainImageData as! Data)
            postsinput.append(postinput.init(mainImage: mainImage, name: title))                
        }
    }
    DispatchQueue.main.async {
        self.tableView.reloadData()
    }
}

建议:不要在主线程击球手上使用 NSData(contentsOf:) 下载图像,而是使用像 SDWebImages 这样的库,或者您可以创建自己的自己的异步图片下载器.

Suggestion : Instead of downloading image using NSData(contentsOf:) on main thread batter to use library like SDWebImages or you can create your own async image downloader.

这篇关于使用 Swift 3 和 Alamofire 从 JSON url 的应用程序中没有显示任何内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆