evermeer / alamofirejsontoobjects Goto Github PK
View Code? Open in Web Editor NEWAn Alamofire extension which converts JSON response data into swift objects using EVReflection
License: Other
An Alamofire extension which converts JSON response data into swift objects using EVReflection
License: Other
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?
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.
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.
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.
In the example you mentioned, the array for "three_day_forecast' returns 0. Please look into it.
Cheers,
Mohsin
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'
Hi,
I'm getting the following error when trying to compile AlamofireJsonToObjects on xCode 7.0 in AlamofireJsonToObjects.swift, line 54.
"constructing an object of class type 'T' with a metatype value must use a 'required' initializer"
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
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.
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
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.
{
"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ção completa é ideal para aquele momento em que você precisa dar um bom trato no seu veículo. Nesse serviço realizamos a limpeza interna e externa completa, aplicamos os melhores produtos para cada área do seu carro, odorizamos o ambiente interno e realizamos a higienização no teto, tapetes, estofados e ar-condicionado.</p>",
"status": "1",
"vantagens": "<p>Comodidade e segurança pois vamos até o seu veículo;</p>\r\n<p>Ecologicamente correto, pois economiza água e não utiliza produtos químicos;</p>\r\n<p>Extermina ácaros e bactérias, evitando ataques alérgicos;</p>\r\n<p>Desodoriza por completo o veículo e não somente disfarça com outros produtos;</p>\r\n<p>Conserva a lataria do veículo;</p>\r\n<p>Não desgasta o estofado pois não existe a necessidade de esfregá-lo;</p>\r\n<p>A limpeza dura duas vezes mais que uma limpeza convencional;</p>\r\n<p>Você ganha uma economia de tempo e dinheiro;</p>\r\n<p>Carro com aspecto de carro novo e limpíssimo;</p>\r\n<p>Higienização interna e externa completa, incluindo o teto do automó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ção e proteção.</p>",
"ordem": "2",
"publico": "<p>Você tem um evento nos próximos dias ou está precisando impressionar alguém? Esse serviço é ideal para você. A gente sabe que melhor que assistir ao casamento do seu amigo de infância é fazer as pessoas assistirem o seu carro chegando bonitão na festa. Se você preza pelo cuidado com o seu veículo e quer que ele tenha sempre um aspecto de carro novo, é a hora ideal para agendar uma higienizaçã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)")
}
}
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)
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
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?
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.
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.
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?
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.
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
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:
Unfortunelly im very new to swift/ios, so i just dont know how and if i can reproduce this.
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
}
}
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"}]}]}
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
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.
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.
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?
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.
hi
is this issue solved in current version?
evermeer/EVReflection#42
thanks
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)'
Any ETA on this? I see that the work on EVReflection Swift 3 is almost done too!
In Alamofire 2.0.0.beta.1 the response method signatures have all changed to return a Response instead of a data and error object.
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?
}
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!
Both AlamofireJsonToObjects and AlamofireXmlToObjects are moved into EVReflection.
You can use these by puting this in your podfile:
pod 'EVReflection/Alamofire'
There are now also sub specs for Moya, RxSwift and ReactiveSwift
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.