Push Notifications · Attaching Media | raywenderlich.com


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/1258151-push-notifications/lessons/15

Hi Audrey,
Great tutorial.

I see that you’re using Data(conentsof: url) but the docs on NSData say:

Don’t use this synchronous initializer to request network-based URLs. For network-based URLs, this method can block the current thread for tens of seconds on a slow network, resulting in a poor user experience, and in iOS, may cause your app to be terminated.

Instead, for non-file URLs, consider using the dataTask(with:completionHandler:) method of the URLSession class

That being said I also saw two other tutorials on RW using dataTask and another using downloadTask. I wonder if any of these make a difference when it comes to solving random image download failures.

Do you have any insight on this?

You’re using Data(contentsOf:) to perform a synchronous data download. If you use an asynchronous method, the function will exit before your data has been retrieved.

what do you mean by “solving random image download failures”?

Wow. Didn’t expect a reply nor one so quick. Super thanks Audrey

What’s the problem if it’s asynchronous? Can’t you just mutate the notification’s attachment with the downloaded image in the completionHandler? I mean as long as you return the completionHandler within 30 seconds you’re good and if you don’t then your serviceExtensionTimeWillExpire will just get called.

Also don’t the docs recommend that you shouldn’t use Data for making network calls. I was told that it should mainly be used for command line tools. But I guess if networking is the only process and nothing else and you don’t mind halting everything else then it can also work. Just that it seemed to be a bit unconventional and not adhering to docs.


As for random image download failures:

(I connected to the debugger but haven’t been able to reproduce my problem to give logs, but it was just plain odd that it just stopped working)

notification service extension doesn’t run on the main queue so there’s no problem using Data(contentsOf:)

if you don’t make the thread wait, the function might exit before the download finishes. That’s why those SO posts sometimes don’t get their media. If you use something like Charles to watch your network traffic, you might see what’s happening.