簡體   English   中英

如何使用JSON中的mutablearray填充我的tableview

[英]How to populate my tableview with a mutablearray from json

所以我要從json格式的網址中獲取數據。 我試圖在表視圖中顯示數據,但是即使感覺很簡單,我也無法弄清楚該如何做。

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()來獲取數據,然后將其存儲在一個空數組中,但是我的腦海空白怎么做。

我無法聲明NSarray的變量並將其數據直接存儲為變量,然后填充tableview。 不過,我希望這能解釋我要達到的目標。

好吧,首先更改函數以返回您的公司數組:

func getJSON() -> NSMutableArray {

}

在for循環結束時返回company數組

for company in companies {

 }

填充數組后,在此塊內返回數組:

dispatch_async(dispatch_get_main_queue(), { 

    return companyArray

})

task.resume()返回數組:

return companyArray

您想從任何地方調用此類並獲取數組:

獲取課程參考

Let companyModal = CompanyModel()

在任何具有表格視圖和類的地方(假設在viewDidLoad ,您都應該首先具有NSMutableArray

var arraySource = NSMutableArray()

viewDidLoad

arraySource = companyModal.getJSON()

並在tableView中顯示數據:

Mytableview.reloadData()

您不能在異步網絡請求的結束內使用return ,而必須使用回調。

您需要從請求中獲得一個NSMutableArray,因此首先,讓我們對此進行回調:

completion: (array: NSMutableArray)->()

我們將此回調添加到方法簽名中:

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

然后在數組可用的位置 ,我們放置以下完成處理程序:

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()
    }
}

現在要從網絡中獲取數組,我們使用像這樣的結尾閉包:

getJSON { (array) in
    print(array)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM