How to populate my tableview with a mutablearray from json

前端 未结 2 2027
野趣味
野趣味 2021-01-27 10:49

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.<

2条回答
  •  天命终不由人
    2021-01-27 11:17

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

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

提交回复
热议问题