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

1.3k Views Asked by At

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.

2

There are 2 best solutions below

1
On BEST ANSWER

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.

0
On

I recently had the same dilemma: I want to access user credentials from the notification service extension but I also want to have the credentials stored safely.

My solution is to have two sets of user credentials. A regular one that gives full access and a restricted one that gives only read permission for a subset of the data. Usually, the notification service extension just needs to fetch one data instance, typically a message or a notification. Therefor, my restricted credentials can only fetch single notifications. These restricted credentials are stored with read access even if the phone is locked.

To additionally increase security, the fetch is performed by non-sequential notification-ids. In this way, the person stealing the restricted credentials doesn't have access to all notifications as their ids cannot be guessed.