1

I'm still beginner in iOS development. I'm using Swift 3, Alamofire 4 and SwiftyJson for my project. I try to fetch the data from JSON. JSON return in single array. Here is the return :

JSON :

[{
    "id": "1",
    "post_title": "Event_1",
    "post_content": "Taylor Swift",
    "start_date": "2016-11-23",
    "end_date": "2016-11-23",
    "post_date": "2016-11-18"
}, {
    "id": "2",
    "post_title": "Event_2",
    "post_content": "Nickelback",
    "start_date": "2016-11-15",
    "end_date": "2016-11-16",
    "post_date": "2016-11-15"
}, {
    "id": "3",
    "post_title": "Event_3",
    "post_content": "Nirvana",
    "start_date": "10.00pm on 22-02-2012",
    "end_date": "6.00am on 23-02-2012",
    "post_date": "2016-07-10"
}]

Swift :

var newsArray : [[String:Any]] = []

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


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomTableViewCell

    let currentNews = newsArray[indexPath.row]
    if let post_content = currentNews["post_content"] {
        cell.lbl_content.text = post_content as? String
    }

    return cell
}    


func getJSON(){

    Alamofire.request(BASE_URL).responseJSON {
        response in

        switch response.result {
        case .success(let value):
            let json = JSON(value)
            print(json)

            if let tempArray = json as? [[String: Any]] {
                self.newsArray = tempArray
                self.tableView.reloadData()
            }

        case .failure(let error):
            print(error)
        }
    }
}

Issue :

Looks like tempArray don't hold any value.

I try to implement the value in tableViewCell.

Any help is appreciated and many thanks.

2
  • Print the tempArray you will get idea whether array is empty or not Commented Dec 22, 2016 at 5:20
  • yes, and its empty Commented Dec 22, 2016 at 5:32

6 Answers 6

1

You can try this code.

Alamofire.request(BASE_URL).responseJSON {
    response in

    switch response.result {
    case .success(let value):
        //to get JSON return value
        if let result = response.result.value {
            let JSON = result as! [[String: Any]]
            //then use guard to get the value your want

        }

case .failure(let error):
    print(error)
}

}

Sign up to request clarification or add additional context in comments.

8 Comments

Why its return all the value in jsonArray instead of jsonObject ?
And 1 more thing, why you are not using (let value) ?
"Why its return all the value in jsonArray instead of jsonObject ? " - I dont know either, it depends on your server implementation, I read your json which doesnt have a key in the root level, so i determine that is a jsonArray.
"And 1 more thing, why you are not using (let value) ?" - You mean why I use guard in stead of let? guard is a swift syntax, please read this ericcerney.com/swift-guard-statement
Correct, the json dont have a key at root level. What is the difference between response.result.value and value ? Looks like you're getting the value from the parameter.
|
0

Try this

if let tempArray = json as? [[String: Any]] {
                self.newsArray = tempArray
                self.tableView.reloadData()
            }

Use json only don't json[]

2 Comments

what is the value of print(json)?
same like return in JSON at the question.
0

Please try Below

if let tempArray = json as? [[String: Any]] {
                self.newsArray = tempArray.mutableCopy()
                self.tableView.reloadData()
            }

1 Comment

It error. Value of type [[String:Any]] has no member 'mutableCopy'
0

Try change json[] as? [[String: Any]] to json.array

2 Comments

It error : Initializer for conditional binding must have Optional type, not '[JSON]'
then change arrayValue to array only, its just for checking nil
0
var newsArray : [[String:Any]] = []

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


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomTableViewCell

    let currentNews = newsArray[indexPath.row]
    if let post_content = currentNews["post_content"] {
        cell.lbl_content.text = post_content as? String
    }

    return cell
}    
    func getJSON(){

    Alamofire.request(BASE_URL).responseJSON {
        response in

        switch response.result {
        case .success(let value):
            let json = JSON(value)
            print(json)

            if let tempArray = json as? NSArray {
                self.newsArray = tempArray
                print(tempArray)
                self.tableView.reloadData()
            }

        case .failure(let error):
            print(error)
        }
    }
    }

Try above line of code. May help you.

5 Comments

No value on tempArray
print log of print(json)?
on print(json) has value, but when it comes to print(tempArray) is null
can you paste it here?
'NSArray' is not convertible to '[[String:Any]]' so I change to to self.newsArray = tempArray as! [[String:Any]]. After that, the tempArray still no value.
0

Currently I'm not using Swift 3, Alamofire 4. I have found some solution in the below link. Please check, if you can any solution from this. Link: http://ashishkakkad.com/2015/10/how-to-use-alamofire-and-swiftyjson-with-swift/

Alamofire.request("http://api.androidhive.info/contacts/").responseJSON { (responseData) -> Void in
    if((responseData.result.value) != nil) {

         let swiftyJsonVar = JSON(responseData.result.value!)

        if let resData = swiftyJsonVar["contacts"].arrayObject {
            self.arrRes = resData as! [[String:AnyObject]]
        }
        if self.arrRes.count > 0 {
            self.tblJSON.reloadData()
        }
    }
}

2 Comments

if the contacts not exist, what I should I put ?
@Sendra please try to use this: if let resData = swiftyJsonVar.arrayObject

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.