We’ve arrived at day 64 of the 100 Days of SwiftUI! Yesterday, we learned how to implement Core Image into our Instafilter app. Today, we’re diving into how to save images to the users photo library and how to use coordinators. Let’s take a look!
Using coordinators to manage SwiftUI view controllers
When we finished yesterday, we were not able to take action when a user selected an image or cancelled selecting an image. The image picker worked, however. To complete this functionality, we need to use coordinators.
SwiftUI’s coordinators are designed to act as delegates for UIKit view controllers. Remember, “delegates” are objects that respond to events that occur elsewhere. For example, UIKit lets us attach a delegate object to its text field view, and that delegate will be notified when the user types anything, when they press return, and so on. This meant that UIKit developers could modify the way their text field behaved without having to create a custom text field type of their own.
Using coordinators in SwiftUI requires you to learn a little about the way UIKit works, which is no surprise given that we’re literally integrating UIKit’s view controllers. So, to demonstrate this we’re going to upgrade our
Hacking with Swift, Paul Hudson (@twostraws)ImagePicker
view so that it can report back when the user selects an image or presses Cancel.
I’m sure you’re interested in how to implement them, so head over to Paul’s article and check it out!
How to save images to the user’s photo library
Just like yesterday, we’re running into some remnants of UIKit, which need to be be reconstructed a little bit to work properly in SwiftUI.
Before we’re done with the techniques for this project, there’s one last piece of UIKit joy we need to tackle: once we’ve processed the user’s image we’ll get a
Hacking with Swift, Paul Hudson (@twostraws)UIImage
back, but we need a way to save that processed image to the user’s photo library. This uses a UIKit function calledUIImageWriteToSavedPhotosAlbum()
, which in its simplest form is trivial to use, but in order to make it work usefully you need to wade back into UIKit. At the very least it will make you really appreciate how much better SwiftUI is!
Wrap up
And that’s it for day 64 and all we need to know for full implementation of our Instafilter app. We’ve now almost finished yet another project and we’ve seen some difficult techniques that need to be adapted in order to make some older UIKit code work in SwiftUI. We’ll now be looking ahead to the wrap up and a few challenges tomorrow, but first, we’re gonna create the app from scratch, so stay tuned for that!
100 Days of SwiftUI – Day 64