Error [NSKeyedUnarchiver validateAllowedClass:forKey:] solution

created at 01-01-2022 views: 7

problem

The storage path is:

lazy var filePath:String = {

        let path =  NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask

            ,true).first! as NSString

        let filePath = path.appendingPathComponent("test.data")

        return filePath

    }()

Using unarchive in the following way will report an error [NSKeyedUnarchiver validateAllowedClass:forKey:]

do{

            let data = try Data(contentsOf:URL(fileURLWithPath:filePath))

            let account = try NSKeyedUnarchiver.unarchivedObject(ofClasses: [UserModel.classForKeyedUnarchiver()], from: data) as? UserModel

           return account

        }catch{

            print(error)

        }

solution

Use unarchiveTopLevelObjectWithData

do{

Let data = try Data.init(contentsOf:URL(fileURLWithPath:filePath))

Let model = try?NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data)as?UserModel

Return model

}Catch{

Print("Get failed: \(error)")

}
created at:01-01-2022
edited at: 01-01-2022: