bmoliveira / moya-objectmapper Goto Github PK
View Code? Open in Web Editor NEWObjectMapper bindings for Moya and RxSwift
License: MIT License
ObjectMapper bindings for Moya and RxSwift
License: MIT License
Hello,
I am trying to figure out how to validate JSON data prior to mapping (e.g. key exists, data type is correct, that sort of things). As stated in the Mappable protocol definition, the init?(map: Map) function is the place to do this.
public protocol Mappable: BaseMappable {
/// This function can be used to validate JSON prior to mapping. Return nil to cancel mapping at this point
init?(map: Map)
}
The question is what would be a correct way to achieve this? Below is my code, but I am pretty sure I should not be mapping anything in init.
struct Result: Entity {
var id: String!
var score: Score!
var markers: [Marker]!
var benefits: [Benefit]!
var date: Date?
}
// MARK: - JSON
extension Result: Mappable {
init?(map: Map) {
precondition(map.mappingType == .fromJSON)
id <- map["id"]
guard id != nil else { return nil }
score <- map["score"]
guard score != nil else { return nil }
markers <- map["markers"]
guard markers != nil else { return nil }
benefits <- map["benefits"]
guard benefits != nil else { return nil }
}
mutating func mapping(map: Map) {
id <- map["id"]
score <- map["score"]
markers <- map["markers"]
benefits <- map["benefits"]
date <- (map["date"], dateTransform)
}
}
Thanks,
Sebastian
After updated to Moya-ObjectMapper (2.4). I failed to build my project. :-(
import Moya_ObjectMapper does not work
I tried many times. I feel helpless.
Is there somewhere a rxswift example?
When I follow the following rxSwift Doc:
RxMoyaProvider<APIService>(endpointClosure: endpointClosure, plugins: [plugins])
.request(service)
.debug("Moya")
.mapObject(Repository)
I get the error message:
Value of type 'Observable<Response>' has no member 'mapObject'
Hello,
I am trying to setup the Moya-ObjectMapper with RxSwift but unfortunately it gives me this error
Cannot invoke 'request' with an argument list of type '(CountryService)'
When I cmd click the request it goes to UIWebView.h NSURLRequest
CountryServiceProvider.request(CountryService.all)
.mapArray(Country)
.subscribe { event -> Void in
switch event {
case .Next(let repos):
self.repos = repos
case .Error(let error):
print(error)
default:
break
}
}.addDisposableTo(disposeBag)
my import on the viewcontroller
import UIKit
import Moya
import ObjectMapper
import RxSwift
import Moya_ObjectMapper
let CountryServiceProvider = MoyaProvider<CountryService>()
CountryService
struct Country: Mappable{
var name: String?
init?(map: Map) {
}
// Mappable
mutating func mapping(map: Map) {
name <- map["name"]
}
}
My podfile
pod 'Moya-ObjectMapper/RxSwift', :git => 'https://github.com/ivanbruel/Moya-ObjectMapper'
pod 'Moya/RxSwift'
pod 'RxSwift', :git => 'https://github.com/ReactiveX/RxSwift'
It seems that it doesn't pick the correct request method somehow.
Hi, sorry if this question is not appropriate, i am trying to install this library using Carthage, but i am getting the following error: "Task failed with exit code 65"
The log file shows a compilation error:
/Users/grago/Work/hereflow-client-ios/Carthage/Checkouts/Moya-ObjectMapper/Source/Response+ObjectMapper.swift:18:13: error: use of unresolved identifier 'MoyaError'
I am using XCode 8.3 with Swift 3.1, does this library support it?
Thanks a lot.
i made a new mapper for a personal project, i build from zero and conforms the swift api guidelines... My idea is not replace your project or pod, but if you like, we can merge both repos :D...
The repo is https://github.com/gperdomor/MoyaObjectMapper
let me know what you think :D
I run the compiled code with Xcode9, then run on iOS11, and the following array structure resolves to empty. But with Xcode9.3 compiled and run on iOS10, this problem won't happen. Can you help me solve this problem?
coordinates: [
[
[100.0, 0.0],
[101.0, 0.0],
[101.0, 1.0],
[100.0, 1.0],
[100.0, 0.0]
]
]
Moya version: 'Moya/RxSwift', '~> 11.0'
with pod 'Moya-ObjectMapper/RxSwift'
This is a design question about how to use ObjectMapper and Moya the best way. I have multiple endpoints answering with the same JSON structure:
{
"data": {
....
},
"metadata": {
"timestamp": 123232323,
"error": null
}
}
Inside "data" key, is the actual data that is mapped to my model objects. I know I could create each model object with the data and metadata fields and be automatically mapped. But that doesn't seem a good design to me, as "data" and "metadata" aren't part of the model object. I could also use the "map to key" function to map directly what is inside "data", but I'll be missing the metadata field in case there's a reported error from the API.
Is there any way (maybe using protocols?) to not have repeated the data and metadata keys on each of my model objects? I'm making the request with Rx like this:
self.provider.rx.request(MultiTarget(API.global(currency: .usd)))
.filterSuccessfulStatusCodes()
.asObservable()
.mapObject(GlobalData.self)
.bind(to: globalDataObj) //<-- maybe filtering metadata object before binding?
.disposed(by: disposeBag)
Hello guys,
I'm trying ObjectMapper with Moya (Swift 3) but "pod install" failed with follow message:
[!] Unable to satisfy the following requirements:
Moya (= 8.0.0-beta.2)
required by Podfile
Moya (~> 5.1.0)
required by Moya-ObjectMapper/Core (1.0.2)
Can someone help me ?
FYI
I'm having this issue on the latest version, if regress to version 1.3.0 this doesn't happens.
After making some searches I see people having the same problem, but they are using Carthage and its not my case.
This even happens with the Demo project (after doing pod update). And Xcode doesn't provide more info
It seems it hasn't been updated for months.
And some pull requests still needs to be handled.
Hi,
I upgraded to latest Moya / RxSwift :
- Moya (11.0.2):
- Moya/Core (= 11.0.2)
- Moya-ObjectMapper/Core (2.7):
- Moya (~> 11)
- ObjectMapper (~> 3.3)
- Moya-ObjectMapper/RxSwift (2.7):
- Moya-ObjectMapper/Core
- RxSwift (~> 4.1)
- Moya/Core (11.0.2):
- Alamofire (~> 4.1)
- Result (~> 3.0)
- Moya/RxSwift (11.0.2):
- Moya/Core
- RxSwift (~> 4.0)
And I got this error using new rx syntax :
"Value of type 'PrimitiveSequence<SingleTrait, Response>' has no member 'mapObject'"
Here's my request code :
_ = self.api_manager
.rx.request(
.auth(accessToken: token)
)
.mapObject(User.self)
.subscribe({ event in
...
})
function signature specialization <preserving fragile attribute, Arg[1] = [Closure Propagated : reabstraction thunk helper from @callee_owned (@unowned Swift.UnsafeBufferPointer<Swift.UInt8>) -> () to @callee_owned (@unowned Swift.UnsafeBufferPointer<Swift.UInt8>) -> (@out ()), Argument Types : [@callee_owned (@unowned Swift.UnsafeBufferPointer<Swift.UInt8>) -> ()]> of generic specialization <preserving fragile attribute, ()> of Swift.StaticString.withUTF8Buffer ((Swift.UnsafeBufferPointer<Swift.UInt8>) -> A) -> A
Its required any mac specifications using like Xcode 9, swift 3, macOsSieraa version -10.12.6
Can't able to install the Moya-ObjectMapper in new project.
I used these pods in my project.
pod 'RxSwift', '> 3.0'> 3.0'
pod 'RxCocoa', '
pod 'Moya', '8.0.3'
pod 'Moya/RxSwift'
pod 'Swinject', '2.0.0'
pod 'SwinjectStoryboard', '1.0.0'
pod 'R.swift'
pod 'SwiftyBeaver'
pod 'Moya-ObjectMapper'
pod 'Moya-ObjectMapper/RxSwift'
pod 'BEMCheckBox'
pod 'Alamofire', '> 4.4'> 4.0'
pod 'AlamofireObjectMapper', '
pod 'Cosmos', '~> 10.0'
pod 'Mixpanel-swift'
pod 'FacebookCore'
I also tried adding the Observable+Mapper.swift separately to the project , but still no luck.
Any help will be appreciated. Thank you
I
I am trying to post a mapped model that I am newing up myself. My model originally only had the init?(map: Map) method but I added another init() {} so I could new one up and set its values before posting it. However, when I do this I get
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write
Do I have to use the map init method? If so what do I pass it?
Here is my model
import Foundation
import ObjectMapper
public class Office: Mappable {
var id: Int = 0
var status: String?
var name: String?
var addressLine1: String?
var addressLine2: String?
var addressLine3: String?
var city: String?
var state: String?
var postalCode: String?
var country: String?
init() { }
public required init?(map: Map) { }
public func mapping(map: Map) {
id <- map["id"]
status <- map["status"]
name <- map["name"]
addressLine1 <- map["address_line1"]
addressLine2 <- map["address_line2"]
addressLine3 <- map["address_line3"]
city <- map["city"]
state <- map["state"]
postalCode <- map["postal_code"]
country <- map["country"]
}
}
And my new office
let newOffice = Office()
newOffice.name = "test"
newOffice.addressLine1 = "test"
newOffice.addressLine2 = "test"
newOffice.postalCode = "test"
Posting my office
self.provider!
.request(.postOffice(office: newOffice)) { result in
switch result {
case let .success(response):
do {
try _ = response.filterSuccessfulStatusCodes()
let office = try response.mapObject(Office.self)
success(office)
} catch {
do{
let apiError = try response.mapObject(APIError.self)
failure(apiError.friendlyDisplay())
} catch {
failure("Creating New Office Failed")
}
}
case let .failure(error):
failure("Post Office Failed")
}
}
My Task
public var task: Task {
switch self {
case let .postOffice(office):
return .requestParameters(parameters: ["office": office], encoding: JSONEncoding.default)
default:
return .requestPlain
}
}
My podfile is
pod 'RxSwift', '~> 3.0'
pod 'ObjectMapper', '-> 2.2.1'
pod 'Moya', '8.0.0-beta.5'
pod 'Moya-ObjectMapper'
pod 'Moya-ObjectMapper/RxSwift'
I got this error when pod install
[!] Unable to satisfy the following requirements:
ObjectMapper (~> 2.2.1)
required by Podfile
ObjectMapper (~> 2.2.1)
required by Podfile
ObjectMapper (= 2.2.2)
required by Podfile.lock
ObjectMapper (= 2.2.1)
required by Moya-ObjectMapper/Core (2.2)
Moya (= 8.0.0-beta.5)
required by Podfile
Moya (= 8.0.0-beta.5)
required by Podfile
Moya (= 8.0.0-beta.5)
required by Podfile.lock
Moya (= 8.0.0-beta.3)
required by Moya-ObjectMapper/Core (2.0.1)
Moya/RxSwift
required by Podfile
Moya/RxSwift
required by Podfile
Moya/RxSwift (= 8.0.0-beta.5)
required by Podfile.lock
Moya/RxSwift (~> 5.3.0)
required by Moya-ObjectMapper/RxSwift (1.1.0)
RxSwift (~> 3.0)
required by Podfile
RxSwift (~> 3.0)
required by Podfile
RxSwift (= 3.0.1)
required by Podfile.lock
RxSwift (~> 3.0)
required by Moya/RxSwift (8.0.0-beta.5)
RxSwift (~> 3.0)
required by RxCocoa (3.0.1)
RxSwift (~> 3.0)
required by RxDataSources (1.0.0)
RxSwift (= 2.0.0-beta.4)
required by Moya-ObjectMapper/RxSwift (1.0.2)
current
ss.dependency "ObjectMapper", '~> 3.0.0'
it need to be '~> 3'
Please, add suport for rxswift 2.4.
Thank you.
I see the following error:
[!] Unable to satisfy the following requirements:
RxSwift (~> 3.2)
required by Podfile
RxSwift (~> 3.0)
required by Moya/RxSwift (8.0.2)
RxSwift (= 3.1.0)
required by Moya-ObjectMapper/RxSwift (2.3)
RxSwift (~> 3.1)
required by RxCocoa (3.2.0)
Maybe the approach taken recently by the Moya is a way to fix problems of that kind.
Moya/Moya#944
The support for JSON null was added in 2.2.2. This is the change that adds it: tristanhimmelman/ObjectMapper@3f87871
How to debug when mapping to JSON?
I'm trying to use Moya-ObjectMapper with RxSwift. However when it comes to debugging it doesn't necessarily provide the best way to see the results.
I'm looking for a way to determine if my incoming JSON doesn't match my mapping or my Mapping doesn't match my JSON.
My case being the following incoming JSON:
{
"data": [
{
"id": 20,
"is_current_user_subscribed": false,
},
{
"id": 35,
"is_current_user_subscribed": false,
},
{
"id": 34,
"is_current_user_subscribed": false,
},
{
"id": 17,
"is_current_user_subscribed": false,
}
]
}
import Mapper
struct ResponseResults: Mappable{
let users: [Users]?
init(map: Mapper) throws {
try responses = map.from("data")
}
}
struct Users: Mappable{
let id: Int?
let isSubscribed: Bool?
init(map: Mapper) throws {
try id = map.from("id")
try isSubscribed = map.from("is_current_user_subscribed")
}
}
rxProvider
.request(.getUsers())
.mapObjectOptional(ResponseResults.self)
.subscribe{ event -> Void in
switch event{
case .Next(let arrayOfUsers):
print(arrayOfUsers) // <<<<<<< This is Null here
case .Error(let error):
print(error)
default:
break
}}.addDisposableTo(disposeBag)
Also, I'm wondering what is the difference between the follwing:
mapArray vs mapArrayOptional
mapObject vs mapObjectOptional
I'm open to suggestions. Thanks!
webservice with parameters input not working ,
It is directly goes out to failure
Not getting the reason,its a simple post api with input parameters, other GET Api working
case let .failure(error):
// let statusCode = response.statusCode
guard let error = error as? CustomStringConvertible else {
break ///stops here
}
}
Rxswift 3.1 has been released, the current dependence of this library and other libraries will be in conflict, please update the dependency information, thank you!
Is there already an early version supporting RxSwift 4 somewhere?
When i add the disposable bag i get Response: Received empty network response for
let disposeBag = DisposeBag()
provider.request(.createMap(location.coordinate.longitude,location.coordinate.latitude))
.mapObject(MapConfig)
.subscribe { event -> Void in
switch event {
case .Next(let repos):
print(repos)
case .Error(let error):
print(error)
default:
break
}
}.addDisposableTo(disposeBag)
}
Right now the version of ObjectMapper
is specified as ss.dependency "ObjectMapper", '~> 2.2'
in podspec. And it doesn't allow us to use version 3.0 of the library. But it's definitely compatible. So I'd propose to make dependency softer.
Not sure if it's needed to make PR for that.
After ObjectMapper 2.2.7 release the library doesn't compile anymore.
Response+ObjectMapper.swift
Error:(27, 56) initializer for conditional binding must have Optional type, not '[T]'
From #43:
A Mapper object can be created with a MapContext object but this possibility wasn't given in the mapObject() and mapArray() functions.
In the lastest ObjectMapper's version, shouldIncludesNilValues is also allowed when creating a Mapper, but I'm kinda a noob with creating pods and I wasn't able to update the dependency version to add this support too.
how can i mapObject this data {status:"ok" message:"" data: model}
the data is my model
Every dependence of this lib has Carthage support.
When using cocopods instal Moya-ObjectMapper/ReactiveCocoa got an error:
None of your spec sources contain a spec satisfying the dependency: Moya-ObjectMapper/ReactiveCocoa (from
https://github.com/ivanbruel/Moya-ObjectMapper`)`.
Then I pod search it Moya-ObjectMapper, found out only Moya-ObjectMapper/RxSwift available.
So, could please release the Moya-ObjectMapper/ReactiveCocoa? Cuz I am using ReactiveCocoa, not RxSwift.
I have two mappable classes: "Hospital" and "ErrorAPI"
How can i "mapObject()" my custom error? I mean, if the server responds with an error, then I want to process it as a mappable object.
JSON error
{
"status" : "401",
"errorsMessage" : "abc"
...
}
My code:
let provider = RxMoyaProvider<APIClient>()
requestHospitalButton.rx_tap
.withLatestFrom(hospitalCode)
.flatMapLatest { [unowned self] code in
self.provider.request(.Hospital(code: code))
}
.mapObject(Hospital)
.subscribe { [unowned self] event in
switch event {
case .Next(let hospital):
// success (Hospital)
case .Error(let error):
// error (Now it string, but i need obj ErrorAPI as Hospital in case .Next)
default: break
}
}
.addDisposableTo(rx_disposeBag)
I'm new to these libraries. Thanks for any help.
When you try to map the JSON to an object that conforms to ImmutableMappable, you get the following error.
assertion failed: BaseMappable should not be implemented directly. Please implement Mappable, StaticMappable or ImmutableMappable:
Is there a way to get around this?
Kind regards,
Frederik
[!] CocoaPods could not find compatible versions for pod "Moya":
In Podfile:
Moya-ObjectMapper/RxSwift (~ > 2.7) was resolved to 2.7, which depends on
Moya-ObjectMapper/Core (= 2.7) was resolved to 2.7, which depends on
Moya (~ > 11)
Specs satisfying the Moya (~> 11)
dependency were found, but they required a higher minimum deployment target.
when I add
pod 'Moya-ObjectMapper/RxSwift', :git => 'https://github.com/ivanbruel/Moya-ObjectMapper'
to my Podfile and install it return
Specs satisfying the
Moya-ObjectMapper/RxSwift (from https://github.com/ivanbruel/Moya-ObjectMapper
) dependency were found, but they required a higher minimum deployment target.
Is there any way I can set the deployment target 8.0 ?
Hi,
working with XCode 7.3 requires RxSwift 2.3.1 for an compilation error regarding XCTests
but ObjectMapper requires RxSwift 2.2 on the pod file
can you please update the requirements?
Best,
Idan
Hello, I'm trying to use Moya-ObjectMapper/RxSwift with the following pods:
When trying to install the pods, I get incompatible version for the Pod:
[!] CocoaPods could not find compatible versions for pod "Moya":
In Podfile:
Moya-ObjectMapper/RxSwift was resolved to 2.5, which depends on
Moya-ObjectMapper/Core (= 2.5) was resolved to 2.5, which depends on
Moya (~> 10.0.0)
Specs satisfying the `Moya (~> 10.0.0)` dependency were found, but they required a higher minimum deployment target.
CocoaPods could not find compatible versions for pod "ObjectMapper":
In Podfile:
Moya-ObjectMapper/RxSwift was resolved to 2.0.1, which depends on
Moya-ObjectMapper/Core (= 2.0.1) was resolved to 2.0.1, which depends on
ObjectMapper (= 2.2.0)
ObjectMapper (~> 3.0)
CocoaPods could not find compatible versions for pod "RxSwift":
In Podfile:
Moya-ObjectMapper/RxSwift was resolved to 1.0.2, which depends on
RxSwift (= 2.0.0-beta.4)
Moya/RxSwift (~> 11.0) was resolved to 11.0.2, which depends on
RxSwift (~> 4.0)
What version of each pod should I use to make it work'?
Thanks
Could you please provide update for new dependencies?
[!] Unable to satisfy the following requirements:
RxSwift (= 3.0.0-beta.1)
required by Podfile.lock
RxSwift (~> 3.0.0-beta.1)
required by RxCocoa (3.0.0-beta.1)
RxSwift (= 3.0.0-beta.1)
required by Moya/RxSwift (7.0.0)
RxSwift (= 2.0.0-beta.4)
required by Moya-ObjectMapper/RxSwift (1.0.2)
In v2.5 Moya/RxSwift was listed as a dependency of RxSwift subspec :
s.subspec "RxSwift" do |ss|
ss.source_files = "Source/RxSwift/*.swift"
ss.dependency "Moya/RxSwift"
ss.dependency "Moya-ObjectMapper/Core"
ss.dependency "RxSwift", '~> 4.0.0'
end
Now in v2.6 Moya/RxSwift has been removed :
s.subspec "RxSwift" do |ss|
ss.source_files = "Source/RxSwift/*.swift"
ss.dependency "Moya-ObjectMapper/Core"
ss.dependency "RxSwift", '~> 4.1'
end
Now we have to add Moya/RxSwift to podfile in order to incorporate the dependency correctly. Is this an oversight? Why was it removed?
NOTE: In the "ReactiveSwift" subspec, there is still the dependency on Moya/ReactiveSwift in v2.6 :
s.subspec "ReactiveSwift" do |ss|
ss.source_files = "Source/ReactiveSwift/*.swift"
ss.dependency "Moya-ObjectMapper/Core"
ss.dependency "Moya/ReactiveSwift", '11'
ss.dependency "ReactiveSwift", "~> 3"
end
Example gives several errors.
.mapArray(Repository) gives "Expected member name or constructor call after type name"
GitHubProvider.request(.userRepositories(username))
.mapArray(Repository)
.subscribe { event -> Void in
switch event {
case .next(let repos):
self.repos = repos
case .error(let error):
print(error)
default:
break
}
}.addDisposableTo(disposeBag)
Do you have a working example for implementing this together with RxSwift? Would be amazing if you could make one. :)
Hi, it works well when I use it with RxSwift, but when I try to do it without Rx here the problem comes.
if let repos = try response.mapArray(Repository)
but the compiler give me an error:
Argument passed to call that takes no arguments
the generic function:
public func mapArray<T: Mappable>() throws -> [T]
how to fix it? Or I did it in a wrong way?
I'm trying to map an object using RxSwift with a keypath like you would do with ObjectMapper.
I tried with .mapString first but since it returns a Single<String> I can't chain .mapObject which expects a Single<Response>.
Should I implement an extension by myself or am I missing something?
Hello,
when I tried to use the code in the example
if let repos = try response.mapArray(Repository) {
it gives me this message
Value of type 'Response' has no member 'mapArray'
thanks,
Hi,
Recently Moya updated to version 7.0.0 so it would be cool to update this library to support that version.
I tried to do this myself, but haven't been able to satisfy the pod install for the sample project using an updated podspec. I was seeing this error:
[!] Unable to satisfy the following requirements:
- `Moya/ReactiveCocoa (~> 7.0)` required by `Moya-ObjectMapper/ReactiveCocoa (1.3)`
Happy to submit a PR if anyone has any ideas about why this isn't working
User can retry button tap on failure alert from server. So webservice can get called again
Hi. This seems like a great tool, but for some reason I'm not able to get it to work. It would be great to have a demo project to take a look at (mainly for the RxSwift binding)
For RxSwift .. we don't need to disposeBag?
Hi,
It seems that Observable+ObjectMapper.swift is not being included when I install Moya-ObjectMapper when installing using cocoapods. Below you see my pods
pod 'RxCocoa', '~> 3.0'
pod 'Swinject', '~> 2.1.1'
pod 'SnapKit', '~> 3.2.0'
pod 'Reusable', '~> 4.0'
pod 'SideMenu', '~> 2.3.4'
pod 'p2.OAuth2', '~> 4.0.1'
pod 'Moya/RxSwift'
pod 'Moya-ObjectMapper/RxSwift'
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.