App Crashing with error: generic parameter 'T' could not be inferred - swift

I'm trying to get custom object which is hashable from UserDefault.
My custom model is defined below:
class WorkerProfileResponse: Mappable, Hashable{
static func == (lhs: WorkerProfileResponse, rhs: WorkerProfileResponse) -> Bool {
return lhs.id == rhs.id
}
var hashValue: Int{
return self.id!
}
var id, loginStatus, lastLogin, lastActive: Int?
var username, email, mobileNumber: String?
var userCategories: [String]?
var userSubCategories: [String]?
var biometricToken: String?
var accessToken: AccessToken?
var userStatus: UserStatus?
var userProfile: UserProfile?
required init(map: Map) {
}
func mapping(map: Map) {
id <- map["id"]
loginStatus <- map["is_logged_in"]
lastLogin <- map["last_login"]
lastActive <- map["last_active"]
biometricToken <- map["biometricToken"]
username <- map["username"]
email <- map["email"]
mobileNumber <- map["mobile_number"]
accessToken <- map["accessToken"]
userStatus <- map["userStatus"]
userCategories <- map["userCategories"]
userSubCategories <- map["userSubCategories"]
userProfile <- map["userProfile"]
}
}
My userdefault method is:
class func getModel<T: Hashable>(key: String) -> T {
let decoded = UserDefaults.standard.data(forKey: key)
let decodedModel = NSKeyedUnarchiver.unarchiveObject(with: decoded!) as! T
return decodedModel
}
And I'm calling it like this:
UserDefault.getModel(key: "workerProfile")
App is crashing when I'm calling this method I don't understand the reason, error is:
error: generic parameter 'T' could not be inferred

I'm answering my own question, if it helps anyone in the future.
It was crashing while decoding because there was no value present in userdefault.
This line had the issue because of force casting:
let decodedModel = NSKeyedUnarchiver.unarchiveObject(with: decoded!) as! T
I've changes this method:
class func getModel<T: Hashable>(key: String) -> T {
let decoded = UserDefaults.standard.data(forKey: key)
let decodedModel = NSKeyedUnarchiver.unarchiveObject(with: decoded!) as! T
return decodedModel
}
To this:
class func getModel<T: Hashable>(key: String) -> T? {
let decoded = UserDefaults.standard.data(forKey: key)
if decoded != nil{
let decodedModel = NSKeyedUnarchiver.unarchiveObject(with: decoded!) as! T
return decodedModel
}
else
{
return nil
}
}

Related

Convert object mapper model class to json string in swift

class LeadsEntity: NSObject, Mappable {
var name: String?
var mobile: String?
var address: String?
var coords: String?
var stime: String?
override init() {}
required init?(map: Map) {}
func mapping(map: Map) {
name <- map["name"]
mobile <- map["mobile"]
address <- map["address"]
coords <- map["coords"]
stime <- map["stime"]
}
}
I am using this method to convert model to json string
func json(from object: Any) -> String? {
let JSONString = (object as! [LeadsEntity]).toJSONString(prettyPrint: true)?.replacingOccurrences(of: "\n", with: "").replacingOccurrences(of: " ", with: "")
return JSONString
}
but it converts like this
I am not able to remove \ and I also tried to remove by .replacingOccurrences(of: "\", with: "", options: NSString.CompareOptions.literal, range:nil) but no success. Thanks in advance.
Give him the model here (type: T.self) and put the Data here (from: data)
do {
let decoded = self.decodeJSON(type: T.self, from: data)
} catch {}
func decodeJSON<T: Decodable>(type: T.Type, from: Data?) -> T? {
let decoder = JSONDecoder()
guard let data = from else { return nil }
do {
let objects = try decoder.decode(type.self, from: data)
return objects
} catch let jsonError {
print("Failed to decode response JSON", jsonError)
return nil
}
}

Get 'NSInvalidArgumentException' 'Attempt to insert non-property list object when saving class type array to UserDefaults [duplicate]

I have a simple object which conforms to the NSCoding protocol.
import Foundation
class JobCategory: NSObject, NSCoding {
var id: Int
var name: String
var URLString: String
init(id: Int, name: String, URLString: String) {
self.id = id
self.name = name
self.URLString = URLString
}
// MARK: - NSCoding
required init(coder aDecoder: NSCoder) {
id = aDecoder.decodeObject(forKey: "id") as? Int ?? aDecoder.decodeInteger(forKey: "id")
name = aDecoder.decodeObject(forKey: "name") as! String
URLString = aDecoder.decodeObject(forKey: "URLString") as! String
}
func encode(with aCoder: NSCoder) {
aCoder.encode(id, forKey: "id")
aCoder.encode(name, forKey: "name")
aCoder.encode(URLString, forKey: "URLString")
}
}
I'm trying to save an instance of it in UserDefaults but it keeps failing with the following error.
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to insert non-property list object for key jobCategory'
This is the code where I'm saving in UserDefaults.
enum UserDefaultsKeys: String {
case jobCategory
}
class ViewController: UIViewController {
#IBAction func didTapSaveButton(_ sender: UIButton) {
let category = JobCategory(id: 1, name: "Test Category", URLString: "http://www.example-job.com")
let userDefaults = UserDefaults.standard
userDefaults.set(category, forKey: UserDefaultsKeys.jobCategory.rawValue)
userDefaults.synchronize()
}
}
I replaced the enum value to key with a normal string but the same error still occurs. Any idea what's causing this?
You need to create Data instance from your JobCategory model using JSONEncoder and store that Data instance in UserDefaults and later decode using JSONDecoder.
struct JobCategory: Codable {
let id: Int
let name: String
}
// To store in UserDefaults
if let encoded = try? JSONEncoder().encode(category) {
UserDefaults.standard.set(encoded, forKey: UserDefaultsKeys.jobCategory.rawValue)
}
// Retrieve from UserDefaults
if let data = UserDefaults.standard.object(forKey: UserDefaultsKeys.jobCategory.rawValue) as? Data,
let category = try? JSONDecoder().decode(JobCategory.self, from: data) {
print(category.name)
}
Old Answer
You need to create Data instance from your JobCategory instance using archivedData(withRootObject:) and store that Data instance in UserDefaults and later unarchive using unarchiveTopLevelObjectWithData(_:), So try like this.
For Storing data in UserDefaults
let category = JobCategory(id: 1, name: "Test Category", URLString: "http://www.example-job.com")
let encodedData = NSKeyedArchiver.archivedData(withRootObject: category, requiringSecureCoding: false)
let userDefaults = UserDefaults.standard
userDefaults.set(encodedData, forKey: UserDefaultsKeys.jobCategory.rawValue)
For retrieving data from UserDefaults
let decoded = UserDefaults.standard.object(forKey: UserDefaultsKeys.jobCategory.rawValue) as! Data
let decodedTeams = NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(decoded) as! JobCategory
print(decodedTeams.name)
Update Swift 4, Xcode 10
I have written a struct around it for easy access.
//set, get & remove User own profile in cache
struct UserProfileCache {
static let key = "userProfileCache"
static func save(_ value: Profile!) {
UserDefaults.standard.set(try? PropertyListEncoder().encode(value), forKey: key)
}
static func get() -> Profile! {
var userData: Profile!
if let data = UserDefaults.standard.value(forKey: key) as? Data {
userData = try? PropertyListDecoder().decode(Profile.self, from: data)
return userData!
} else {
return userData
}
}
static func remove() {
UserDefaults.standard.removeObject(forKey: key)
}
}
Profile is a Json encoded object.
struct Profile: Codable {
let id: Int!
let firstName: String
let dob: String!
}
Usage:
//save details in user defaults...
UserProfileCache.save(profileDetails)
Hope that helps!!!
Thanks
Swift save Codable object to UserDefault with #propertyWrapper
#propertyWrapper
struct UserDefault<T: Codable> {
let key: String
let defaultValue: T
init(_ key: String, defaultValue: T) {
self.key = key
self.defaultValue = defaultValue
}
var wrappedValue: T {
get {
if let data = UserDefaults.standard.object(forKey: key) as? Data,
let user = try? JSONDecoder().decode(T.self, from: data) {
return user
}
return defaultValue
}
set {
if let encoded = try? JSONEncoder().encode(newValue) {
UserDefaults.standard.set(encoded, forKey: key)
}
}
}
}
enum GlobalSettings {
#UserDefault("user", defaultValue: User(name:"",pass:"")) static var user: User
}
Example User model confirm Codable
struct User:Codable {
let name:String
let pass:String
}
How to use it
//Set value
GlobalSettings.user = User(name: "Ahmed", pass: "Ahmed")
//GetValue
print(GlobalSettings.user)
Save dictionary Into userdefault
let data = NSKeyedArchiver.archivedData(withRootObject: DictionaryData)
UserDefaults.standard.set(data, forKey: kUserData)
Retrieving the dictionary
let outData = UserDefaults.standard.data(forKey: kUserData)
let dict = NSKeyedUnarchiver.unarchiveObject(with: outData!) as! NSDictionary
Based on Harjot Singh answer. I've used like this:
struct AppData {
static var myObject: MyObject? {
get {
if UserDefaults.standard.object(forKey: "UserLocationKey") != nil {
if let data = UserDefaults.standard.value(forKey: "UserLocationKey") as? Data {
let myObject = try? PropertyListDecoder().decode(MyObject.self, from: data)
return myObject!
}
}
return nil
}
set {
UserDefaults.standard.set(try? PropertyListEncoder().encode(newValue), forKey: "UserLocationKey")
}
}
}
Here's a UserDefaults extension to set and get a Codable object, and keep it human-readable in the plist (User Defaults) if you open it as a plain text file:
extension Encodable {
var asDictionary: [String: Any]? {
guard let data = try? JSONEncoder().encode(self) else { return nil }
return try? JSONSerialization.jsonObject(with: data) as? [String : Any]
}
}
extension Decodable {
init?(dictionary: [String: Any]) {
guard let data = try? JSONSerialization.data(withJSONObject: dictionary) else { return nil }
guard let object = try? JSONDecoder().decode(Self.self, from: data) else { return nil }
self = object
}
}
extension UserDefaults {
func setEncodableAsDictionary<T: Encodable>(_ encodable: T, for key: String) {
self.set(encodable.asDictionary, forKey: key)
}
func getDecodableFromDictionary<T: Decodable>(for key: String) -> T? {
guard let dictionary = self.dictionary(forKey: key) else {
return nil
}
return T(dictionary: dictionary)
}
}
If you want to also support array (of codables) to and from plist array, add the following to the extension:
extension UserDefaults {
func setEncodablesAsArrayOfDictionaries<T: Encodable>(_ encodables: Array<T>, for key: String) {
let arrayOfDictionaries = encodables.map({ $0.asDictionary })
self.set(arrayOfDictionaries, forKey: key)
}
func getDecodablesFromArrayOfDictionaries<T: Decodable>(for key: String) -> [T]? {
guard let arrayOfDictionaries = self.array(forKey: key) as? [[String: Any]] else {
return nil
}
return arrayOfDictionaries.compactMap({ T(dictionary: $0) })
}
}
If you don't care about plist being human-readable, it can be simply saved as Data (will look like random string if opened as plain text):
extension UserDefaults {
func setEncodable<T: Encodable>(_ encodable: T, for key: String) throws {
let data = try PropertyListEncoder().encode(encodable)
self.set(data, forKey: key)
}
func getDecodable<T: Decodable>(for key: String) -> T? {
guard
self.object(forKey: key) != nil,
let data = self.value(forKey: key) as? Data
else {
return nil
}
let obj = try? PropertyListDecoder().decode(T.self, from: data)
return obj
}
}
(With this second approach, you don't need the Encodable and Decodable extensions from the top)

Codable Struct: Get Value by Key

I have for example codable struct User:
struct User: Codable {
// ...
var psnTag: String?
var xblTag: String?
var steamTag: String?
var nintendoTag: String?
var instagramId: String?
// ...
}
and stringKey as String = "psnTag"
How can I get the value from instance by stringKey?
Like this:
let stringKey = "psnTag"
user.hasKeyForPath(stringKey) //return Bool
user.valueForPath(stringKey) //return AnyObject
Start with extending Encodable protocol and declare methods for hasKey and for value
Using Mirror
extension Encodable {
func hasKey(for path: String) -> Bool {
return Mirror(reflecting: self).children.contains { $0.label == path }
}
func value(for path: String) -> Any? {
return Mirror(reflecting: self).children.first { $0.label == path }?.value
}
}
Using JSON Serialization
extension Encodable {
func hasKey(for path: String) -> Bool {
return dictionary?[path] != nil
}
func value(for path: String) -> Any? {
return dictionary?[path]
}
var dictionary: [String: Any]? {
return (try? JSONSerialization.jsonObject(with: JSONEncoder().encode(self))) as? [String: Any]
}
}
Now you can use it like this:
.hasKey(for: "key") //returns Bool
.value(for: "key") //returns Any?

Alamofire.request().responseObject doesn't return response

I use AlamofireObjectMapper extension. I want to get response, but it's failed. My tableLeague object is always nil because code with response closure doesn't call ({ (response: DataResponse) in
if response.result.isSuccess {
tableLeague = response.result.value
} doesn't call). I use next methods:
let header = ["X-Auth-Token":"1231231"]
static let sharedInstance = ServerAPI()
private func getRequest(uri: String) -> DataRequest {
return Alamofire.request(uri, method: .get, headers: header)
}
public func getTableLeague() -> TableLeague {
var tableLeague: TableLeague?
getRequest(uri: URL).responseObject { (response: DataResponse<TableLeague>) in
if response.result.isSuccess {
tableLeague = response.result.value
}
}
return tableLeague!
}
And use in business class:
public func readTableLeague() -> TableLeague {
let tableLeague = ServerAPI.sharedInstance.getTableLeague()
return tableLeague
}
I think it can be because response haven't yet but i try to set object that i haven't yet
Whats a problem? Completion handlers i need to use else?
Please try to map by following structure
class Response: Mappable {
var success: Bool?
var data: [Data]?
required init?(_ map: Map) {
mapping(map)
}
func mapping(map: Map) {
success <- map["success"]
data <- map["data"]
}
}
class Data: Mappable {
var uid: Int?
var name: String?
// add other field which you want to map
required init?(_ map: Map) {
mapping(map)
}
func mapping(map: Map) {
uid <- map["uid"]
name <- map["name"]
}
}
When you get JSON response simple map by this syntax
let response = Mapper<Response>().map(responseObject)
if let id = response?.data?[0].uid {
println(id)
}

Casting AnyObject to Specific Class

I'm using socket.io Swift Library. With the following line of code,
socket.on("info") { (dataArray, socketAck) -> Void in
let user = dataArray[0] as? User
print(user._id)
}
dataArray[0] is a valid object but user appears to be nil after casting.
Since dataArray[0] returns as an AnyObject,
how can i cast AnyObject to User Object?. Or somehow manage to do what i want with a different approach?
Since after this line
let user = dataArray[0] as? User
you have a nil value inside user it means that you don't have a User value at the first position of dataArray.
Since dataArray comes from a server (as I guess) it probably contains a serialized version of User.
Now we really need to know what really dataArray[0] is. However...
if dataArray[0] contains NSData
In this case try this
let json = JSON(dataArray[0] as! NSData)
let user = User(json:json)
You need to create a constructor that accept AnyObject and read data in it.
I guess in this case dataArray[0] is an JSON Object.
class User {
init(data: [String: AnyObject]) {
username = data["username"] as? String ?? ""
}
}
This is how i manage mine:
// Structure used as parameter
struct InfoStruct {
var nome: String = ""
var sobrenome:String = ""
var nascimentoTimestamp: NSNumber = 0
init() {
}
// Struct to AnyObject
func toAnyObject() -> Any {
var dic = [String:AnyObject?]()
if (nome != "") { dic["nome"] = nome as AnyObject }
if (sobrenome != "") { dic["sobrenome"] = sobrenome as AnyObject }
if (nascimentoTimestamp != 0) { dic["nascimentoTimestamp"] = nascimentoTimestamp as AnyObject }
return dic
}
// AnyObject to Struct
func fromAnyObject(dic:[String:AnyObject]) -> InfoStruct {
var retorno = InfoStruct()
if (dic["nome"] != nil) { retorno.nome = dic["nome"] as? String ?? "" }
if (dic["sobrenome"] != nil) { retorno.sobrenome = dic["sobrenome"] as? String ?? "" }
if (dic["nascimentoTimestamp"] != nil) { retorno.nascimentoTimestamp = dic["nascimentoTimestamp"] as? NSNumber ?? 0 }
return retorno
} }
// User class
class Usuario: NSObject {
var key: String
var admin: Bool
var info: InfoStruct // Struct parameter
init(_ key: String?) {
self.key = key ?? ""
admin = false
info = InfoStruct() // Initializing struct
}
// From Class to AnyObject
func toAnyObject() -> Any {
var dic = [String:AnyObject?]()
if (key != "") { dic["key"] = key as AnyObject }
if (admin != false) { dic["admin"] = admin as AnyObject }
dic["info"] = info.toAnyObject() as AnyObject // Struct
return dic
}
// From AnyObject to Class
func fromAnyObject(dic:[String:AnyObject]) -> Usuario {
let retorno = Usuario(dic["key"] as? String)
if (dic["key"] != nil) { retorno.key = dic["key"] as? String ?? "" }
if (dic["admin"] != nil) { retorno.admin = dic["admin"] as? Bool ?? false }
if (dic["info"] != nil) { retorno.info = InfoStruct.init().fromAnyObject(dic: dic["info"] as! [String : AnyObject]) } // Struct
return retorno
} }
// Using
let dao = FirebaseDAO.init(_type: FirebaseDAOType.firebaseDAOTypeUser)
dao.loadValue(key: uid) { (error, values:[String : AnyObject]) in
if error == nil {
let user = Usuario(values["key"] as? String).fromAnyObject(dic: values)
}
}
I hope it helps!