How to delete files in iOS Notification Service Extension?Can I embed a custom font in an iPhone application?Will Apple push notification feedback service report devices that call unregisterForRemoteNotificationsDoes iOS 8 support dynamic linking?NSURLSession - control the transfer rateiOS Share extension how to support *.wav filesiOS extension- sharing bubble vs sharing button?Access webpage properties in Share extensionIOS Share extension: how to read from notes postsShare data from notification service extensionUpdating model from iOS push notification

Bach Invention - fingering

Is it possible to animate 2 folds on the same sheet?

Conservation of momentum in photon-atom collision

How do I activate Windows XP nowadays (in 2019)?

Ethics: Is it ethical for a professor to conduct research using a student's ideas without giving them credit?

Is there a preferred time in their presidency when US presidents pardon the most people?

Did Ohio pass a law granting students the right to give scientifically wrong answers consistent with their religious beliefs?

My PhD defense is next week and I am having negative thoughts about my work and knowledge. Any advice on how to tackle this?

UK visitors visa needed fast for badly injured family member

What is the "two-drive trick" that can read Amiga disks on a PC?

Angle paths are superposed in tikz

Linking the intuition of topology with its axiomatic definition

ASCII texturing

Why does Darth Sidious fear Luke Skywalker?

What is the correct way for pilots to say times?

Are conjugate vectors unique?

Were there ever 12-, 24-, 48-, etc bit processors?

Engine sync for jet engines; vs prop sync to eliminate beats

SSH host identification changes on one wireless network

RPMs too high on freeway?

Is every conformal manifold equivalent to a flat one with cone singularities?

Why do some DSLRs have ISO less than 100?

Days in indexed month

Is staccato implied in the bass on this Burgmuller Arabesque?



How to delete files in iOS Notification Service Extension?


Can I embed a custom font in an iPhone application?Will Apple push notification feedback service report devices that call unregisterForRemoteNotificationsDoes iOS 8 support dynamic linking?NSURLSession - control the transfer rateiOS Share extension how to support *.wav filesiOS extension- sharing bubble vs sharing button?Access webpage properties in Share extensionIOS Share extension: how to read from notes postsShare data from notification service extensionUpdating model from iOS push notification






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty
margin-bottom:0;









0


















I have a UNNotificationServiceExtension that downloads videos and images to the Documents directory for use by classes that adopt UNNotificationContentExtension. I want to delete the media files that are no longer being used by any notifications. I am not sure how to go about doing this.



  • I tried to delete the files in my AppDelegate, but I believe the UNNotificationServiceExtension has its own Documents directory per the "Sharing Data With Your Containing App" section of this document: https://developer.apple.com/library/archive/documentation/General/Conceptual/ExtensibilityPG/ExtensionScenarios.html, so I cannot access these files from my main app. They are in a different container.

  • I don't want to create an App Group to share the data between the app and the extension just so that I can delete the unused files.

  • I don't want to delete the unused files in the UNNotificationServiceExtension, because the extension has a limited amount of time in which to complete its work, and if I try to download files and delete other files, it may time out.

I think the best option is to check to see which files are needed by any delivered notifications and to delete the unneeded files in the Notification Service Extension's Documents directory. My concern with this is that the UNNotificationServiceExtension is only given a short period of time during which it must complete all of its work, after which it will time out.



So, my question is, "Is this the right way to clean up unused files from a Notification Service Extension, or is there a better way?"










share|improve this question



























  • When you clear the notification from your device's notification tray, the media(Notification content) downloaded with the notification is automatically removed by the device. And if you are storing data in some other place explicitly then you have to add App groups in order to store and delete the data.

    – manishsharma93
    Mar 29 at 6:16

















0


















I have a UNNotificationServiceExtension that downloads videos and images to the Documents directory for use by classes that adopt UNNotificationContentExtension. I want to delete the media files that are no longer being used by any notifications. I am not sure how to go about doing this.



  • I tried to delete the files in my AppDelegate, but I believe the UNNotificationServiceExtension has its own Documents directory per the "Sharing Data With Your Containing App" section of this document: https://developer.apple.com/library/archive/documentation/General/Conceptual/ExtensibilityPG/ExtensionScenarios.html, so I cannot access these files from my main app. They are in a different container.

  • I don't want to create an App Group to share the data between the app and the extension just so that I can delete the unused files.

  • I don't want to delete the unused files in the UNNotificationServiceExtension, because the extension has a limited amount of time in which to complete its work, and if I try to download files and delete other files, it may time out.

I think the best option is to check to see which files are needed by any delivered notifications and to delete the unneeded files in the Notification Service Extension's Documents directory. My concern with this is that the UNNotificationServiceExtension is only given a short period of time during which it must complete all of its work, after which it will time out.



So, my question is, "Is this the right way to clean up unused files from a Notification Service Extension, or is there a better way?"










share|improve this question



























  • When you clear the notification from your device's notification tray, the media(Notification content) downloaded with the notification is automatically removed by the device. And if you are storing data in some other place explicitly then you have to add App groups in order to store and delete the data.

    – manishsharma93
    Mar 29 at 6:16













0













0









0








I have a UNNotificationServiceExtension that downloads videos and images to the Documents directory for use by classes that adopt UNNotificationContentExtension. I want to delete the media files that are no longer being used by any notifications. I am not sure how to go about doing this.



  • I tried to delete the files in my AppDelegate, but I believe the UNNotificationServiceExtension has its own Documents directory per the "Sharing Data With Your Containing App" section of this document: https://developer.apple.com/library/archive/documentation/General/Conceptual/ExtensibilityPG/ExtensionScenarios.html, so I cannot access these files from my main app. They are in a different container.

  • I don't want to create an App Group to share the data between the app and the extension just so that I can delete the unused files.

  • I don't want to delete the unused files in the UNNotificationServiceExtension, because the extension has a limited amount of time in which to complete its work, and if I try to download files and delete other files, it may time out.

I think the best option is to check to see which files are needed by any delivered notifications and to delete the unneeded files in the Notification Service Extension's Documents directory. My concern with this is that the UNNotificationServiceExtension is only given a short period of time during which it must complete all of its work, after which it will time out.



So, my question is, "Is this the right way to clean up unused files from a Notification Service Extension, or is there a better way?"










share|improve this question
















I have a UNNotificationServiceExtension that downloads videos and images to the Documents directory for use by classes that adopt UNNotificationContentExtension. I want to delete the media files that are no longer being used by any notifications. I am not sure how to go about doing this.



  • I tried to delete the files in my AppDelegate, but I believe the UNNotificationServiceExtension has its own Documents directory per the "Sharing Data With Your Containing App" section of this document: https://developer.apple.com/library/archive/documentation/General/Conceptual/ExtensibilityPG/ExtensionScenarios.html, so I cannot access these files from my main app. They are in a different container.

  • I don't want to create an App Group to share the data between the app and the extension just so that I can delete the unused files.

  • I don't want to delete the unused files in the UNNotificationServiceExtension, because the extension has a limited amount of time in which to complete its work, and if I try to download files and delete other files, it may time out.

I think the best option is to check to see which files are needed by any delivered notifications and to delete the unneeded files in the Notification Service Extension's Documents directory. My concern with this is that the UNNotificationServiceExtension is only given a short period of time during which it must complete all of its work, after which it will time out.



So, my question is, "Is this the right way to clean up unused files from a Notification Service Extension, or is there a better way?"







ios unnotificationserviceextension






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 28 at 22:14







Nick

















asked Mar 28 at 22:08









NickNick

114 bronze badges




114 bronze badges















  • When you clear the notification from your device's notification tray, the media(Notification content) downloaded with the notification is automatically removed by the device. And if you are storing data in some other place explicitly then you have to add App groups in order to store and delete the data.

    – manishsharma93
    Mar 29 at 6:16

















  • When you clear the notification from your device's notification tray, the media(Notification content) downloaded with the notification is automatically removed by the device. And if you are storing data in some other place explicitly then you have to add App groups in order to store and delete the data.

    – manishsharma93
    Mar 29 at 6:16
















When you clear the notification from your device's notification tray, the media(Notification content) downloaded with the notification is automatically removed by the device. And if you are storing data in some other place explicitly then you have to add App groups in order to store and delete the data.

– manishsharma93
Mar 29 at 6:16





When you clear the notification from your device's notification tray, the media(Notification content) downloaded with the notification is automatically removed by the device. And if you are storing data in some other place explicitly then you have to add App groups in order to store and delete the data.

– manishsharma93
Mar 29 at 6:16












1 Answer
1






active

oldest

votes


















0



















Thanks to manishsharma93, I was able to implement a good solution. I am now storing the files in a directory shared by the main app and the notification service extension. I first had to set up a shared App Group using the information found here: https://developer.apple.com/library/archive/documentation/Miscellaneous/Reference/EntitlementKeyReference/Chapters/EnablingAppSandbox.html#//apple_ref/doc/uid/TP40011195-CH4-SW19



Then in my AppDelegate, I added this private function, which I call at the end of the applicationDidFinishLaunching(_:) method:



// I call this at the end of the AppDelegate.applicationDidFinishLaunching(_:) method
private func clearNotificationMedia()
// Check to see if there are any delivered notifications. If there are, don't delete the media yet,
// because the notifications may be using them. If you wanted to be more fine-grained here,
// you could individually check to see which files the notifications are using, and delete everything else.
UNUserNotificationCenter.current().getDeliveredNotifications (notifications) in
guard notifications.isEmpty else return

let fileManager = FileManager.default

guard let mediaCacheUrl = fileManager.containerURL(forSecurityApplicationGroupIdentifier: "group.com.yourGroupHere")?.appendingPathComponent("media_cache", isDirectory: true) else return

// Check to see if the directory exists. If it doesn't, we have nothing to do here.
var isDirectory: ObjCBool = false
let directoryExists = FileManager.default.fileExists(atPath: mediaCacheUrl.path, isDirectory: &isDirectory)
guard directoryExists && isDirectory.boolValue else
print("No media_cache directory to delete.", terminator: "n")
return


// The directory exists and there aren't any notifications using media stored there,
// so go ahead and delete it. Use a lock to make sure that there isn't data corruption,
// since the directory is shared.
let lock = NSLock()
lock.lock()
do
try FileManager.default.removeItem(at: mediaCacheUrl)
DebugLog("Successfully deleted media_cache directory.")
catch let error as NSError
DebugLog("Error: (error.localizedDescription). Failed to delete media_cache directory.")

lock.unlock()




It works like a charm. Thanks again for pointing me in the right direction manishsharma93.






share|improve this answer



























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );














    draft saved

    draft discarded
















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55407601%2fhow-to-delete-files-in-ios-notification-service-extension%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown


























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0



















    Thanks to manishsharma93, I was able to implement a good solution. I am now storing the files in a directory shared by the main app and the notification service extension. I first had to set up a shared App Group using the information found here: https://developer.apple.com/library/archive/documentation/Miscellaneous/Reference/EntitlementKeyReference/Chapters/EnablingAppSandbox.html#//apple_ref/doc/uid/TP40011195-CH4-SW19



    Then in my AppDelegate, I added this private function, which I call at the end of the applicationDidFinishLaunching(_:) method:



    // I call this at the end of the AppDelegate.applicationDidFinishLaunching(_:) method
    private func clearNotificationMedia()
    // Check to see if there are any delivered notifications. If there are, don't delete the media yet,
    // because the notifications may be using them. If you wanted to be more fine-grained here,
    // you could individually check to see which files the notifications are using, and delete everything else.
    UNUserNotificationCenter.current().getDeliveredNotifications (notifications) in
    guard notifications.isEmpty else return

    let fileManager = FileManager.default

    guard let mediaCacheUrl = fileManager.containerURL(forSecurityApplicationGroupIdentifier: "group.com.yourGroupHere")?.appendingPathComponent("media_cache", isDirectory: true) else return

    // Check to see if the directory exists. If it doesn't, we have nothing to do here.
    var isDirectory: ObjCBool = false
    let directoryExists = FileManager.default.fileExists(atPath: mediaCacheUrl.path, isDirectory: &isDirectory)
    guard directoryExists && isDirectory.boolValue else
    print("No media_cache directory to delete.", terminator: "n")
    return


    // The directory exists and there aren't any notifications using media stored there,
    // so go ahead and delete it. Use a lock to make sure that there isn't data corruption,
    // since the directory is shared.
    let lock = NSLock()
    lock.lock()
    do
    try FileManager.default.removeItem(at: mediaCacheUrl)
    DebugLog("Successfully deleted media_cache directory.")
    catch let error as NSError
    DebugLog("Error: (error.localizedDescription). Failed to delete media_cache directory.")

    lock.unlock()




    It works like a charm. Thanks again for pointing me in the right direction manishsharma93.






    share|improve this answer






























      0



















      Thanks to manishsharma93, I was able to implement a good solution. I am now storing the files in a directory shared by the main app and the notification service extension. I first had to set up a shared App Group using the information found here: https://developer.apple.com/library/archive/documentation/Miscellaneous/Reference/EntitlementKeyReference/Chapters/EnablingAppSandbox.html#//apple_ref/doc/uid/TP40011195-CH4-SW19



      Then in my AppDelegate, I added this private function, which I call at the end of the applicationDidFinishLaunching(_:) method:



      // I call this at the end of the AppDelegate.applicationDidFinishLaunching(_:) method
      private func clearNotificationMedia()
      // Check to see if there are any delivered notifications. If there are, don't delete the media yet,
      // because the notifications may be using them. If you wanted to be more fine-grained here,
      // you could individually check to see which files the notifications are using, and delete everything else.
      UNUserNotificationCenter.current().getDeliveredNotifications (notifications) in
      guard notifications.isEmpty else return

      let fileManager = FileManager.default

      guard let mediaCacheUrl = fileManager.containerURL(forSecurityApplicationGroupIdentifier: "group.com.yourGroupHere")?.appendingPathComponent("media_cache", isDirectory: true) else return

      // Check to see if the directory exists. If it doesn't, we have nothing to do here.
      var isDirectory: ObjCBool = false
      let directoryExists = FileManager.default.fileExists(atPath: mediaCacheUrl.path, isDirectory: &isDirectory)
      guard directoryExists && isDirectory.boolValue else
      print("No media_cache directory to delete.", terminator: "n")
      return


      // The directory exists and there aren't any notifications using media stored there,
      // so go ahead and delete it. Use a lock to make sure that there isn't data corruption,
      // since the directory is shared.
      let lock = NSLock()
      lock.lock()
      do
      try FileManager.default.removeItem(at: mediaCacheUrl)
      DebugLog("Successfully deleted media_cache directory.")
      catch let error as NSError
      DebugLog("Error: (error.localizedDescription). Failed to delete media_cache directory.")

      lock.unlock()




      It works like a charm. Thanks again for pointing me in the right direction manishsharma93.






      share|improve this answer




























        0















        0











        0









        Thanks to manishsharma93, I was able to implement a good solution. I am now storing the files in a directory shared by the main app and the notification service extension. I first had to set up a shared App Group using the information found here: https://developer.apple.com/library/archive/documentation/Miscellaneous/Reference/EntitlementKeyReference/Chapters/EnablingAppSandbox.html#//apple_ref/doc/uid/TP40011195-CH4-SW19



        Then in my AppDelegate, I added this private function, which I call at the end of the applicationDidFinishLaunching(_:) method:



        // I call this at the end of the AppDelegate.applicationDidFinishLaunching(_:) method
        private func clearNotificationMedia()
        // Check to see if there are any delivered notifications. If there are, don't delete the media yet,
        // because the notifications may be using them. If you wanted to be more fine-grained here,
        // you could individually check to see which files the notifications are using, and delete everything else.
        UNUserNotificationCenter.current().getDeliveredNotifications (notifications) in
        guard notifications.isEmpty else return

        let fileManager = FileManager.default

        guard let mediaCacheUrl = fileManager.containerURL(forSecurityApplicationGroupIdentifier: "group.com.yourGroupHere")?.appendingPathComponent("media_cache", isDirectory: true) else return

        // Check to see if the directory exists. If it doesn't, we have nothing to do here.
        var isDirectory: ObjCBool = false
        let directoryExists = FileManager.default.fileExists(atPath: mediaCacheUrl.path, isDirectory: &isDirectory)
        guard directoryExists && isDirectory.boolValue else
        print("No media_cache directory to delete.", terminator: "n")
        return


        // The directory exists and there aren't any notifications using media stored there,
        // so go ahead and delete it. Use a lock to make sure that there isn't data corruption,
        // since the directory is shared.
        let lock = NSLock()
        lock.lock()
        do
        try FileManager.default.removeItem(at: mediaCacheUrl)
        DebugLog("Successfully deleted media_cache directory.")
        catch let error as NSError
        DebugLog("Error: (error.localizedDescription). Failed to delete media_cache directory.")

        lock.unlock()




        It works like a charm. Thanks again for pointing me in the right direction manishsharma93.






        share|improve this answer














        Thanks to manishsharma93, I was able to implement a good solution. I am now storing the files in a directory shared by the main app and the notification service extension. I first had to set up a shared App Group using the information found here: https://developer.apple.com/library/archive/documentation/Miscellaneous/Reference/EntitlementKeyReference/Chapters/EnablingAppSandbox.html#//apple_ref/doc/uid/TP40011195-CH4-SW19



        Then in my AppDelegate, I added this private function, which I call at the end of the applicationDidFinishLaunching(_:) method:



        // I call this at the end of the AppDelegate.applicationDidFinishLaunching(_:) method
        private func clearNotificationMedia()
        // Check to see if there are any delivered notifications. If there are, don't delete the media yet,
        // because the notifications may be using them. If you wanted to be more fine-grained here,
        // you could individually check to see which files the notifications are using, and delete everything else.
        UNUserNotificationCenter.current().getDeliveredNotifications (notifications) in
        guard notifications.isEmpty else return

        let fileManager = FileManager.default

        guard let mediaCacheUrl = fileManager.containerURL(forSecurityApplicationGroupIdentifier: "group.com.yourGroupHere")?.appendingPathComponent("media_cache", isDirectory: true) else return

        // Check to see if the directory exists. If it doesn't, we have nothing to do here.
        var isDirectory: ObjCBool = false
        let directoryExists = FileManager.default.fileExists(atPath: mediaCacheUrl.path, isDirectory: &isDirectory)
        guard directoryExists && isDirectory.boolValue else
        print("No media_cache directory to delete.", terminator: "n")
        return


        // The directory exists and there aren't any notifications using media stored there,
        // so go ahead and delete it. Use a lock to make sure that there isn't data corruption,
        // since the directory is shared.
        let lock = NSLock()
        lock.lock()
        do
        try FileManager.default.removeItem(at: mediaCacheUrl)
        DebugLog("Successfully deleted media_cache directory.")
        catch let error as NSError
        DebugLog("Error: (error.localizedDescription). Failed to delete media_cache directory.")

        lock.unlock()




        It works like a charm. Thanks again for pointing me in the right direction manishsharma93.







        share|improve this answer













        share|improve this answer




        share|improve this answer










        answered Apr 3 at 16:03









        NickNick

        114 bronze badges




        114 bronze badges































            draft saved

            draft discarded















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55407601%2fhow-to-delete-files-in-ios-notification-service-extension%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown









            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript