How to append object in Mappable class(Model). iOS swift - ios

In my app, I'm using Alamofire-ObjectMapper.
I have a [OrderDetailSecond]. now i want to use for loop for this array and when isRxMedicine == 1 i want to add that object in any array so i can display that in my UITableView.
here is my code
this is my model
class OrderDetailSecond: Mappable {
var id : Int?
var isRxMedicine : Int?
var medicineTypeId : String?
var name : String?
var orderId : String?
var price : String?
var quentity : Int?
var strength : String?
required init?(_ map: Map){
}
func mapping(map: Map) {
id <- map["id"]
isRxMedicine <- map["is_rx_medicine"]
medicineTypeId <- map["medicine_type_id"]
name <- map["name"]
orderId <- map["order_id"]
price <- map["price"]
quentity <- map["qty"]
strength <- map["strengh"]
}
}
now here i am trying to add objects in new element
if let Rx_OrderDetail = self.orderdetailInstance, Rx_detail = Rx_OrderDetail.result{
let detailArray = Rx_detail[0].orederDetail
if let orderdata = detailArray
{
for RxDataFilter in orderdata
{
if (RxDataFilter.isRxMedicine == 1)
{
array?.append(RxDataFilter)
}
}
elementConunt = orderdata.count
}
return elementConunt
}
but its not working
Note: orderdata is in form [OrderDetailSecond]

Related

ios : memory file operator bool crash

I am using realmswift in my project, so as per apple guidelines I converted whole project into swift 4.2 and all pod libraries into latest version. Project is converted successfully but I get crash everytime when I run project.
I have uploaded screenshot for better understanding.
Now here is my model for inserting value in database
class SyncProductModel: Object, Mappable {
#objc dynamic var id: String?
#objc dynamic var productType : Int = 0
#objc dynamic var name: String?
#objc dynamic var category :String?
#objc dynamic var sku : String?
#objc dynamic var baseMOQ : Double = 0.0
#objc dynamic var isActive : Bool = false
#objc dynamic var isFavourite : Bool = false
#objc dynamic var createdAt : String?
#objc dynamic var updatedAt : String?
#objc dynamic var uom : String?
#objc dynamic var productDesc : String?
#objc dynamic var retailUOM : String?
#objc dynamic var isInCart : Bool = false
var isSelecetd = false
var attachments = List<AttachmentModel>()
var inventory = List<SyncInventoryModel>()
var inventoryModel : SyncInventoryModel?
// var tags = List<tags>()
// var baseProperties = List<baseProperties>()
required convenience init?(map: Map) {
self.init()
}
override class func primaryKey() -> String? {
return "id"
}
func mapping(map: Map) {
id <- map["id"]
productType <- map["type"]
name <- map["name"]
category <- map["category"]
sku <- map["sku"]
var baseQty : Any?
baseQty <- map["baseMOQ"]
baseMOQ = Utilities.getDoubleValue(value: baseQty)
isActive <- map["isActive"]
createdAt <- map["createdAt"]
updatedAt <- map["updatedAt"]
uom <- map["uom"]
productDesc <- map["description"]
retailUOM <- map["retailUOM"]
attachments <- (map["attachments"], ListTransform<AttachmentModel>())
// tags <- (map["attachments"], ListTransform<tags>())
// baseProperties <- (map["baseProperties"], ListTransform<baseProperties>())
}
Here is my code for inserting value into db
for obj in masterProduct
{
if self.realm.isInWriteTransaction {
self.realm.add(obj, update: true)
}
else {
try! self.realm.write {
// Here My application get crashed.
self.realm.add(obj, update: true)
}
}
}
But everytime application get crashed. Please help me I stuck here.
Any help would be appreciated.

Alamofire ObjectMapper - Extract common fields from all models and map them

There are few fields common in all models returned by api. But they don't come as a separate object. They are there among other fields.
Example of two models :
Event :
[
{
"event":{
"id":3,
"company_id":18,
"archived":false,
"created_by":229,
"updated_by":229,
"owner_id":229,
"subject":"",
"start_date":null,
"end_date":null,
"name":null,
"name_class_name":"",
"related_to":null,
"related_to_class_name":"",
"status":"",
"created_at":"2018-05-07T01:59:38.921-04:00",
"updated_at":"2018-05-07T01:59:38.921-04:00",
"custom_nf":false
}
}
]
Opportunity :
[
{
"opportunity":{
"id":4,
"company_id":18,
"archived":false,
"created_by":229,
"updated_by":229,
"owner_id":229,
"account_id":null,
"name":"",
"lead_source":"",
"amount":null,
"close_date":null,
"probability":null,
"stage":"",
"created_at":"2018-05-07T01:49:55.441-04:00",
"updated_at":"2018-05-07T01:49:55.441-04:00"
}
}
]
As shown, initial fields are common in both (all) models - id, company_id, archived, created_by and so on.
There are tons of projects I have worked with ObjectMapper but didn't encounter this before. I am fully aware of handling nested models, but this is a different case.
Though I can easily handle this by repeating all common fields in all models. But this doesn't sound good.
What I am looking is a way I can create a separate model class with all common fields. But the question is - how would I map that with api response using ObjectMapper ?
Just as an example, this is how I have created Opportunity model :
import UIKit
import ObjectMapper
class Opportunity: NSObject, Mappable {
var id: Int?
var companyId: Int?
var archived: Int?
var createdBy: Int?
var updatedBy: Int?
var ownerId: Int?
var accountId: Int?
var name: String?
var leadSource: String?
var amount: String?
var closeDate: String?
var probability: String?
var stage: String?
var createdAt: String?
var updatedAt: String?
required init?(map: Map) {
}
func mapping(map: Map) {
self.id <- map["id"]
self.companyId <- map["company_id"]
self.archived <- map["archived"]
self.createdBy <- map["created_by"]
self.updatedBy <- map["updated_by"]
self.ownerId <- map["owner_id"]
self.accountId <- map["account_id"]
self.name <- map["name"]
self.leadSource <- map["lead_source"]
self.amount <- map["amount"]
self.closeDate <- map["close_date"]
self.probability <- map["probability"]
self.stage <- map["stage"]
self.createdAt <- map["created_at"]
self.updatedAt <- map["updated_at"]
}
}
You can create base entity and put there common fields.
Example:
import UIKit
import ObjectMapper
class BaseEntity: NSObject, Mappable {
var id: Int?
var companyId: Int?
var archived: Int?
var createdBy: Int?
var updatedBy: Int?
var ownerId: Int?
var name: String?
var createdAt: String?
var updatedAt: String?
required init?(map: Map) {
}
func mapping(map: Map) {
self.id <- map["id"]
self.companyId <- map["company_id"]
self.archived <- map["archived"]
self.createdBy <- map["created_by"]
self.updatedBy <- map["updated_by"]
self.ownerId <- map["owner_id"]
self.name <- map["name"]
self.createdAt <- map["created_at"]
self.updatedAt <- map["updated_at"]
}
}
class Opportunity: BaseEntity {
var accountId: Int?
var leadSource: String?
var amount: String?
var closeDate: String?
var probability: String?
var stage: String?
required init?(map: Map) {
super.init(map: map)
}
override func mapping(map: Map) {
super.mapping(map: map)
self.accountId <- map["account_id"]
self.leadSource <- map["lead_source"]
self.amount <- map["amount"]
self.closeDate <- map["close_date"]
self.probability <- map["probability"]
self.stage <- map["stage"]
}
}
Note: BaseEntity isn't good name, I think you can give better name.

Json parsing Issue using objectmapper library in swift

I am facing issue with parsing response from server side. I get response in this format
1.)
For first image my model class is working fine. In this I don't null
2.)
For second image response my Model class is not working it's giving nil after parsing.In this I get null in array
My Model class for my api response is this
class GetTodayMyKpiResponse: Mappable{
var status: String?
var myKpiMonth: MyKpiMonthResponse?
var myKpiWeek: MyKpiWeekResponse?
required init?(map: Map){
}
func mapping(map: Map) {
status <- map["status"]
myKpiMonth <- map["myKpiMonth"]
myKpiWeek <- map["myKpiWeek"]
}
}
class MyKpiMonthResponse: Mappable{
var myKpiMonthYear: Double?
var myKpiMonthDetailList: [MyKpiMonthDetailResponse]?
var myKpiMonthList: [MyKpiMonthListReponse]?
required init?(map: Map) {
}
func mapping(map: Map) {
myKpiMonthYear <- map["myKpiMonthYear"]
myKpiMonthDetailList <- map["myKpiMonthDetail"]
myKpiMonthList <- map["myKpiMonthList"]
}
}
class MyKpiMonthDetailResponse: Mappable{
var myKpiMonthDetailOutletCode: String?
var myKpiMonthDetailUnitTiers: [String]?
var myKpiMonthDetailTargetUnits: [String]?
var myKpiMonthDetailBonusIncentive: Double?
var myKpiMonthDetailOutletName: String?
var myKpiMonthDetailModelName: [String]?
var myKpiMonthDetailMonth: String?
var myKpiMonthDetailType: Double?
required init?(map: Map) {
}
func mapping(map: Map) {
myKpiMonthDetailOutletCode <- map["myKpiMonthDetailOutletCode"]
myKpiMonthDetailUnitTiers <- map["myKpiMonthDetailUnitTiers"]
myKpiMonthDetailTargetUnits <- map["myKpiMonthDetailTargetUnits"]
myKpiMonthDetailBonusIncentive <- map["myKpiMonthDetailBonusIncentive"]
myKpiMonthDetailOutletName <- map["myKpiMonthDetailOutletName"]
myKpiMonthDetailModelName <- map["myKpiMonthDetailModelName"]
myKpiMonthDetailMonth <- map["myKpiMonthDetailMonth"]
myKpiMonthDetailType <- map["myKpiMonthDetailType"]
}
}
class MyKpiMonthListReponse: Mappable {
var myKpiMonthMaxUnit: Double?
var myKpiMonthDate: String?
var myKpiMonthBonusAmount: Double?
var myKpiMonthActivatedUnit: Double?
var myKpiMonthMinUnit: Double?
var myKpiMonthCurrentUnit: Double?
var myKpiMonthBonusStatus: String?
var myKpiMonthOutletName: String?
var myKpiMonthOutletAddress: String?
required init?(map: Map) {
}
func mapping(map: Map) {
myKpiMonthMaxUnit <- map["myKpiMonthMaxUnit"]
myKpiMonthDate <- map["myKpiMonthDate"]
myKpiMonthBonusAmount <- map["myKpiMonthBonusAmount"]
myKpiMonthActivatedUnit <- map["myKpiMonthActivatedUnit"]
myKpiMonthMinUnit <- map["myKpiMonthMinUnit"]
myKpiMonthCurrentUnit <- map["myKpiMonthCurrentUnit"]
myKpiMonthBonusStatus <- map["myKpiMonthBonusStatus"]
myKpiMonthOutletName <- map["myKpiMonthOutletName"]
myKpiMonthOutletAddress <- map["myKpiMonthOutletAddress"]
}
}
class MyKpiWeekResponse: Mappable{
var myKpiWeekDetail: [MyKpiWeekDetailResponse]?
var myKpiWeekList: [MyKpiWeekListResponse]?
var myKpiWeekYear: Double?
var myKpiWeekMonth: Double?
required init?(map: Map) {
}
func mapping(map: Map) {
myKpiWeekDetail <- map["myKpiWeekDetail"]
myKpiWeekList <- map["myKpiWeekList"]
myKpiWeekYear <- map["myKpiWeekYear"]
myKpiWeekMonth <- map["myKpiWeekMonth"]
}
}
class MyKpiWeekDetailResponse: Mappable{
var myKpiWeekDetailEndDate: String?
var myKpiWeekDetailUnitTiers: [String]?
var myKpiWeekDetailOutletName: String?
var myKpiWeekDetailStartDate: String?
var myKpiWeekDetailType: Double?
var myKpiWeekDetailModelName: [String]?
var myKpiWeekDetailTypeOfReward: String?
var myKpiWeekDetailOutletCode: String?
var myKpiWeekDetailTargetUnits: [String]?
required init?(map: Map) {
}
func mapping(map: Map) {
myKpiWeekDetailEndDate <- map["myKpiWeekDetailEndDate"]
myKpiWeekDetailUnitTiers <- map["myKpiWeekDetailUnitTiers"]
myKpiWeekDetailOutletName <- map["myKpiWeekDetailOutletName"]
myKpiWeekDetailStartDate <- map["myKpiWeekDetailStartDate"]
myKpiWeekDetailType <- map["myKpiWeekDetailType"]
myKpiWeekDetailModelName <- map["myKpiWeekDetailModelName"]
myKpiWeekDetailTypeOfReward <- map["myKpiWeekDetailTypeOfReward"]
myKpiWeekDetailOutletCode <- map["myKpiWeekDetailOutletCode"]
myKpiWeekDetailTargetUnits <- map["myKpiWeekDetailTargetUnits"]
}
}
class MyKpiWeekListResponse: Mappable {
var myKpiWeekBonusStatus: String?
var myKpiWeekEndDate: String?
var myKpiWeekActivatedUnit: Double?
var myKpiWeekStartDate: String?
var myKpiWeekMinUnit: Double?
var myKpiWeekCurrentUnit: Double?
var myKpiWeekOutletName: String?
var myKpiWeekTypeOfReward: String?
var myKpiWeekOutletAddress: String?
var myKpiWeekMaxUnit: Double?
required init?(map: Map) {
}
func mapping(map: Map) {
myKpiWeekBonusStatus <- map["myKpiWeekBonusStatus"]
myKpiWeekEndDate <- map["myKpiWeekEndDate"]
myKpiWeekActivatedUnit <- map["myKpiWeekActivatedUnit"]
myKpiWeekStartDate <- map["myKpiWeekStartDate"]
myKpiWeekMinUnit <- map["myKpiWeekMinUnit"]
myKpiWeekCurrentUnit <- map["myKpiWeekCurrentUnit"]
myKpiWeekOutletName <- map["myKpiWeekOutletName"]
myKpiWeekTypeOfReward <- map["myKpiWeekTypeOfReward"]
myKpiWeekOutletAddress <- map["myKpiWeekOutletAddress"]
myKpiWeekMaxUnit <- map["myKpiWeekMaxUnit"]
}
}
If there is no data available then send empty array not null. Even in myKpiMonthList doesn't contain null array. There is no logic that null value in array at index 2.
You can send empty string or empty array even. Still there is no any logic for the null value.
Either handle all null value from server side else it always crash.

AlamofireObjectMapper how to map object?

This is the reponse which i got from api
{
Message = "email verification link has been sent to your email. please verify your account.";
Result = {
"V002_vendors_type" = "<null>";
"V003_pharmacy" = (
);
"V010_subscription" = "<null>";
"attempt_date" = "<null>";
created = "2016-04-27T12:26:04.5809108+00:00";
email = "i9#gmail.com";
"first_name" = jack;
id = 10180;
"is_lock" = 0;
"last_name" = "<null>";
mobile = 9999999999;
password = e10adc3949ba59abbe56e057f20f883e;
"profile_Image" = "<null>";
status = PV;
subscription = 1;
updated = "2016-04-27T12:26:04.5809108+00:00";
"vendor_type_id" = 1;
};
Status = 1;}
now i am mapping this response by alamofireObjectMapper
here is my code
func pharmacySignUp()
{
let url = "http://\(basicURL)vendor_signup"
let param :[String : AnyObject] =
[
"email" : txtemail.text!,
"password" : txtpassword.text!,
"mobile" : txtmobile.text!,
"first_name" : txtname.text!
]
Alamofire.request(.POST, url, parameters: param, encoding: .JSON).responseObject { (response:Response<signupVarificationCode, NSError>) in
print(response.result.value)
let signupVarificationCode = response.result.value
print(signupVarificationCode)
print(signupVarificationCode!.Message)
print(signupVarificationCode?.Status)
print(signupVarificationCode?.result)
if let threedayForecast = signupVarificationCode?.result {
for ResultNew in threedayForecast {
print(ResultNew)
}
}
}
and these are my class in which i am saving values
class signupVarificationCode: Mappable {
var Message : String?
var Status : String?
var result:[String:AnyObject]?
required init?(_ map: Map){
}
func mapping(map: Map) {
Message <- map["Message"]
Status <- map["Status"]
result <- map["Result"]
}
}
class Resultnew: Mappable
{
var lastName : String?
var isLock : String?
var mobile : String?
var id: String?
var attemptDate : String?
var Created : String?
var Updated : String?
var Subscription: String?
var vendor_type : String?
var profileimage : String?
var pharmacy : String?
var vsbuscription : String?
var email: String?
var status : String?
var vendor_typeId : String?
var FirstName : String?
var Password: String?
required init?(_ map: Map){
}
func mapping(map: Map) {
lastName <- map["last_name"]
mobile <- map["mobile"]
id <- map["id"]
isLock <- map["is_lock"]
attemptDate <- map["attempt_date"]
Created <- map["created"]
Updated <- map["updated"]
Subscription <- map["subscription"]
vendor_type <- map["V002_vendors_type"]
profileimage <- map["profile_Image"]
pharmacy <- map["V003_pharmacy"]
vsbuscription <- map["V010_subscription"]
email <- map["email"]
status <- map["status"]
vendor_typeId <- map["vendor_type_id"]
FirstName <- map["first_name"]
Password <- map["password"]
}
}
Here i am getting values in my function as
for ResultNew in threedayForecast {
print(ResultNew)
}
but these vales are coming like this
("last_name", <null>)
("mobile", 123456)
("is_lock", 0)
("attempt_date", <null>)
("created", 2016-04-27T12:32:20.6046072+00:00)
("updated", 2016-04-27T12:32:20.6046072+00:00)
("subscription", 1)
("V002_vendors_type", <null>)
("profile_Image", <null>)
("V003_pharmacy", [])
("V010_subscription", <null>)
("email", i10#gmail.com)
("status", PV)
("vendor_type_id", 1)
("first_name", jack)
("id", 10182)
("password", e10adc3949ba59abbe56e057f20f883e)
but i cannot access is like this
print(ResultNew.mobile)
so how acn i access perticular value which i want to access.like i want to only password among these so how can do this?
You specified that the result should be a dictionary ([String:AnyObject]) so you got a dictionary. Try changing it to this :
var Message : String?
var Status : String?
var result:Resultnew? // <-- this line

ObjectMapper - initialize object IOS

Simple thing that is giving me a headache - how to initialize an object that conforms to mappable protocol, without any JSON yet.
What I would like to do, is simply initialise empty User object in code like this:
let user = User()
however that gives me error:
"missing argument for parameter #1 in call"
I was able to do it in version 0.14 with swift 1.2, but now it doesnt work. Do you guys know how to do it now in swift 2 and new Object Mapper ? (I know how to initialize it with json etc, I just want to initialize that object for other purposes and I cant figure out how)
class User: Mappable {
var username: String?
var age: Int?
var weight: Double!
var array: [AnyObject]?
var dictionary: [String : AnyObject] = [:]
var bestFriend: User? // Nested User object
var friends: [User]? // Array of Users
var birthday: NSDate?
required init?(_ map: Map) {
}
// Mappable
func mapping(map: Map) {
username <- map["username"]
age <- map["age"]
weight <- map["weight"]
array <- map["arr"]
dictionary <- map["dict"]
bestFriend <- map["best_friend"]
friends <- map["friends"]
birthday <- (map["birthday"], DateTransform())
}
}
please help!
The following should work:
class User: NSObject, Mappable {
var username: String?
var age: Int?
var weight: Double!
var array: [AnyObject]?
var dictionary: [String : AnyObject] = [:]
var bestFriend: User? // Nested User object
var friends: [User]? // Array of Users
var birthday: NSDate?
override init() {
super.init()
}
convenience required init?(_ map: Map) {
self.init()
}
// Mappable
func mapping(map: Map) {
username <- map["username"]
age <- map["age"]
weight <- map["weight"]
array <- map["arr"]
dictionary <- map["dict"]
bestFriend <- map["best_friend"]
friends <- map["friends"]
birthday <- (map["birthday"], DateTransform())
}
}
Fixed version of above answer:
init() {}
required convenience init?(_ map: Map) { self.init() }

Resources