1

I have such array in from api:

[{
    data = "";
    datetime = "23.07.2020 12:09";
    id = 340593;
    status = "My current task is";
},...]

I have created such struct:

struct RemarksModel {
    let id:Int
    let status,datetime:String
    let data:String?
}

And here I make request:

AF.request(URLRequest(url:Pathes.init(endpoint: "notepad/\(noteModel?.id ?? 0)/documentation").resourseUrl),
                   interceptor: CallInterceptor.init(method:HTTPMethod.get)).responseJSON(completionHandler: { (response) in
                    print(response.description)
                    switch response.result{
                    case .success(let array):
                        let remarksData = array as? [RemarksModel]
                        
                        let json = response.data as? [RemarksModel]
                        
                        
                        print(json?.count)
                        
                        
//                        if remarksData?.count ?? 1 > 0{
//                            self.remarksArray += remarksData!
//                            self.tableView.reloadData()
//                        }
                        
                        
                    case .failure(let error):
                        print(error.localizedDescription)
                        
                    }
                    
                   })

the problem is that I can't convert this array to array of my model objects. when I try to add all received data to array my app crashes because my array is nil, despite of json in logs. Maybe I have to use another way of converting received json array to objects array?

0

2 Answers 2

4

You can use directly .responseDecodable function instead of .responseData or .responseJSON after confirming RemarksModel to Codable (or just Decodable) protocol

.responseDecodable(of: [RemarksModel].self, queue: .main, decoder: JSONDecoder()) { (response) in
    switch response.result {
    case let .success(data):
        // success
        print(data)
    case let .failure(error):
        // error
        print(error.localizedDescription)
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

You can add Codable protocol to RemarksModel and use .responseData instead of .responseJSON

.responseData { response in
    switch response.result {
    case let .success(data):
        do {
            let result = try JSONDecoder().decode([RemarksModel].self, from: data)
            // success
        } catch {
            print("decoding error:\n\(error)")
            // error
        }
    case let .failure(error):
        // error
    }
}

Comments

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.