Airdropping Core Data

So I know this is probably a stretch, but is there any way to airdrop an object from core data? From what I understand airdrop is only used with links, but is there a way to convert the data of a core data object into a file, convert the file into a link, send it via airdrop, and convert it back into a file, and then add that object from a file to another user's core data storage?

Any help would be greatly appreciated. Thanks!!

Excellent question. I'm working on the same thing. So far, I have been able to airdrop a record (to my M1 Mac from my M1 iPad Pro)successfully using this code:

func shareDicta() {  //LOG1

 let url = saveDicta("share")  print(url)  let activityVC = UIActivityViewController(activityItems:[url],applicationActivities:nil)  activityVC.title = "Share One"  activityVC.excludedActivityTypes = []  activityVC.popoverPresentationController?.sourceView = self.view  activityVC.popoverPresentationController?.sourceRect = CGRect(x:self.view.bounds.midX,y:self.view.bounds.midY,width:0,height:0)  self.present(activityVC, animated: true, completion: nil)    }

//=============

func saveDicta(_ fName: String) -> URL {  var dictaFName = ""  if(fName.count<1){return URL(string:"")!}  dictaFName = fName

 let fetchRequest: NSFetchRequest = DictaData.fetchRequest()  fetchRequest.predicate = NSPredicate(format:"%K == %@","dictaUUID",svUUID as CVarArg as CVarArg)     fetchRequest.fetchLimit = 1

 guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {return URL(string:"")!}  let context = appDelegate.persistentContainer.viewContext        do{   let dicta = try context.fetch(fetchRequest).first       do {    let dictaURL = try FileManager.default.url(for:.documentDirectory,in:.userDomainMask,appropriateFor:nil,     create:false).appendingPathComponent(dictaFName + ".dicta")    let data = try NSKeyedArchiver.archivedData(withRootObject:dicta as Any,requiringSecureCoding:false)    try data.write(to:dictaURL)      return dictaURL   }catch{    print("ERROR: (error.localizedDescription)")    return URL(string:"")!   }     }  catch let error as NSError {   print("DictaData FETCH FAILED. (error), (error.userInfo)")   return URL(string:"")!  }    } //==============

When I send it back to my app on my iPad, I am struggling to read it back in, not to mention adding to the CoreData storage. Here's what I have so far on that end:

@objc class func insertDicta(_ path: URL) {  print("DictateVC:(#function)");

 print(path)

 if(fm.fileExists(atPath:path.path)){       do{    let dData = try Data(contentsOf:path)         //let dicta = try! NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(dData) as! NSManagedObject    let dicta = try! NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(dData)    print(dData)         try fm.removeItem(at:path)    }catch let error as NSError{    print("Could not save. (error), (error.userInfo)")    //okAlert("Save Failed","")    return   }      } }

I am able to read/load the record into 'dData' but on the next line, when I try 'NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(dData)' the app crashes with this error:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[DictaData initWithCoder:]: unrecognized selector sent to instance 0x280939500'

Here, DictData is the name of my CoreData entity. Anyway, I don't know if this helps at all, but I hope so. Can you let me know if you've discovered anything which works? I'm right in the middle of working on it, so any breakthroughs would be very helpful. BTW, the record my app sends to the Mac can be read with the TextEdit app, and looks like this:

bplist00‘ X$versionY$archiverT$topX$objects�܆_NSKeyedArchiver— TrootÄØ)*.4DEKLRZ[_cdefgknopU$nullfi !"#$%&'(YdictaFnSzYdictaMlhfSurlUtitleYdictaFColYdictaIndxYdictaDateYdictaLocaYcanonTextYdictaLangV$classZdictaMonthYdictaUUIDYdictaFontÄÄÄ�ÄÄÄÄÄÄÄÄÄÄÄ i0J0o0à0F0T0V0D00Y“+,-WNS.time#AƒDπzŸ¶Ä“/012Z$classnameX$classesVNSDate¢13XNSObjectŸ56789:;<=>??@AB>C_UIColorComponentCountWUIGreenVUIBlueWUIAlphaUNSRGB_UISystemColorNameUUIRed\NSColorSpace"����"?Ä��E0 0 1ÄÄYblueColor”/0FGHI[$classhintsWUIColor¢G3°JWNSColor"B≤‚”MNOPQ_UIFontDescriptorOptions_UIFontDescriptorAttributes�ÄÄ ”STUWYWNS.keysZNS.objects°VÄ°XÄÄ _NSFontFamilyAttribute_American Typewriter“/0]^\NSDictionary¢]3“/0`a_UIFontDescriptor¢b3_UIFontDescriptor _Japanese Uja-JA"=LÃÕ“hij\NS.uuidbytesOÔ√˚ ∏C∏Öπt<&ŇRÄ“/0lmVNSUUID¢l3i0J0o0à0F0T0V0D00YW2022007“/0qrYDictaData£qs3_NSManagedObject����$�)�2�7�I�L�Q�S�n�t�ë�õ�•�©�Ø�π�√�Õ�◊�·�Î�Ú�˝!#%')+-@EMVX]hqx{ÑóØ∑æ∆ÇÊÛı˙ˇ (035=BIcÄÇÑÜç§¶®™¬ÿ›ÍÌÚ6<AFSfhmtwäíó°•�������������t��������������∑

From my perspective, there is useful data there, so that if I could just load that data, as, I might be able to access this information, parse it, if you will, then reconstruct it into a format which could then be inserted into CoreData. Something like this:

@objc func saveDicta() {  //print("(#function)")

 if(edDict){saveEdit();return}     guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {return}  let managedContext = appDelegate.persistentContainer.viewContext  let entity = NSEntityDescription.entity(forEntityName:"DictaData",in:managedContext)!  let dicta = NSManagedObject(entity:entity,insertInto:managedContext)      dicta.setValue(self.textView.text,forKeyPath:"title")  dicta.setValue(local,   forKeyPath:"dictaLoca")  dicta.setValue(langu,   forKeyPath:"dictaLang")  dicta.setValue(index,   forKeyPath:"dictaIndx")  dicta.setValue(fgcol,   forKeyPath:"dictaFCol")  dicta.setValue(descr,   forKeyPath:"dictaFont")  dicta.setValue(fntSz,   forKeyPath:"dictaFnSz")  dicta.setValue(mlhfa,   forKeyPath:"dictaMlhf")  dicta.setValue(UUID(),  forKeyPath:"dictaUUID")  dicta.setValue(NSDate(), forKeyPath:"dictaDate")       do {   try managedContext.save()   dictas.append(dicta)  } catch let error as NSError {   print("Could not save. (error), (error.userInfo)")   okAlert("Save Failed","")   return  } }

Good luck. Please let me know of any breakthroughs.

--Jon

Airdropping Core Data
 
 
Q