Giter Club home page Giter Club logo

alamofirejsontoobjects's People

Contributors

davidwu226 avatar evermeer avatar tamir7 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

alamofirejsontoobjects's Issues

[Question] What happens if the response is not of expected type?

I'm using version 2.1 of Swift3 branch with Alamofire 4.0, with do following code:

Alamofire.request(Constants.base_uri + "api/register", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers)
        .responseObject { (response: DataResponse<RegisterResponse>) in
        if let result = response.result.value {
           print(response.response?.statusCode)
           print(response.response?.description)
           print(response.debugDescription)
           print(result.username)
        }
        else if let error = response.result.error {
            print(error.localizedDescription)
        }

My server is Laravel and no errors occur, I'm all fine. But if any validation error occurs, response will be an something like:

{
  "username": [
    "some error.",
    "another error."
  ],
  "email": [
    "some error."
  ]
}

, and that's when I get the following exception:

 -[__NSSingleObjectArrayI length]: unrecognized selector sent to instance 0x618000011510
 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSSingleObjectArrayI length]: unrecognized selector sent to instance 0x618000011510'

My RegisterResponse class is the following:

class RegisterResponse: EVObject {
    public var username: String?
    var firstname: String?
    var lastname: String?
    var mobile: String?
    var email: String?
    var updated_at: String?
    var created_at: String?
    var id: Int?
}

Issue with int key named count

Hi, im having an issue with an property named count:

---> setValue 'MetaModel {
   hash = 1667855328
   key = status, value = SUCCESS
   key = count, value = 0
}
' for key '_meta' should be handled.
class MetaModel : EVObject {
    var status: String?
    var count: Int?

    override func setValue(value: AnyObject!, forUndefinedKey key: String) {
        switch key {
        case "count":
             count = 0 // just to test, without this code is always <null>
        default:
            NSLog("---> setValue for key '\(key)' should be handled.")
        }
    }

}

If i wont handle 'count' case it always shows:

---> setValue 'MetaModel {
   hash = 1676107560
   key = status, value = SUCCESS
   key = count, value = <null>
}

Is there any issue with the key 'code' ? (is it a keyword maybe) ? Thanks in advance.

.description outputs a boolean as a number (0 or 1)

Hi there,

I'm trying to map some simple JSON:

{"id":121,"active":false}

In the following model:

class MyObject : EVObject {

    var id : Int = 0
    var active: Bool = false
...

However the boolean maps to an int, I get the following output of the mapping:

MyObject {
   id = 121
   active = 0
}

Am I missing something?

Could not create an instance for type "Forecast"

Hi.
I used your library my old project and it was very helpful for me. Thank you.

Now I'm using your library again. But I faced a problem this time. I suspected my model class and because of that I used your example for the test.

I got this error "Could not create an instance for type Forecast".

now my versions :
xcode : 7.3.1
pod version : 1.0.1
imported some pods :
Alamofire (3.5.0)
AlamofireJsonToObjects (1.6.0)
EVReflection (2.46.0)

I think this is about versions but I dont know.
Do you have any idea about that?
Thanks.

Error parsing array swift 3

Hi @evermeer , i was used to use AlamofireJsonToObjects with swift 2.3 and now im trying to update my apps to swift 3.0. Im have some problems with arrays:

My ws basically has a JsonMessage object which can have an array of objects or a single object (JsonMessageSingle and JsonMessageList). I was able to parse the JsonMessageSingle normally using Generics, but it stuck on this screen when trying to parse the json below (im not sure, but i guessed it cant parse the generic array):

May you help me please? Thanks in advance.

image

{
  "status": "SUCCESS",
  "message": null,
  "data": "2017-01-30 13:56:45",
  "objects": [
    {
      "idPacote": "12",
      "alias": "higienizacao-completa",
      "nome": "Higienização completa",
      "desconto": "10",
      "descricao": "<p>A higieniza&ccedil;&atilde;o completa &eacute; ideal para aquele momento em que voc&ecirc; precisa dar um bom trato no seu ve&iacute;culo. Nesse servi&ccedil;o realizamos a limpeza &nbsp;interna e externa completa, aplicamos os melhores produtos para cada &aacute;rea do seu carro, odorizamos o ambiente interno e realizamos a higieniza&ccedil;&atilde;o no teto, tapetes, estofados e ar-condicionado.</p>",
      "status": "1",
      "vantagens": "<p>Comodidade e seguran&ccedil;a pois vamos&nbsp;at&eacute; o seu ve&iacute;culo;</p>\r\n<p>Ecologicamente correto, pois economiza &aacute;gua e n&atilde;o utiliza produtos qu&iacute;micos;</p>\r\n<p>Extermina &aacute;caros e bact&eacute;rias, evitando ataques al&eacute;rgicos;</p>\r\n<p>Desodoriza por completo o ve&iacute;culo e n&atilde;o somente disfar&ccedil;a com outros produtos;</p>\r\n<p>Conserva a lataria do ve&iacute;culo;</p>\r\n<p>N&atilde;o desgasta o estofado pois n&atilde;o existe a necessidade de esfreg&aacute;-lo;</p>\r\n<p>A limpeza dura duas vezes &nbsp;mais que uma limpeza convencional;</p>\r\n<p>Voc&ecirc; ganha uma economia de tempo e dinheiro;</p>\r\n<p>Carro com aspecto de carro novo e limp&iacute;ssimo;</p>\r\n<p>Higieniza&ccedil;&atilde;o interna e externa completa, incluindo o teto do autom&oacute;vel;</p>\r\n<p>Ar condicionado renovado;</p>\r\n<p>Bancos hidratados e sem risco de ressecamento;</p>\r\n<p>Pneus com brilho, hidrata&ccedil;&atilde;o e prote&ccedil;&atilde;o.</p>",
      "ordem": "2",
      "publico": "<p>Voc&ecirc; tem um evento nos pr&oacute;ximos dias ou est&aacute; precisando impressionar algu&eacute;m? Esse servi&ccedil;o &eacute; ideal para voc&ecirc;. A gente sabe que melhor que assistir ao casamento do seu amigo de inf&acirc;ncia &eacute; fazer as pessoas assistirem o seu carro chegando bonit&atilde;o na festa. Se voc&ecirc; preza pelo cuidado com o seu ve&iacute;culo e quer que ele tenha sempre um aspecto de carro novo, &eacute; a hora ideal para agendar uma higieniza&ccedil;&atilde;o completa.</p>",
      "idAlbum": "4"
    }
  ]
}
class JsonMessageList<T> : JsonMessage<T>, EVGenericsKVC where T:MyModel {
    var objects : [T]?
    
    required
    init() {
        super.init()
    }

    func getGenericType() -> NSObject {
        return T() as! NSObject
    }
    
    
    func setGenericValue(_ value: AnyObject!, forUndefinedKey key: String) {
        switch key {
        case "objects":
            objects = value as! [T]
            break
        default:
            print("---> setValue '\(value)' for key '\(key)' should be handled.")
        }
    }

}



class JsonMessage<T> : EVObject where T:MyModel {
    
    var message : String?
    var data : String?
    var status : String?
    
    required
    init() {
        super.init()
    }
}



 func makeRequest(method: HTTPMethod, URL: String, callListener: CallListListener<T>, headers : [String:String]? = nil) {
        callListener.onPreRequestInternal()
        //    print("making request " + getMethod(method) + " to " + URL)
        
        Alamofire.request(URL, method: method, headers: headers ?? getHeaders())
            .responseJSON { response in
                // do whatever you want here
                switch response.result {
                case .failure(let error):
                    print(error)
                case .success(let responseObject):
                    print(responseObject)
                }
            }

            .responseObject {
                (response: DataResponse<JsonMessageList<T>>) in
                
                if let result = response.result.value {
                    callListener.afterRequest(response: result)
                } else {
                 //   print("Request failed with error: \(response.response.er)")
                }
                
        }

Compilation errors in Xcode 7.0 (7A220)

Hi,

still the same error when I try to use AlamofireJsonToObjects 1.2.0 with Alamofire 3.0.0-beta.3 (now public enum Result< Value, Error: ErrorType> in Result.swift) from Cocoapods

alamofire

Regards.

Build error happened within carthage

Thank you for your works,

I tried to get and build your project within carthage, but error happened.
It seems that there is no Info.plist in master branch or so. Please fix it.


The following build commands failed:
ProcessInfoPlistFile /Users/XXX/Library/Developer/Xcode/DerivedData/AlamofireJsonToObjects-fjegefcudpictvaahsrfpcutkyjr/Build/Products/Release-iphoneos/AlamofireJsonToObjects.framework/Info.plist AlamofireJsonToObjects/Info.plist
(1 failure)

Improve Request extension

I'm having a generic function which fires requests to different endpoints. Sometimes these endpoints do not return anything. This is expected. I saw that the responseObject method will fail if the data object is nil.

My proposal would be to change it like this:

 public func responseObject<T:EVObject>(queue: dispatch_queue_t?, completionHandler: (NSURLRequest, NSHTTPURLResponse?, T?, AnyObject?, NSError?) -> Void) -> Self {
        return responseString{(request, response, data, error) in
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
                var parsedObject:T?
                if let notEmptyData = data {
                  parsedObject = T(json: notNilObject)
                }
                dispatch_async(queue ?? dispatch_get_main_queue()) {
                    completionHandler(self.request, self.response, parsedObject, data, error)
                }
            }

        }
    }

Let me know what you think about this. For the responseArray function something similar is needed.

Swift Compiler Error for Xcode 8.3

Please help to solve the problem
Through a pod installed AlamofireJsonToObjects (2.4.1)
When compiling, I see 2 errors:
AlamofireJsonToObjects.swift: 68: 72: 'NSDictionary' is not convertible to '[AnyHashable: Any]'; Did you mean to use 'as!' To force downcast?
AlamofireJsonToObjects.swift: 130: 98: 'NSDictionary' is not convertible to '[AnyHashable: Any]'; Did you mean to use 'as!' To force downcast?

Xcode Version 8.3 (8E162)

In their Xcode 8.2.1 everything worked fine

Generic list parse

Hi, im trying to parse a generic list, i think that there is no support for it for now, but is there any way i can use setValue forUndefinedKey function to pass a class type and be able to parse the list? Maybe is there another way? Thanks in advance.

What i have now:

class JsonMessage : EVObject {
  var _meta : MetaModel

  override
  init() {
      _meta = MetaModel()
  }
} 


class JsonMessageList<T> : JsonMessage {
  var records = [T]()

  override
  init() {

  }

}
   Alamofire.request(.GET, URL, headers: headers)
            .responseObject { (response: JsonMessageList<ProductModel>?, error: NSError?) in
               if (error == nil && response != nil) {
                   for product in response!.records {
                       println("id: " + product.name!);
                   }
                }
                else {
                    println("Error on request");
                }
            }

Im an Android Developer, and i have created a lib that does this on android.
I pass a Model.class (Class) to a ListHelperModel and use this list as a type for gson (a google library that parse json to objects) to parse the list.

Take a look if you want:

ListHelperModel

Check getList() method

Unfortunelly im very new to swift/ios, so i just dont know how and if i can reproduce this.

Use legacy swift error with swift 3

Hi evermeer,

I have just download Xcode 8 (not the beta) and im trying to use the latest version of AlamofireJsonToObjects, but its showing this error:

image

Its just like the alamofire dependency is using an old version of swift. Can you help me please? Thanks in advance.

Is not key value coding-compliant for the key __response_statusCode?

Just updated EVReflection and this lib, and all my classes says this, what is that?


WARNING: The class 'ClassName' is not key value coding-compliant for the key '__response_statusCode'
 There is no support for optional type, array of optionals or enum properties.
As a workaround you can implement the function 'setValue forUndefinedKey' for this. See the unit tests for more information

Migration help needed

Hi there,

I've trying to use the Swift 3 branch, and adopt some thing to Alamofire 4. I get this warning, and I can't quite understand it? This is my code:

`Alamofire.request(apiURL + "users", headers: headers).responseObject { (response: Result<User>) in
                if let user = response.value {
                    completionHandler(user, nil);
                } else {
                    completionHandler(nil, response.error as NSError?);
                }
            }
    }
`

My previous code looked like this:

Alamofire.request(.GET, apiURL + "users", headers: headers).responseObject { (response: Result<User, Error>) in
                if let user = response.value {
                    print(user)
                    completionHandler(user, nil);
                } else {
                    completionHandler(nil, response.error);
                }
            }
    }

However this gives me this error: Generic type Result specialized with too many type parameters (got 2, but expected 1)

I also seem to get another, for me, not understandable error in this piece of code


func getPackage(completionHandler: @escaping (Package?, NSError?) -> ()){

        Alamofire.request(URL + "package", method: .get, headers: headers())
            .responseObject { (response: Result<Package>) in
                if let userPackage = response.value {
                    print(userPackage);

                    completionHandler(userPackage, nil);
                } else {
                    completionHandler(nil, response.error);
                }
        }
    }

This gives me the following error: Cannot convert value of type '(Result<Package>) -> ()' to expected argument type '(URLRequest?, HTTPURLResponse?, Result<_>) -> Void'

Nested Generics

The issue may be dublicated with EVReflection issues page. Bu I dont know where to I write. I just need help. :(

Hello

Is that possible nested generics in EVReflection? I was tested code that the following but it not work. Could you help me about the issue?

class ResponseModel<T:BaseModel> : EVObject,EVGenericsKVC {    

      required init() {
          super.init();
        }

    var success : String?;
    var reason : String?
    var content : [T]?;


    internal override func setValue(value: AnyObject!, forUndefinedKey key: String) {
        if(key == "content"){
            content = value as? [T];
        }
    }

}


class PagerModel<T:BaseModel>: BaseModel,EVGenericsKVC{    
    required init() {
        super.init();
    }

    var total:String?;
    var per_page:String?;
    var current_page:String?;
    var last_page:String?;
    var next_page_url:String?;
    var prev_page_url:String?;
    var from:String?;
    var to:String?;
    var data:[T]?;


       internal  override func setValue(value: AnyObject!, forUndefinedKey key: String) {
        if(key == "data"){
        data = value  as? [T];
        }
    }




class BaseWebServices<T:BaseModel> : NSObject  {

    let BASE_URL : String! = "http://localhost/IOS/public/api/v1/";

    var listener : ResponseListener?;



    func executeService(serviceUrl : String, method : Alamofire.Method,parameters: [String: AnyObject]){

        let URL : String = "\(self.BASE_URL)\(serviceUrl)";
        Alamofire.request(method, URL, parameters:parameters)
            .responseObject { (response: Result<ResponseModel<T>, NSError>) in

                switch response{
                case .Success( _)  :
                    if let result : ResponseModel<T> = response.value {
                        self.listener?.onResponseSuccess(result);
                    }
                    break;
                case .Failure(let error) :
                    self.listener?.onResponseFail(error)
                    break;
                }
        }



    }


class NewsHeaderService: BaseWebServices<PagerModel<NewsHeader>>,ResponseListener {

    override  init() {
        super.init();
        super.listener = self;


        executeService("getNewsHeadersByPrjId/1", method: .POST, parameters: ["token":Common.TOKEN_KEY])
    }

    func onResponseSuccess<T : BaseModel where T : protocol<ObjectProtocol>>(object: ResponseModel<T>) {

    }



    func onResponseFail(failMessage: NSError) {

    }
}


class NewsHeader : BaseModel{   

    var id : String?;
    var Description: String?;
    var newsTypeId:String?;
    var newsOrder : String?;
    var isCommentActive : String?;
    var placeTypeId : String?;
    var link : String?;
    var title : String?; 
    var pubDate : String?;
    var imageUrl : String?;
    var imageThumUrl : String?;
    var appId : String?;
    var projectId : String?;
    var isValid : String?;
    var created_at : String?;
    var updated_at : String?;
}

When I try to execute

var service : NewsHeaderService = NewsHeaderService();

There was an error,

ERROR: Could not create an instance for type PagerModel
dict:{
"current_page" = 1;
data = (
{
appId = 1;
"created_at" = "2016-06-29 12:15:23";
description = 33333;
id = 1;
imageThumUrl = "";
imageUrl = "uploads/74d41d1a8b39541ce2e7b6fc1f844ef0_04_IP-MAN-3_Courtesy-of-Well-Go-USA_0-752x440.jpg";
isCommentActive = 1;
isValid = 1;
link = 11111;
newsOrder = 0;
newsTypeId = 2;
placeTypeId = 1;
projectId = 1;
pubDate = "";
title = 22222;
"updated_at" = "2016-06-29 12:15:23";
}
);
from = 1;
"last_page" = 1;
"next_page_url" = "";
"per_page" = 15;
"prev_page_url" = "";
to = 1;
total = 1;
}

If I change class PagerModel<T:BaseModel> toclass PagerModel and remove "data" property it works fine but I need the data :) Can anybody help me about my issue? Thanks for your time.

Edit: Here is parsed JSON data

{"success":true,"reason":"OK","content":[{"total":1,"per_page":15,"current_page":1,"last_page":1,"next_page_url":null,"prev_page_url":null,"from":1,"to":1,"data":[{"id":1,"newsTypeId":"2","newsOrder":"0","isCommentActive":"1","placeTypeId":"1","link":"11111","title":"22222","description":"33333","pubDate":"","imageUrl":"uploads/74d41d1a8b39541ce2e7b6fc1f844ef0_04_IP-MAN-3_Courtesy-of-Well-Go-USA_0-752x440.jpg","imageThumUrl":"","appId":"1","projectId":"1","isValid":"1","created_at":"2016-06-29 12:15:23","updated_at":"2016-06-29 12:15:23"}]}]}

import AlamofireJsonToObjects not sufficient

In the readme it is written that the following has to be done to use AlamofireJsonToObjects:

import AlamofireJsonToObjects

If i do this i get the following error: Use of undeclared type 'EVObject'
If i add the following import: import EVReflection it works.

I'm using Cocoapods.

Saving json on NSUserDefaults

Hi evermeer, i just want to expose the approach im using to save json for local usage. My app basically loads data from the api on the first time and on the next it check if theres local data instead of downloading it again, the user can use a pull to reflesh to force the redownload.

Im using NSUserDefaults for saving a json array and using EVReflection to parse it when retrieving. What do you think about this approach? Heres the code:

// this class basically provides an id so i can use getById and compare objects 
class MyModel : EVObject{
    var id : Int = 0
}
import UIKit
import EVReflection
import AlamofireJsonToObjects

class AbstractLocalDB<T where T:MyModel>: NSObject {


    // add single object to list
    func add(object : T, name : String) {

        var oldArray = NSUserDefaults.standardUserDefaults().objectForKey(name)
        var array : [NSString]
        if (oldArray != nil) {
             array = oldArray as! [NSString]
        }
        else {
            array = [NSString]()
        }

        var toJson = EVReflection.toJsonString(object, performKeyCleanup: false)

        array.append(toJson as! NSString!)
        NSUserDefaults.standardUserDefaults().setObject(array, forKey: name)

    }

    func clearAll() {
        let appDomain = NSBundle.mainBundle().bundleIdentifier!

        NSUserDefaults.standardUserDefaults().removePersistentDomainForName(appDomain)
    }

    func add(object : T) {
        self.add(object, name: String(T().dynamicType))
    }

    // add or replace saved list
    func add(objects : [T], name : String) {

        var array : [NSString] = [NSString]()

        for object in objects {
            var toJson = EVReflection.toJsonString(object, performKeyCleanup: false)
            array.append(toJson as! NSString!)

        }

        NSUserDefaults.standardUserDefaults().setObject(array, forKey: name)
        print(array)

    }

    func add(objects : [T]) {

     self.add(objects, name: String(T().dynamicType))
    }

    func getAll(object : T, name : String) -> [T]? {
        var oldArray = NSUserDefaults.standardUserDefaults().objectForKey(name)
        var array : [NSString]
        var objArray:[T]
        if (oldArray != nil) {
            var str : String = formatStringToJson(oldArray as! [NSString])


            print(str)
            objArray = EVReflection.arrayFromJson(T().dynamicType.init(), json: str)

            return objArray;

        }
        return nil;

    }

    func clear(object : T, name : String) {
        var list : [T]? = getAll(object, name: name)

        if (list != nil) {
            self.remove(list!, name: name)
        }
    }

    func remove(object : T) {
        self.remove(object, name: String(T().dynamicType))
    }

    func remove(list : [T], name : String) {
        for object in list {
            self.remove(object, name: name)
        }
    }

    func remove(object : T, name : String) {
        var exist : Bool = false
        let objArray = self.getAll(object, name : name)
        var myObject : T
        var index : Int = 0;
        let id : Int = (object as MyModel!).id

        if (objArray != nil) {
            var objectArray : [T] = objArray!
            for (var x = 0 ; x < objectArray.count ; x++) {
                let myModel = objectArray[x] as MyModel!
                if (myModel.id == id) {
                    exist = true
                    index = x
                    break
                }
            }
        }


        if (exist) {

            var stringArray : [NSString] = NSUserDefaults.standardUserDefaults().objectForKey(name) as! [NSString]

            stringArray.removeAtIndex(index)
            NSUserDefaults.standardUserDefaults().setObject(stringArray, forKey: name)

        }
    }

    func edit(object : T) {
        self.edit(object, name: String(T().dynamicType))
    }

    func edit(object : T, name : String) {

        var exist : Bool = false
        var objArray = self.getAll(object, name : name)
        var myObject : T
        var index : Int = 0;

        if (objArray != nil) {
            var objectArray : [T] = objArray!
            for (var x = 0 ; x < objectArray.count ; x++) {
                var myModel = objectArray[x] as MyModel!
                if (myModel.id == object.id) {
                    exist = true
                    index = x
                    break
                }
            }
        }
        else {
            self.add(object, name: name)
            return
        }


        if (exist) {

            var stringArray : [NSString] = NSUserDefaults.standardUserDefaults().objectForKey(name) as! [NSString]

            var toJson = EVReflection.toJsonString(object, performKeyCleanup: false)
            stringArray[index] = toJson
            NSUserDefaults.standardUserDefaults().setObject(stringArray, forKey: name)

        }
        else {
            self.add(object, name: name)
        }

    }

    func getById(object : T, name : String, id: Int) -> T? {
        let objArray = self.getAll(object, name : name)
        var myObject : T

        if (objArray != nil) {
            let objectArray : [T] = objArray!
            for model in objectArray {
                let myModel = model as MyModel!
                if (myModel.id == id) {
                    return model
                }
            }
        }
        return nil

    }


    private func formatStringToJson(array : [NSString]) -> String {
        var str = "["
        for (var x = 0 ; x < array.count ; x++) {
            str += array[x] as String
            if (x < array.count - 1) {
                str += ", "
            }
        }

        str += "]"
      //  println(str)

        return str

    }

  }

Mapping list of objects?

Hi there,

I'm trying to map the following JSON:

[{"id":121, "active":true}]

Into the following object:

class UserPackageTransfer: EVObject, Mappable {

    var userPackages = [UserPackage]()
...

`class UserPackage : EVObject, Mappable {

var id : Int = 0
var active: Bool = false`

...

I try to map it this way:

Alamofire.request(apiURL + "?userid=2", method: .get, parameters: nil, encoding: URLEncoding.default, headers: headers()).responseObject { (response: DataResponse) in

But the object I get is empty, and I'm left with:

Optional(UserPackageTransfer {
   hash = 0
   userPackages = (
)
}

Any suggestions?

Response class module problem

Using latest version, when i run application target everything works fine.
But I added Test target to the project (Quick&Nimble) and tried to run test target, the problem is:
req.responseObject { (response: Result<T, NSError>) in
if let result = response.value {

I have single response class that belongs to two target (app and test).
Even T is type of class belongs to Test module, result objects class is belongs to app target class.
It seems like you convert result class regardless of module check.

Custom parser

Hi, i have the following class:

class EventModel : MyModel {
    var name : String?
    var dateStart : String?
    var dateEnd : String?
    var allDay : Int = 0
    var objectFull : NSObject?
    var objectType : String?

 override func setValue(value: AnyObject!, forUndefinedKey key: String) {
        switch key {
        case "objectFull":
            if (objectType == "task") {
                objectFull = (value as? TaskModel)!
            }
            else if (objectType == "sale") {
                objectFull = (value as? SaleModel)!
            }
            break
        default:
            print("---> setValue '\(value)' for key '\(key)' should be handled.")
        }
    } 


}

I know i could solve this with generics, but i receive an array of events from my server, so i cant instantiate it with generics. This approach (NSObject) isnt working. May you help me please? Thanks in advance.

Build error when including as CocoaPod

0  swift                    0x00000001049483ad PrintStackTraceSignalHandler(void*) + 45
1  swift                    0x0000000104947b56 SignalHandler(int) + 790
2  libsystem_platform.dylib 0x00007fff88f9f52a _sigtramp + 26
3  libsystem_platform.dylib 0x00007f8443d83d50 _sigtramp + 3135129664
4  swift                    0x0000000101a6dc06 swift::irgen::emitWitnessTableRef(swift::irgen::IRGenFunction&, swift::CanType, llvm::Value**, swift::ProtocolConformanceRef) + 102
5  swift                    0x0000000101a6e309 void llvm::function_ref<void (swift::irgen::GenericRequirement)>::callback_fn<(anonymous namespace)::EmitPolymorphicArguments::emit(swift::CanTypeWrapper<swift::SILFunctionType>, llvm::ArrayRef<swift::Substitution>, swift::irgen::WitnessMetadata*, swift::irgen::Explosion&)::$_14>(long, swift::irgen::GenericRequirement) + 857
6  swift                    0x0000000101a6351b (anonymous namespace)::PolymorphicConvention::enumerateRequirements(llvm::function_ref<void (swift::irgen::GenericRequirement)> const&) + 299
7  swift                    0x0000000101a6de68 swift::irgen::emitPolymorphicArguments(swift::irgen::IRGenFunction&, swift::CanTypeWrapper<swift::SILFunctionType>, swift::CanTypeWrapper<swift::SILFunctionType>, llvm::ArrayRef<swift::Substitution>, swift::irgen::WitnessMetadata*, swift::irgen::Explosion&) + 472
8  swift                    0x0000000101ad0e71 (anonymous namespace)::IRGenSILFunction::visitFullApplySite(swift::FullApplySite) + 2929
9  swift                    0x0000000101abb458 swift::irgen::IRGenModule::emitSILFunction(swift::SILFunction*) + 9160
10 swift                    0x00000001019cd20f swift::irgen::IRGenerator::emitLazyDefinitions() + 6399
11 swift                    0x0000000101aa058a performIRGeneration(swift::IRGenOptions&, swift::ModuleDecl*, swift::SILModule*, llvm::StringRef, llvm::LLVMContext&, swift::SourceFile*, unsigned int) + 1802
12 swift                    0x0000000101955f31 performCompile(swift::CompilerInstance&, swift::CompilerInvocation&, llvm::ArrayRef<char const*>, int&, swift::FrontendObserver*) + 23777
13 swift                    0x000000010194e2b3 swift::performFrontend(llvm::ArrayRef<char const*>, char const*, void*, swift::FrontendObserver*) + 17859
14 swift                    0x000000010190a5cf main + 8239
15 libdyld.dylib            0x00007fff8744c5ad start + 1
Stack dump:
0.	Program arguments: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift -frontend -c -primary-file /Users/me/src/MyProject/Pods/AlamofireJsonToObjects/AlamofireJsonToObjects/AlamofireJsonToObjects.swift -target x86_64-apple-ios8.0 -enable-objc-interop -sdk /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator10.2.sdk -I /Users/me/Library/Developer/Xcode/DerivedData/Workspaces-gjylqawyfbcwxdbmcefvzjjvbhll/Build/Products/Debug-iphonesimulator/AlamofireJsonToObjects -F /Users/me/Library/Developer/Xcode/DerivedData/Workspaces-gjylqawyfbcwxdbmcefvzjjvbhll/Build/Products/Debug-iphonesimulator/AlamofireJsonToObjects -F /Users/me/Library/Developer/Xcode/DerivedData/Workspaces-gjylqawyfbcwxdbmcefvzjjvbhll/Build/Products/Debug-iphonesimulator/Alamofire -F /Users/me/Library/Developer/Xcode/DerivedData/Workspaces-gjylqawyfbcwxdbmcefvzjjvbhll/Build/Products/Debug-iphonesimulator/EVReflection -enable-testing -g -import-underlying-module -module-cache-path /Users/me/Library/Developer/Xcode/DerivedData/ModuleCache -D COCOAPODS -serialize-debugging-options -Xcc -I/Users/me/Library/Developer/Xcode/DerivedData/Workspaces-gjylqawyfbcwxdbmcefvzjjvbhll/Build/Intermediates/Pods.build/Debug-iphonesimulator/AlamofireJsonToObjects.build/swift-overrides.hmap -Xcc -iquote -Xcc /Users/me/Library/Developer/Xcode/DerivedData/Workspaces-gjylqawyfbcwxdbmcefvzjjvbhll/Build/Intermediates/Pods.build/Debug-iphonesimulator/AlamofireJsonToObjects.build/AlamofireJsonToObjects-generated-files.hmap -Xcc -I/Users/me/Library/Developer/Xcode/DerivedData/Workspaces-gjylqawyfbcwxdbmcefvzjjvbhll/Build/Intermediates/Pods.build/Debug-iphonesimulator/AlamofireJsonToObjects.build/AlamofireJsonToObjects-own-target-headers.hmap -Xcc -I/Users/me/Library/Developer/Xcode/DerivedData/Workspaces-gjylqawyfbcwxdbmcefvzjjvbhll/Build/Intermediates/Pods.build/Debug-iphonesimulator/AlamofireJsonToObjects.build/AlamofireJsonToObjects-all-non-framework-target-headers.hmap -Xcc -ivfsoverlay -Xcc /Users/me/Library/Developer/Xcode/DerivedData/Workspaces-gjylqawyfbcwxdbmcefvzjjvbhll/Build/Intermediates/Pods.build/all-product-headers.yaml -Xcc -iquote -Xcc /Users/me/Library/Developer/Xcode/DerivedData/Workspaces-gjylqawyfbcwxdbmcefvzjjvbhll/Build/Intermediates/Pods.build/Debug-iphonesimulator/AlamofireJsonToObjects.build/AlamofireJsonToObjects-project-headers.hmap -Xcc -I/Users/me/Library/Developer/Xcode/DerivedData/Workspaces-gjylqawyfbcwxdbmcefvzjjvbhll/Build/Products/Debug-iphonesimulator/AlamofireJsonToObjects/include -Xcc -I/Users/me/src/MyProject/Pods/Headers/Private -Xcc -I/Users/me/src/MyProject/Pods/Headers/Public -Xcc -I/Users/me/Library/Developer/Xcode/DerivedData/Workspaces-gjylqawyfbcwxdbmcefvzjjvbhll/Build/Intermediates/Pods.build/Debug-iphonesimulator/AlamofireJsonToObjects.build/DerivedSources/x86_64 -Xcc -I/Users/me/Library/Developer/Xcode/DerivedData/Workspaces-gjylqawyfbcwxdbmcefvzjjvbhll/Build/Intermediates/Pods.build/Debug-iphonesimulator/AlamofireJsonToObjects.build/DerivedSources -Xcc -DPOD_CONFIGURATION_DEBUG=1 -Xcc -DDEBUG=1 -Xcc -DCOCOAPODS=1 -Xcc -ivfsoverlay -Xcc /Users/me/Library/Developer/Xcode/DerivedData/Workspaces-gjylqawyfbcwxdbmcefvzjjvbhll/Build/Intermediates/Pods.build/Debug-iphonesimulator/AlamofireJsonToObjects.build/unextended-module-overlay.yaml -Xcc -working-directory/Users/me/src/MyProject/Pods -emit-module-doc-path /Users/me/Library/Developer/Xcode/DerivedData/Workspaces-gjylqawyfbcwxdbmcefvzjjvbhll/Build/Intermediates/Pods.build/Debug-iphonesimulator/AlamofireJsonToObjects.build/Objects-normal/x86_64/AlamofireJsonToObjects~partial.swiftdoc -Onone -parse-as-library -module-name AlamofireJsonToObjects -emit-module-path /Users/me/Library/Developer/Xcode/DerivedData/Workspaces-gjylqawyfbcwxdbmcefvzjjvbhll/Build/Intermediates/Pods.build/Debug-iphonesimulator/AlamofireJsonToObjects.build/Objects-normal/x86_64/AlamofireJsonToObjects~partial.swiftmodule -serialize-diagnostics-path /Users/me/Library/Developer/Xcode/DerivedData/Workspaces-gjylqawyfbcwxdbmcefvzjjvbhll/Build/Intermediates/Pods.build/Debug-iphonesimulator/AlamofireJsonToObjects.build/Objects-normal/x86_64/AlamofireJsonToObjects.dia -emit-dependencies-path /Users/me/Library/Developer/Xcode/DerivedData/Workspaces-gjylqawyfbcwxdbmcefvzjjvbhll/Build/Intermediates/Pods.build/Debug-iphonesimulator/AlamofireJsonToObjects.build/Objects-normal/x86_64/AlamofireJsonToObjects.d -emit-reference-dependencies-path /Users/me/Library/Developer/Xcode/DerivedData/Workspaces-gjylqawyfbcwxdbmcefvzjjvbhll/Build/Intermediates/Pods.build/Debug-iphonesimulator/AlamofireJsonToObjects.build/Objects-normal/x86_64/AlamofireJsonToObjects.swiftdeps -o /Users/me/Library/Developer/Xcode/DerivedData/Workspaces-gjylqawyfbcwxdbmcefvzjjvbhll/Build/Intermediates/Pods.build/Debug-iphonesimulator/AlamofireJsonToObjects.build/Objects-normal/x86_64/AlamofireJsonToObjects.o 
1.	While emitting IR SIL function @_TTVFC22AlamofireJsonToObjects18EVNetworkingObject15propertyMappingfT_GSaTGSqSS_GSqSS___ for 'propertyMapping' at /Users/me/src/MyProject/Pods/AlamofireJsonToObjects/AlamofireJsonToObjects/AlamofireJsonToObjects.swift:22:19

Using AlamofireJsonToObjects (2.4.0)

Any thoughts?

Is it able to obtain an array of object?

For example, to get users array, or a user object. (assume user is a model and with proper function defined)

Is this library able to obtain an array of object as well as a single object?

1.6 version uses EVReflection swift 3 version

I am using pod as below:
pod 'AlamofireJsonToObjects', '~> 1.0'

After running pod update today, I received build errors and noticed EVReflection module changed to swift 3 version like below

open class EVObject: NSObject, NSCoding { // These are redundant in Swift 2+: CustomDebugStringConvertible, CustomStringConvertible, Hashable, Equatable

Array mapping return empty array

Hi,

I try to map an array of objects like this:

Models

open class ApiGenericBase: EVNetworkingObject {
    var success: NSNumber?
    var message: String?
    var status_code: String?
}

open class ApiResponse<T>: ApiGenericBase, EVGenericsKVC where T:NSObject {
    var data: T = T()
    
    public func setGenericValue(_ value: AnyObject!, forUndefinedKey key: String) {
        switch key {
        case "data":
            data = value as? T ?? T()
        default:
            print("---> setGenericValue '\(value)' forUndefinedKey '\(key)' should be handled.")
        }
    }
    
    public func getGenericType() -> NSObject {
        return T()
    }
}

public class Vehicle: EVNetworkingObject {
    var uuid: String?
    ...
}

open class List<T>: EVNetworkingObject, EVGenericsKVC where T:NSObject {
    var records: [T] = [T]()
    
    public func setGenericValue(_ value: AnyObject!, forUndefinedKey key: String) {
        records = value as? [T] ?? [T]()
    }
    
    public func getGenericType() -> NSObject {
        return [T]() as NSObject
    }
    
}

and I'm calling like this:

manager.request(GetVehicleFromArgusPlateProvider, method: .get,
                        parameters: parameters,
                        encoding: URLEncoding.default,
                        headers: nil).responseObject { (response: DataResponse<ApiResponse<List<Vehicle>>>) in
            ...
        }

but when I dump response I have an empty array:

dump(response)
▿ _TtGC9xxx_v24ListCS_7Vehicle_ = {
  "records" : [

  ]
} #0
  - super: AlamofireJsonToObjects.EVNetworkingObject
    ▿ super: EVReflection.EVObject
      - super: NSObject
      - evReflectionStatuses: 0 elements
  - records: 0 elements

My JSON server response:

{
  "data": [
    {
      "uuid": "52ec7e70-eb02-11e6-b6f3-1bb7c380e65e",
      ...
    },
    {
      "uuid": "53230b60-eb02-11e6-aee4-47e7e9e49d51",
      ...
    },
    {
      "uuid": "5366e810-eb02-11e6-93b6-91512741054a",
      ...
    },
    {
      "uuid": "53aa9cd0-eb02-11e6-a958-215ccabe8e51",
      ...
    }
  ]
}

Any idea or help please.
Thanks.

Null response in array

In the example you mentioned, the array for "three_day_forecast' returns 0. Please look into it.

Cheers,
Mohsin

NSArray element failed to match the Swift Array Element type

I'm having an issue when trying to get an array of objects inside an an object to deserialize. The output is saying fatal error: NSArray element failed to match the Swift Array Element type and then the debugger breaks on line 560 of EVReflection.swift mi = Mirror(reflecting: theValue) with the error: Thread 1: EXC_BAD_INSTRUCTION (code=EXC_1386_INVOP, subcode=0x0).

It's been able to deserialize nested objects when its not in an array, so not sure what the issue might be here. I'll paste some code below though so you can see my process.

Alamofire Request, the error happens when I ask it to print the debugDescription

Alamofire.request(.GET, "http://server.com/api/get/all", headers: getAuthenticationHeaders()).
validate().
responseArray { (response: Result<[MyPrimaryObject], NSError>) in
       if(response.isSuccess){
           print(response.debugDescription)
           success(response.value)
       }
       if(response.isFailure){
           let error : NSError = response.error!
           NSLog("API failure: \(error.debugDescription)")
           failure(error)
       }
   }

Models:

public class MyPrimaryObject : EVObject{

    public var myPrimaryObjectId : NSUUID?
    public var name : String = ""
    public var myObjectDescription: String?

    public var numberOfOccurrences : Int = 0
    public var positiveResponsePercentage : Float = 0

    public var secondaryObjects : [MySecondaryObject]?

    override public func propertyMapping() -> [(String?, String?)] {
        return [("myObjectDescription","Description")]

    }
}

public class MySecondaryObject : EVObject {
    public var mySecondaryObjectId : Int = 0
    public var dateRecorded : NSDate?
    public var rating : Int = 0
    public var userRemarks : String?
}

It also should be noted that MyPrimaryObject is parsed perfectly when the secondaryObjects are null from the API response.

I've obviously simplified, I'm happy to share the actual code with you privately. Any help would be greatly appreciated! Thanks so much!

get Array with key

my server returns a response like this

{data:[array of EVObject]}

How can i get those kind of data?

I have tried
Alamofire.request(.GET, URL) .responseArray("data", completionHandler: (Result<[EVObject], NSError>) -> Void in)
but it gives me a compile error

Cannot invoke 'responseArray' with an argument list of type '(String, completionHandler: (Result<[EVObject], NSError>).Type)'

Using with Swift 2.0 and xcode 7.0

Hi, whats the default version for use with swift 2.0?

I was using:

use_frameworks!
pod "AlamofireJsonToObjects"

to get the latests, but after updating to xcode 7 it's showing a lot of syntax errors. Thanks in advance.

Help with usage

Hi my friends, i tried all of bug fixing but i couldn't be success to use alamofirejsontoobjects in my swift 3.0.2 project with Xcode 8.2.1. My project is in link below. Please help me.
http://jmp.sh/rAS7YCX

Custom mapping problem

Hi,

I try to use AlamofireJsonToObjects 1.2.0 with a custom mapping.

Alamofire.request(.GET, "http://myendpointurl/", parameters: nil).responseArray {
(response: Result<[Site]>) -> Void in
NSLog("sites count: %d", response.value!.count)
}

class Site: EVObject {

/*var id: NSNumber?
var openDataId: NSString?
var title: NSString?
var nature: NSString?
var latitude: NSNumber?
var longitude: NSNumber?
var startDate: NSDate?
var endDate: NSDate?
var carNuisanceLevel: NSNumber?
var carNuisanceDescription: NSString?
var bikeNuisanceLevel: NSNumber?
var bikeNuisanceDescription: NSString?
var pedestrianNuisanceLevel: NSNumber?
var pedestrianNuisanceDescription: NSString?
var contactUrl: NSString?*/

var id: Int?
var openDataId: String?
var title: String?
var nature: String?
var latitude: Double?
var longitude: Double?
var startDate: NSDate?
var endDate: NSDate?
var carNuisanceLevel: Double?
var carNuisanceDescription: String?
var bikeNuisanceLevel: Double?
var bikeNuisanceDescription: String?
var pedestrianNuisanceLevel: Double?
var pedestrianNuisanceDescription: String?
var contactUrl:String?

override func propertyMapping() -> [(String?, String?)] {
    return [("openDataId","record_id"), ("startDate","start_date"), ("endDate","end_date"), ("carNuisanceLevel","nuisance_car"), ("carNuisanceDescription","nuisance_car_description"), ("bikeNuisanceLevel","nuisance_bike"), ("bikeNuisanceDescription","nuisance_bike_description"), ("pedestrianNuisanceLevel","nuisance_pedestrian"), ("pedestrianNuisanceDescription","nuisance_pedestrian_description"), ("contactUrl","myfeelback_url")]
}

}

In this configuration (Swift types use Int, String), I have this error on each field binding try

WARNING: The class 'Site' is not key value coding-compliant for the key 'carNuisanceLevel'
There is no support for optional type, array of optionals or enum properties.
As a workaround you can implement the function 'setValue forUndefinedKey' for this. See the unit tests for more information

When I use other configuration (ObjC types use NSNumber, NSString), I don't have warning message anymore but a breakpoint (I suppose on each field binding try) in init method assemblor code of my relative class

0x9c6e0 <+0>:   pushl  %ebp
0x9c6e1 <+1>:   movl   %esp, %ebp
0x9c6e3 <+3>:   pushl  %esi
0x9c6e4 <+4>:   subl   $0x84, %esp
0x9c6ea <+10>:  calll  0x9c6ef                   ; <+15> at Site.swift:12
0x9c6ef <+15>:  popl   %eax
0x9c6f0 <+16>:  movl   0x8(%ebp), %ecx
0x9c6f3 <+19>:  movl   %ecx, -0x8(%ebp)

-> 0x9c6f6 <+22>: movl $0x0, -0x10(%ebp)

What am I doing wrong?

Other question, for example for startDate, I get a string in UTC format, is AlamofireJsonToObjects able to manage conversion to NSDate natively or do I add some specific process ?

Thanks in advance.

Incorrect arguments label in call

Hi there,

I just updated my podfile to use the main branch instead of the Swift3, and now I'm facing several instances of the same error.

"Incorrect argument label in call (have 'dictionary:', expected 'coder:')"

This error occurs in both line 61 and 125.

Empty objects after serialization

When a JSON object returned from the server is different from the object expected on the client, the serialized object just make it empty and do not return any error.

For example:

Client object expected

class UserInformation:EVObject
{
var username: String?
var password: String?
}

Server object sent

{error:"An error message"}

Result

Result object returns with success, empty UserInformation and no errors

Expected

Result object returns with serialization error and nil Result.value

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.