swiftxcodepush-notificationapple-push-notificationsunnotificationserviceextension

Notification Service Extension - make URL request when app is not running


We implemented Notification Service Extension in our app. Our goal is to download some data from our server and modify the notification content in didReceive(_:withContentHandler:).

It's working fine when the app is running in the background, or has just been terminated. When the app is not running however, it can not download the data and the service extension time expires.

EDIT: Okay, I edited this question, and removed my networking code, because I figured out what my issue was. However, this led to another problem.

My networking code did not run when the app was terminated, because I store the user's access token on the keychain, which can not be accessed when the phone is locked.

So, I'm at a stalemate right now: On the one hand, I do not want to store the access token in UserDefaults, because that's just unsafe. On the other hand, I need to use the access token when the device is locked, to display the proper notification content. Any help appreciated.


Solution

  • You can access the keychain's contents even if the device is locked, with the proper settings. However, please be advised that this will greatly reduce the security of that information.

    If you're using keychain directly, you can set the kSecAttrAccessible property of the keychain item that stores your access token to kSecAttrAccessibleAlways.

    If, like most folks, you're using an open-source library such as Swift Keychain Wrapper, you can do the following:

    KeychainWrapper.standard.set(accessToken, forKey: key, withAccessibility: .always)

    Another note that might save you some time, from Swift Keychain Wrapper's documentation:

    Important: You can't modify value for key if it was previously set with different accessibility option. Remove the value for key and set it with new accessibility option. (Otherwise the value will not change).

    If you want to read up on keychain item accessibility I would suggest starting with this.