如何使用json中的mutablearray填充我的tableview [英] How to populate my tableview with a mutablearray from json

查看:118
本文介绍了如何使用json中的mutablearray填充我的tableview的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我从一个json格式的url中获取数据。我正试图在我的tableview中显示数据但是,即使感觉很简单,我也无法弄清楚如何做到这一点。

So I'm fetching data from a url which is in a json format. I'm trying to display the data in my tableview but, even though it feels simple, I can't figure out how to do it.

class CompanyModel {

func getJSON() {

    let companyArray: NSMutableArray = NSMutableArray()

    let requestURL: NSURL = NSURL(string: "http://localhost/Companies/JSON.php")!
    let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithRequest(urlRequest) {
        (data, response, error) -> Void in

        let httpResponse = response as! NSHTTPURLResponse
        let statusCode = httpResponse.statusCode

        if (statusCode == 200) {
            print("Everyone is fine, file downloaded successfully.")

            do{

                let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)



                if let companies = json["companies"] as? [[String: AnyObject]] {

                    for company in companies {

                        if let name = company["name"] as? String,
                            let phoneNumber = company["phone_number"] as? String,
                            let website = company["website"] as? String,
                            let email = company["email"] as? String,
                            let address = company["address"] as? String

                        {
                        let company = CompanyModel()

                            company.name = name
                            company.phoneNumber = phoneNumber
                            company.website = website
                            company.email = email
                            company.address = address
                        }
                        companyArray.addObject(company)
                        print(companyArray)
                    }
                }
            } catch {
                print("Error with Json: \(error)")
            }

        }
        print(companyArray) <- array is populated
    }
    print(companyArray) <- array is empty
    task.resume()
}
}

我知道我之前已经完成了......我在猜测 viewDidLoad()我打电话给 CompanyModel()。getJSON()这将获取数据,然后将其存储在一个空数组中,但我的想法一无所知。

I know i've done it before....I'm guessing in viewDidLoad() I'd call CompanyModel().getJSON() which would fetch the data, then store it in an empty array but my mind feels blank on how to do it.

我无法声明NSarray的变量并直接将变量的数据存储给我,然后填充tableview。不过,我希望这能解释我想要实现的目标。

I can't declare a variable of NSarray and store the data of it the variable directly for me to then populate the tableview. Nevertheless, I hope this explains what I'm trying to acheive.

推荐答案

你不能使用在异步网络请求的关闭中返回,你必须改为使用回调。

You can't use return within the closure of an asynchronous network request, you have to use a callback instead.

你需要一个来自请求的NSMutableArray,所以首先,让我们回复一下:

You need a NSMutableArray from the request, so first, let's make a callback for this:

completion: (array: NSMutableArray)->()

我们将此回调添加到方法签名中:

We add this callback to the method signature:

func getJSON(completion: (array: NSMutableArray)->())

然后在数组可用的位置,我们放置此完成处理程序:

And then at the location where the array will be available, we place this completion handler:

class CompanyModel {
    func getJSON(completion: (array: NSMutableArray)->()) {
        let companyArray: NSMutableArray = NSMutableArray()
        let requestURL: NSURL = NSURL(string: "http://localhost/Companies/JSON.php")!
        let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithRequest(urlRequest) {
            (data, response, error) -> Void in
            let httpResponse = response as! NSHTTPURLResponse
            let statusCode = httpResponse.statusCode
            if (statusCode == 200) {
                do{
                    let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
                    if let companies = json["companies"] as? [[String: AnyObject]] {
                        for company in companies {
                            if let name = company["name"] as? String,
                                let phoneNumber = company["phone_number"] as? String,
                                let website = company["website"] as? String,
                                let email = company["email"] as? String,
                                let address = company["address"] as? String {
                                let company = CompanyModel()
                                company.name = name
                                company.phoneNumber = phoneNumber
                                company.website = website
                                company.email = email
                                company.address = address
                                companyArray.addObject(company)
                            }
                        }

                        // CALLBACK HERE
                        completion(array: companyArray)

                    }
                } catch {
                    print("Error with Json: \(error)")
                }
            }
        }
        task.resume()
    }
}

现在获取网络中的数组我们使用这样的尾随闭包:

Now to get the array from the network we use a trailing closure like this:

getJSON { (array) in
    print(array)
}

这篇关于如何使用json中的mutablearray填充我的tableview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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