Search code examples
arraysjsonswiftalamofire

Converting response NSArray to Object array swift3


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.


Solution

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