0

Hi i am able to get response from server for array list. But i dont know how to parse that response in object array [Feed] and send it on on completion handler. My Code is as follows:

class FeedsService {

    private var feedsEndPoint: String = "https://jsonplaceholder.typicode.com/posts"

    public func getFeeds(completion: ([Feed]) -> Void) {
        Alamofire.request(feedsEndPoint, method: .get)
            .validate(statusCode: 200..<300)
            .validate(contentType: ["application/json"])
            .responseJSON{ response in
                print("Response \(response.result.value)")

        }
    }
}

Feed Model is as follows:

class Feed {
    private var title: String
    private var body: String

    init(title:String, body: String) {
        self.title = title
        self.body = body
    }

    public func getTitle() -> String {
        return self.title
    }

    public func getBody() -> String {
        return self.body;
    }
}

I want to parse this as Feed Array and sent it on completion callback. I am using Alamofire rest library for loading data from rest server.

2
  • Nobody can answer your question without seeing what your dataset looks like. -1 Commented Dec 12, 2016 at 14:08
  • 1
    i wonder y u downvoted Please check data set here jsonplaceholder.typicode.com/posts O.o Commented Dec 12, 2016 at 14:26

1 Answer 1

1

You can try this:

    class FeedsService {

    private var feedsEndPoint: String = "https://jsonplaceholder.typicode.com/posts"

    public func getFeeds(completion: @escaping ([Feed]) -> Void) {
        Alamofire.request(feedsEndPoint, method: .get)
            .validate(statusCode: 200..<300)
            .validate(contentType: ["application/json"])
            .responseJSON{ response in
                print("Response \(response.result.value)")
                var feeds = [Feed]()
                if let jsonArray = response.result.value as? [[String: Any]] {
                    for json in jsonArray {
                        if let feed = Feed(json: json) {
                            feeds.append(feed)
                        }
                    }
                    completion(feeds)
                } else {
                    // handle error
                }
        }
    }
}

Also, update your Feed class:

class Feed {
    private var title: String
    private var body: String

    init(title:String, body: String) {
        self.title = title
        self.body = body
    }

    init?(json: [String: Any]) {
        guard let title = json["title"] as? String,
            let body = json["body"] as? String else {
                return nil
        }
        self.title = title
        self.body = body
    }

    public func getTitle() -> String {
        return self.title
    }

    public func getBody() -> String {
        return self.body;
    }
}

Just change "title" and "body" to whatever is the appropriate key in your json response.

As El Tomato is pointing out that Feed init is not working, this is a test code that can be tried out in a playground:

let testFeedJson = ["title": "Test Title", "body" : "Test Body"]
if let testFeed = Feed(json: testFeedJson) {
    print(testFeed.getTitle())
    print(testFeed.getBody())
}
Sign up to request clarification or add additional context in comments.

5 Comments

You are not intializing Feed to create an instance of feeds.
Sorry, I don't get it. Feed instance is created here: if let feed = Feed(json: json) {feeds.append(feed)}
Check the updated answer (at the bottom) and please try the Feed class in the playground. Please, tell me what is wrong there before giving me -1.
Yes checking your answer thanks for response, can u clarify this code let feeds = response.result.value as! [Feed] print("Feeds count : (feeds.count)") It does compile and counts return correct
I am not sure that let feeds = response.result.value as! [Feed] will create an array of Feed objects. Server is returning an array of [String:Any] objects. You have to iterate through that array and create Feed object from [String:Any] object. Can you try the code I suggested in my answer?

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.