No value associated with key CodingKeys - JSONDecoder() Error - ios

Here I have 3 files loginView(SwiftUI file) for UI purpose, LoginViewModel for handling the logic, ServiceManager for handling the Network call
Below code is in loginView(SwiftUI file)
Button("Login") {
loginVM.loginWebserviceCall()
}
Below code is in loginVM class
protocol LoginViewModelService: AnyObject {
func getLoginWebServiceCall(url: URL, params: [String: Any], completion: #escaping (Result<LoginRequest, APIError>) -> ())
}
class LoginViewModel: ObservableObject {
private weak var movieService: LoginViewModelService?
#Published var error: NSError?
init(movieService: LoginViewModelService = LoginStore.shared) {
self.movieService = movieService
}
fileprivate func loginWebserviceCall() {
let loginParams = ["username": "userEnteredUserName", "password": "userEnteredPassword", "request_token": "token"]
self.movieService!.getLoginWebServiceCall(url: "API_URL",
params: loginParams) { [weak self] (result) in
guard let self = self else { return }
switch result {
case .success(let response):
print(response)
case .failure(let error):
self.error = error as NSError
}
}
}
}
class LoginStore: LoginViewModelService {
static let shared = LoginStore()
private init() {}
func getLoginWebServiceCall(url: URL, params: [String: Any], completion: #escaping (Result<LoginRequest, APIError>) -> ()) {
ServiceManager.shared().requestWebServiceCall(requestType: .POST, url: url, params: params, completion: completion)
}
}
Below code is in ServiceManager class
class ServiceManager: NSObject {
private static var manager: ServiceManager? = nil
static func shared() -> ServiceManager {
if manager == nil {
manager = ServiceManager()
}
return manager!
}
func requestWebServiceCall<Response: Decodable>(requestType: HTTPMethod,
url: URL, params: [String: Any]? = nil,
completion: #escaping (Result<Response, APIError>) -> ()) {
var urlRequest = URLRequest.init(url: url)
if let params = params {
let postData = try? JSONSerialization.data(withJSONObject: params, options: .init(rawValue: 0))
urlRequest.httpBody = postData
}
urlRequest.httpMethod = requestType.rawValue
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
URLSession.shared.dataTask(with: urlRequest) { [weak self] (data, response, error) in
guard let self = self else { return }
guard let data = data else {
self.executeCompletionHandlerInMainThread(with: .failure(.noData), completion: completion)
return
}
do {
if let str = String(data: data, encoding: .utf8) {
print(str)
// Output: {"success":true,"expires_at":"2022-06-23 08:56:52 UTC","request_token":"6587563498567begjhgf3r5387853"}
}
let decodedResponse = try JSONDecoder().decode(Response.self, from: data)
self.executeCompletionHandlerInMainThread(with: .success(decodedResponse), completion: completion)
} catch let DecodingError.keyNotFound(key, context) {
print("Key '\(key)' not found:", context.debugDescription)
print("codingPath:", context.codingPath)
} catch {
print(error)
}
}.resume()
}
private func executeCompletionHandlerInMainThread<Response: Decodable>(with result: Result<Response, APIError>,
completion: #escaping (Result<Response, APIError>) -> ()) {
DispatchQueue.main.async {
completion(result)
}
}
}
Below is the JSON we are expecting as response
{
"success": true,
"expires_at": "2018-07-24 04:10:26 UTC",
"request_token": "1531f1a558c8357ce8990cf887ff196e8f5402ec"
}
But once I get response, the decoding is getting failed and it is going inside catch block(in ServiceManager class) and it print's below error.
Key 'CodingKeys(stringValue: "username", intValue: nil)' not found: No value associated with key CodingKeys(stringValue: "username", intValue: nil) ("username").
codingPath: []
It is showing username as not found. But in my API response, I don't have username at all.
But I am passing username as httpBody to this API.
What could be the reason? Why it is throwing error?

Related

Codable for API request

How would I make this same API request through codables?
In my app, this function is repeated in every view that makes API calls.
func getOrders() {
DispatchQueue.main.async {
let spinningHUD = MBProgressHUD.showAdded(to: self.view, animated: true)
spinningHUD.isUserInteractionEnabled = false
let returnAccessToken: String? = UserDefaults.standard.object(forKey: "accessToken") as? String
let access = returnAccessToken!
let headers = [
"postman-token": "dded3e97-77a5-5632-93b7-dec77d26ba99",
"Authorization": "JWT \(access)"
]
let request = NSMutableURLRequest(url: NSURL(string: "https://somelink.com")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error!)
} else {
if let dataNew = data, let responseString = String(data: dataNew, encoding: .utf8) {
print("----- Orders -----")
print(responseString)
print("----------")
let dict = self.convertToDictionary(text: responseString)
print(dict?["results"] as Any)
guard let results = dict?["results"] as? NSArray else { return }
self.responseArray = (results) as! [HomeVCDataSource.JSONDictionary]
DispatchQueue.main.async {
spinningHUD.hide(animated: true)
self.tableView.reloadData()
}
}
}
})
dataTask.resume()
}
}
I would suggest to do the following
Create Base Service as below
import UIKit
import Foundation
enum MethodType: String {
case get = "GET"
case post = "POST"
case put = "PUT"
case patch = "PATCH"
case delete = "DELETE"
}
class BaseService {
var session: URLSession!
// MARK: Rebuilt Methods
func FireGenericRequest<ResponseModel: Codable>(url: String, methodType: MethodType, headers: [String: String]?, completion: #escaping ((ResponseModel?) -> Void)) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
// Request Preparation
guard let serviceUrl = URL(string: url) else {
print("Error Building URL Object")
return
}
var request = URLRequest(url: serviceUrl)
request.httpMethod = methodType.rawValue
// Header Preparation
if let header = headers {
for (key, value) in header {
request.setValue(value, forHTTPHeaderField: key)
}
}
// Firing the request
session = URLSession(configuration: URLSessionConfiguration.default)
session.dataTask(with: request) { (data, response, error) in
DispatchQueue.main.async {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
if let data = data {
do {
guard let object = try? JSONDecoder().decode(ResponseModel.self , from: data) else {
print("Error Decoding Response Model Object")
return
}
DispatchQueue.main.async {
completion(object)
}
}
}
}.resume()
}
private func buildGenericParameterFrom<RequestModel: Codable>(model: RequestModel?) -> [String : AnyObject]? {
var object: [String : AnyObject] = [String : AnyObject]()
do {
if let dataFromObject = try? JSONEncoder().encode(model) {
object = try JSONSerialization.jsonObject(with: dataFromObject, options: []) as! [String : AnyObject]
}
} catch (let error) {
print("\nError Encoding Parameter Model Object \n \(error.localizedDescription)\n")
}
return object
}
}
the above class you may reuse it in different scenarios adding request object to it and passing any class you would like as long as you are conforming to Coddle protocol
Create Model Conforming to Coddle protocol
class ExampleModel: Codable {
var commentId : String?
var content : String?
//if your JSON keys are different than your property name
enum CodingKeys: String, CodingKey {
case commentId = "CommentId"
case content = "Content"
}
}
Create Service to the specific model with the endpoint constants subclassing to BaseService as below
class ExampleModelService: BaseService<ExampleModel/* or [ExampleModel]*/> {
func GetExampleModelList(completion: ((ExampleModel?)/* or [ExampleModel]*/ -> Void)?) {
super.FireRequestWithURLSession(url: /* url here */, methodType: /* method type here */, headers: /* headers here */) { (responseModel) in
completion?(responseModel)
}
}
}
Usage
class MyLocationsController: UIViewController {
// MARK: Properties
// better to have in base class for the controller
var exampleModelService: ExampleModelService = ExampleModelService()
// MARK: Life Cycle Methods
override func viewDidLoad() {
super.viewDidLoad()
exampleModelService.GetExampleModelList(completion: { [weak self] (response) in
// model available here
})
}
}
Basically, you need to conform Codable protocol in your model classes, for this you need to implement 2 methods, one for code your model and another for decode your model from JSON
func encode(to encoder: Encoder) throws
required convenience init(from decoder: Decoder) throws
After that you will be able to use JSONDecoder class provided by apple to decode your JSON, and return an array (if were the case) or an object of your model class.
class ExampleModel: Codable {
var commentId : String?
var content : String?
//if your JSON keys are different than your property name
enum CodingKeys: String, CodingKey {
case commentId = "CommentId"
case content = "Content"
}
}
Then using JSONDecoder you can get your model array like this
do {
var arrayOfOrders : [ExampleModel] = try JSONDecoder().decode([ExampleModel].self, from: dataNew)
}
catch {
}
First of all, I can recommend you to use this application -quicktype- for turning json file to class or struct (codable) whatever you want. enter link description here.
After that you can create a generic function to get any kind of codable class and return that as a response.
func taskHandler<T:Codable>(type: T.Type, useCache: Bool, urlRequest: URLRequest, completion: #escaping (Result<T, Error>) -> Void) {
let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
if let error = error {
print("error : \(error)")
}
if let data = data {
do {
let dataDecoded = try JSONDecoder().decode(T.self, from: data)
completion(.success(dataDecoded))
// if says use cache, let's store response data to cache
if useCache {
if let response = response as? HTTPURLResponse {
self.storeDataToCache(urlResponse: response, urlRequest: urlRequest, data: data)
}
}
} catch let error {
completion(.failure(error))
}
} else {
completion(.failure(SomeError))
}
}
task.resume()
}

iOS - Alamofire RequestRetrier not provoked

I am trying to implement a retry mechanism and i saw that alamofire has one.
I am trying to implement a simple mechanism of retry with number of times for a request , yet something is wrong.
class OAuth2Handler: RequestAdapter, RequestRetrier {
func adapt(_ urlRequest: URLRequest) throws -> URLRequest {
return urlRequest
}
var defaultRetryCount = 4
private var requestsAndRetryCounts: [(Request, Int)] = []
private var lock = NSLock()
private func index(request: Request) -> Int? {
return requestsAndRetryCounts.index(where: { $0.0 === request })
}
func addRetryInfo(request: Request, retryCount: Int? = nil) {
lock.lock() ; defer { lock.unlock() }
guard index(request: request) == nil else { print("ERROR addRetryInfo called for already tracked request"); return }
requestsAndRetryCounts.append((request, retryCount ?? defaultRetryCount))
}
func deleteRetryInfo(request: Request) {
lock.lock() ; defer { lock.unlock() }
guard let index = index(request: request) else { print("ERROR deleteRetryInfo called for not tracked request"); return }
requestsAndRetryCounts.remove(at: index)
}
func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: #escaping RequestRetryCompletion){
lock.lock() ; defer { lock.unlock() }
guard let index = index(request: request) else { completion(false, 0); return }
let (request, retryCount) = requestsAndRetryCounts[index]
if retryCount == 0 {
completion(false, 0)
} else {
requestsAndRetryCounts[index] = (request, retryCount - 1)
completion(true, 0.5)
}
}
}
this is the class that i am trying to use this:
let sessionManager = SessionManager()
override init() {
sessionManager.adapter = RequestAdapter.self as? RequestAdapter
sessionManager.retrier = OAuth2Handler()
}
func sendRequest(url: String,meth: HTTPMethod,parameters: [String: AnyObject]?, success: #escaping (String, Data) -> Void, failure: #escaping (Error) -> Void) {
self.asyncSerialWorker.enqueueWork { (done) in
self.sessionManager.request(url, method:meth).responseJSON { (responseObject) -> Void in
if responseObject.result.isSuccess {
print("Generic succsess")
let value = responseObject.result.value
let json = JSON(value!)
guard let result = responseObject.data else {return}
success(self.parser.parseMaiden(json: json), result)
}
if responseObject.result.isFailure {
let error : Error = responseObject.result.error!
print("login failed")
failure(error)
}
done()
}
}
}
if there are any other suggestions i would love to hear them
thanks
sessionManager.adapter = RequestAdapter.self as? RequestAdapter seems very wrong. You should be setting it to an instance of your OAuth2Handler.
So the issue her was to add the request to the retry, so first i did this:
let sessionManager = SessionManager()
var retrier = OAuth2Handler()
override init() {
sessionManager.retrier = retrier
}
and in the call itself i did as follow:
func sendRequest(url: String,meth: HTTPMethod,parameters: [String: AnyObject]?, success: #escaping (String, Data) -> Void, failure: #escaping (Error) -> Void) {
let request = sessionManager.request(url, method: meth, parameters: parameters, encoding: JSONEncoding.default)
retrier.addRetryInfo(request: request)
self.asyncSerialWorker.enqueueWork { (done) in
self.sessionManager.request(url, method:meth).responseJSON { (responseObject) -> Void in
if responseObject.result.isSuccess {
print("Generic succsess")
let value = responseObject.result.value
let json = JSON(value!)
guard let result = responseObject.data else {return}
success(self.parser.parseMaiden(json: json), result)
}
if responseObject.result.isFailure {
let error : Error = responseObject.result.error!
print("login failed")
failure(error)
}
done()
}
}
}
as you can see i have add to the retry a request :
retrier.addRetryInfo(request: request)
maybe i should do a remove in success(will check and update)

Web service is called twice

I have a problem with a webService call.
The problem is that when I call the service, and debug code, and print log in console, I'm sure my webService is only called once (log print once in console), but my request is apparently sent twice to the server and I have duplicate data in the list.
I know that it's not a server-side problem because it only happens on IOS (not Android).
Here is my code for call services:
public class PersistencyManager {
public func SendPostHttpRequest(baseURL: String, parameter: [String:Any], content: String, closure:#escaping ((_ success:JSON,_ error:NSError?) -> Void)) {
let manager = Alamofire.SessionManager.default
debugPrint("Request parameter ------>",parameter)
debugPrint(" Service URL -------> \(baseURL)")
if let url = URL(string: baseURL) {
var urlRequest = URLRequest(url: url)
urlRequest.setValue("text/html; charset=utf-8", forHTTPHeaderField: "Content-Type")
urlRequest.setURLEncodedFormData(parameters: parameter)
manager.request(urlRequest).responseJSON { response in
switch response.result {
case .success(let JSON) :
debugPrint("get Json response ---> \((JSON)) ")
closure(JSON,nil)
case .failure(let error):
closure(nil,error as NSError)
debugPrint("get error ---> \((error.localizedDescription)) ")
}
}
}
}
}
class LibraryAPI {
static let shareInstance : LibraryAPI = { LibraryAPI() }()
private let persistencyManager : PersistencyManager
init() {
persistencyManager = PersistencyManager()
}
func GetPostResponse(baseURL : String,parameters:[String:Any],contentType: String,closure:#escaping ((_ success:PersistencyManager.JSON,_ error:NSError?) -> Void)) {
persistencyManager.SendPostHttpRequest(baseURL: baseURL, parameter: parameters, content: contentType, closure: { success, error in
closure(success, error)
})
}
}
class TransactionAPI: TransactionProtocol {
static let shareInstance: TransactionAPI = {TransactionAPI()}()
func AddNewManagerRequest(_ parameter: [String : Any], closure: #escaping (([String : Any]?, NSError?) -> Void)) {
let url = Constants.BaseURL + Constants.K_NEWREQPORTERAGE
LibraryAPI.shareInstance.GetPostResponse(baseURL: url, parameters: parameter, contentType: "JSON", closure: {success,error in
var response: [String:Any]?
if let json = success as? [String: Any] {
response = json
}
closure(response, error)
})
}
}
class AddNewOrderViewController: MainViewController {
private func RegisterForNewPorterageRequest() {
let time = Utilities.shareInstance.GetSystemTime()
guard let userID = UserDefaults.standard.value(forKey: "user_id") as? String else {
return
}
StartActivity(activityColor: Constants.ACTIVITY_COLOR)
let token = TokenCreator.shareInstance.CreateTokenWithUserID(userID: userID, methodName: Constants.M_NEWREQUESTPORTERAGE)
request.tok = token
request.time = time
request.user_id = userID
let jsonModel = Utilities.shareInstance.GetJsonForm(objectClass: request)
TransactionAPI.shareInstance.AddNewManagerRequest(jsonModel, closure: {[weak self] success,error in
guard let strongSelf = self else{
return
}
if error != nil {
OperationQueue.main.addOperation {
strongSelf.StopActivity()
strongSelf.CreateCustomTopField(text: Constants.serverError, color: Constants.ERROR_COLOR)
}
}
else {
if let response = success {
debugPrint("add request service call once")
if let status = response["status"] as? String {
if status == "succ" {
OperationQueue.main.addOperation {
strongSelf.presentResultAlert()
}
}else {
OperationQueue.main.addOperation {
strongSelf.StopActivity()
strongSelf.CreateCustomTopField(text: Constants.send_data_error, color: Constants.ERROR_COLOR)
}
}
}
}
}
})
}
}
After adding log to server, I made sure my request was sent twice to server.
All console log print once in console.
I don't know when I call service twice, and why my request was sent twice to the server.
I don't understand how the log be displayed once, but the service has been called twice?
Any help appreciated.
It's really confusing, but it works perfectly with this method.
i have this method in persistencyMangerClass and i using this method instead SendPostHttpRequest.What really is the difference between these two methods. :|
public func SendMultiPartRequestWith(baseUrl: String, parameters: [String : Any],closure: #escaping ((_ success:JSON,_ error:NSError? ) -> Void)){
let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 30
manager.session.configuration.timeoutIntervalForResource = 15
debugPrint(" Service URL -------> \(baseUrl)")
debugPrint("Request parameter ------>",parameters)
let headers: HTTPHeaders = [
"Content-type": "multipart/form-data"
]
manager.upload(multipartFormData: { (multipartFormData) in
for (key, value) in parameters {
if let data = value as? Data {
let fileName = (key as String) + ".jpg"
let mimType = (key as String) + "/jpg"
multipartFormData.append(data, withName: key as String, fileName: fileName, mimeType: mimType)
}
else {
if let v = value as? String {
multipartFormData.append("\(v)".data(using: String.Encoding.utf8)!, withName: key as String)
}else {
multipartFormData.append("".data(using: String.Encoding.utf8)!, withName: key as String)
}
}
}
}, usingThreshold: UInt64.init(), to: baseUrl, method: .post, headers: headers) { (result) in
switch result{
case .success(let upload, _, _):
upload.responseString { response in
if let err = response.error{
closure(nil, err as NSError)
return
}
if let JSON = response.result.value {
closure(JSON, nil)
}
}
case .failure(let error):
closure(nil, error as NSError)
}
}
}

Thread 1: break point error to send post method

I would like to send post method (to login user) but when I click on login button in run time I got this message :
my class:
typealias ServiceResponse = (JSON, NSError?) -> Void
class RestApiManager: NSObject {
static let sharedInstance = RestApiManager()
let baseURL = "***********"
func login(body: [String: AnyObject],onCompletion: #escaping (JSON) -> Void) {
let route = baseURL+"o/token/"
makeHTTPPostRequest(path: route,body: body, onCompletion: { json, err in
onCompletion(json as JSON)
})
}
func getCategories(onCompletion: #escaping (JSON) -> Void) {
let route = baseURL+"o/token/"
makeHTTPGetRequest(path: route, onCompletion: { json, err in
onCompletion(json as JSON)
})
}
func getRandomUser(onCompletion: #escaping (JSON) -> Void) {
let route = baseURL
makeHTTPGetRequest(path: route, onCompletion: { json, err in
onCompletion(json as JSON)
})
}
// MARK: Perform a GET Request
private func makeHTTPGetRequest(path: String, onCompletion: #escaping ServiceResponse) {
let request = NSMutableURLRequest(url: NSURL(string: path)! as URL)
let session = URLSession.shared
let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
if let jsonData = data {
let json:JSON = JSON(data: jsonData)
onCompletion(json, error as NSError?)
} else {
onCompletion(nil, error as NSError?)
}
})
task.resume()
}
// MARK: Perform a POST Request
private func makeHTTPPostRequest(path: String, body: [String: AnyObject], onCompletion: #escaping ServiceResponse) {
let request = NSMutableURLRequest(url: NSURL(string: path)! as URL)
// Set the method to POST
request.httpMethod = "POST"
do {
// Set the POST body for the request
let jsonBody = try JSONSerialization.data(withJSONObject: body, options: .prettyPrinted)
request.httpBody = jsonBody
let session = URLSession.shared
let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
if let jsonData = data {
let json:JSON = JSON(data: jsonData)
onCompletion(json, nil)
} else {
onCompletion(nil, error as NSError?)
}
})
task.resume()
} catch {
// Create your personal error
onCompletion(nil, nil)
}
}
}
in my login controller :
//after click on login button
let parameters = ["grant_type": "password",
"username": "test29#gmail.com",
"password": "1",
"client_id": "toS899lbMGolv8j24piz0JI38VUCi6Mvzru27iBA",
"client_secret":"lG14Tk7m2mGYLMvBndW2yFZ1NGRLNrriIPH6gw30gAnMAcFMa5xJE3wP8H 4SDHAK0ND5nKIoSLZskFQQ1knEYiaPC3i5LNutPJlusiMNiuvhUHWnbvTCjmNkuCBkGgqO"]
RestApiManager.sharedInstance.login(body: parameters as [String : AnyObject]) { (json: JSON) in
print(json)
}
Try to put it back to the main thread:
func login(body: [String: AnyObject],onCompletion:#escaping(JSON) -> Void) {
let route = baseURL+"o/token/"
makeHTTPPostRequest(path: route,body: body, onCompletion: { json, err in
DispatchQueue.main.async {
onCompletion(json as JSON)
}
})
}

Alamofire 3->4 trouble with Reponse & ResponseSerializer Swift 3.0

I'm having trouble with the ResponseSerializer I get an unresolved identifier and for Response I get an undeclared type. I've read from alamofire migration doc that Response has been changed to multiple types. So I should change Response->DataReponse but this means I can only pass one argument like:
// What I have
Response(<ListWrapper, NSError>)
// What I should change it to?
DataResponse(<ListWrapper>)
How can I still recieve the Error this way and more importantly how do I migrate the extension to alamofire 4?
My class:
class List{
var idNumber: String?
var title: String?
var posterPath: String?
var release: String?
required init(json: JSON, id: Int?)
{
self.idNumber = json[ListFields.Id.rawValue].stringValue
self.title = json[ListFields.Title.rawValue].stringValue
self.posterPath = json[ListFields.PosterPath.rawValue].stringValue
self.release = json[ListFields.Release.rawValue].stringValue
}
class func setURL_APPEND(_ url: String)
{
URL_APPEND = url
}
// MARK: Endpoints
class func endpointForList() -> String
{
return URL_APPEND
}
fileprivate class func getListAtPath(_ path: String, completionHandler: #escaping (ListWrapper?, NSError?) -> Void) {
Alamofire.request(path)
.responseListArray { response in
if let error = response.result.error
{
completionHandler(nil, error)
return
}
completionHandler(response.result.value, nil)
}
}
class func getList(_ completionHandler: #escaping (ListWrapper?, NSError?) -> Void)
{
getListAtPath(List.endpointForList(), completionHandler: completionHandler)
}
}
// Problem is here:
// for ResponseSerializer I get an unresolved identifier
// and for Response I get an undeclared type
extension Alamofire.Request {
func responseListArray(_ completionHandler: #escaping (Response<ListWrapper, NSError>) -> Void) -> Self {
let responseSerializer = ResponseSerializer<ListWrapper, NSError> { request, response, data, error in
guard error == nil else
{
return .failure(error!)
}
guard let responseData = data else {
let failureReason = "Array could not be serialized because input data was nil."
let error = Alamofire.Error.errorWithCode(.dataSerializationFailed, failureReason: failureReason)
return .failure(error)
}
let JSONResponseSerializer = Request.JSONResponseSerializer(options: .allowFragments)
let result = JSONResponseSerializer.serializeResponse(request, response, responseData, error)
switch result {
case .success(let value):
let json = SwiftyJSON3.JSON(value)
let wrapper = ListWrapper()
var allList:Array = Array<List>()
wrapper.totalCount = json["favorite_count"].intValue
// print(json)
let results = json["items"]
// print(results)
for jsonList in results
{
//print(jsonList.1)
let list = List(json: jsonList.1, id: Int(jsonList.0) )
if (list.posterPath == "")
{
continue
}
else
{
//print(movies.posterPath)
allList.append(list)
}
}
wrapper.results = allList
return .success(wrapper)
case .failure(let error):
return .failure(error)
}
}
return response(responseSerializer: responseSerializer,completionHandler: completionHandler)
}
}
Bro try below code see:
func responseListArray(_ completionHandler: #escaping (Response<ListWrapper>) -> Void) -> Self {
let responseSerializer = ResponseSerializer<ListWrapper> { request, response, data, error in
guard error == nil else
{
return .failure(error!)
}
guard let responseData = data else {
return .failure(AFError.responseSerializationFailed(reason: .inputDataNil))
}
let JSONResponseSerializer = Request.JSONResponseSerializer(options: .allowFragments)
let result = JSONResponseSerializer.serializeResponse(request, response, responseData, error)
switch result {
case .success(let value):
let json = SwiftyJSON3.JSON(value)
let wrapper = ListWrapper()
var allList:Array = Array<List>()
wrapper.totalCount = json["favorite_count"].intValue
// print(json)
let results = json["items"]
// print(results)
for jsonList in results
{
//print(jsonList.1)
let list = List(json: jsonList.1, id: Int(jsonList.0) )
if (list.posterPath == "")
{
continue
}
else
{
//print(movies.posterPath)
allList.append(list)
}
}
wrapper.results = allList
return .success(wrapper)
case .failure(let error):
return .failure(error)
}
}
return response(responseSerializer: responseSerializer,completionHandler: completionHandler)
}

Resources