how to save and retrive cbperipheral in coredata and in swift

To save a CBPeripheral instance in Core Data, you can make it conform to the NSCoding protocol:

main.swift
class PeripheralObject: NSManagedObject, NSCoding {
    
    @NSManaged var macAddress: String?
    @NSManaged var name: String?

    func encode(with aCoder: NSCoder) {
        aCoder.encode(macAddress, forKey: "macAddress")
        aCoder.encode(name, forKey: "name")
    }

    required convenience init?(coder aDecoder: NSCoder) {
        let context = CoreDataStack.sharedInstance.persistentContainer.viewContext
        self.init(entity: PeripheralObject.entity(), insertInto: context)

        macAddress = aDecoder.decodeObject(forKey: "macAddress") as? String
        name = aDecoder.decodeObject(forKey: "name") as? String
    }
    
}
646 chars
20 lines

Now you can save the CBPeripheral object in Core Data by converting it to NSData and storing it in the PeripheralObject instance:

main.swift
let peripheralObject = PeripheralObject(context: context)
let data = NSKeyedArchiver.archivedData(withRootObject: peripheral)
peripheralObject.macAddress = peripheral.identifier.uuidString
peripheralObject.name = peripheral.name
peripheralObject.data = data

do {
    try context.save()
} catch let error as NSError {
    print("Could not save. \(error), \(error.userInfo)")
}
377 chars
12 lines

To retrieve the CBPeripheral instance, you can fetch the PeripheralObject from Core Data and deserialize the NSData back into a CBPeripheral:

main.swift
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "PeripheralObject")
fetchRequest.predicate = NSPredicate(format: "macAddress = %@", uuid.uuidString)

do {
    let results = try context.fetch(fetchRequest) as! [PeripheralObject]
    if let data = results.first?.data {
        let peripheral = NSKeyedUnarchiver.unarchiveObject(with: data) as! CBPeripheral
        return peripheral
    }
} catch let error as NSError {
    print("Could not fetch. \(error), \(error.userInfo)")
}

return nil
511 chars
15 lines

gistlibby LogSnag