1

I want to save custom whole object to NSUserDefault ?

This is my custom object ..

import UIKit
import ObjectMapper

class SAuthModel: Mappable {

    var status: Int?
    var message: String?
    var result: SResultModel?
    var authToken: String?

    required init?(map: Map) {

    }

    func mapping(map: Map) {
        status       <- map["code"]
        message      <- map["message"]
        authToken    <- map["authToken"]
        result       <- map["data"]
    }
}

class SResultModel: Mappable {

    var name, email, countryCode, mobile, isNotification, promoCode, imageURL, _id, isMobileVerify,otp,faceBookId,googleId,stripeCustId,isProfileSet,created:String?

    required init?(map: Map) {

    }

    func mapping(map: Map) {
        name             <- map["name"]
        email            <- map["email"]
        countryCode      <- map["countryCode"]
        mobile           <- map["mobile"]
        isNotification   <- map["isNotification"]
        promoCode        <- map["promoCode"]
        imageURL         <- map["imageURL"]
        _id              <- map["_id"]
        isMobileVerify   <- map["isMobileVerify"]
        otp              <- map["otp"]
        faceBookId       <- map["faceBookId"]
        googleId         <- map["googleId"]
        stripeCustId     <- map["stripeCustId"]
        isProfileSet     <- map["isProfileSet"]


    }
}

 SAuthService().logInService(parameters:userModel.toJSON()).done{(response) -> Void  in
            SVProgressHUD.dismiss()

            if response.status == 210 {
                guard let responseMessage = response.message else {
                    return
                }
                HHelper.showAlert(responseMessage)
            } else if response.status == 200 {
                USER_DEFAULTS.set(response.result, forKey:ConstantTexts.resultData.localizedString)

                kAppDelegate.pushToHomeViewContoller()
            }
}

Im trying to save custom model object in USER_DEFAULTS but its keep on crashing .

M Reza
  • 18,350
  • 14
  • 66
  • 71

1 Answers1

0

the proper way to store to UserDefaults is described in this article

var userDefaults = UserDefaults.standard
let encodedData: Data = NSKeyedArchiver.archivedData(withRootObject: teams)
userDefaults.set(encodedData, forKey: "teams")

basically you have to supply it a Data object...