ExtensionDelegate.swift 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*****************************************************************************
  2. * ExtensionDelegate.swift
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2015 VideoLAN. All rights reserved.
  6. * $Id$
  7. *
  8. * Authors: Tobias Conradi <videolan # tobias-conradi.de>
  9. *
  10. * Refer to the COPYING file of the official project for license.
  11. *****************************************************************************/
  12. import WatchKit
  13. import WatchConnectivity
  14. import CoreData
  15. import MediaLibraryKit
  16. class ExtensionDelegate: NSObject, WKExtensionDelegate, WCSessionDelegate {
  17. func applicationDidFinishLaunching() {
  18. // Perform any final initialization of your application.
  19. WCSession.defaultSession().delegate = self;
  20. WCSession.defaultSession().activateSession()
  21. }
  22. func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void) {
  23. let msg = VLCWatchMessage(dictionary: message)
  24. if msg.name == VLCWatchMessageNameNotification, let payloadDict = msg.payload as? [String : AnyObject] {
  25. if let name = payloadDict["name"] as? String {
  26. handleRemoteNotification(name, userInfo: payloadDict["userInfo"] as? [String : AnyObject])
  27. }
  28. }
  29. }
  30. func handleRemoteNotification(name:String, userInfo: [String: AnyObject]?) {
  31. NSNotificationCenter.defaultCenter().postNotificationName(name, object: self, userInfo: userInfo)
  32. }
  33. func session(session: WCSession, didReceiveFile file: WCSessionFile) {
  34. let fileType = file.metadata?["filetype"] as? String ?? ""
  35. if fileType == "coredata" {
  36. copyUpdatedCoreDataDBFromURL(file.fileURL)
  37. }
  38. }
  39. func copyUpdatedCoreDataDBFromURL(url:NSURL) {
  40. let library = MLMediaLibrary.sharedMediaLibrary()
  41. do {
  42. // we can be sure that it's only the sqlite file and no -wal -shm etc. therefore we can just plain copy it.
  43. if NSFileManager.defaultManager().fileExistsAtPath(library.persistentStoreURL!.absoluteString) {
  44. try NSFileManager.defaultManager().replaceItemAtURL(library.persistentStoreURL, withItemAtURL: url, backupItemName: nil, options: NSFileManagerItemReplacementOptions.UsingNewMetadataOnly, resultingItemURL: nil)
  45. } else {
  46. try NSFileManager.defaultManager().copyItemAtURL(url, toURL: library.persistentStoreURL)
  47. }
  48. } catch {
  49. print("failed to copy Core Data DB to new DB location on watch")
  50. }
  51. NSNotificationCenter.defaultCenter().postNotificationName(VLCDBUpdateNotification, object: self)
  52. }
  53. }