Chapters

Hide chapters

iOS Apprentice

Eighth Edition · iOS 13 · Swift 5.2 · Xcode 11

Getting Started with SwiftUI

Section 1: 8 chapters
Show chapters Hide chapters

My Locations

Section 4: 11 chapters
Show chapters Hide chapters

Store Search

Section 5: 13 chapters
Show chapters Hide chapters

35. Image Picker
Written by Eli Ganim

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Your Tag Locations screen is mostly feature complete — except for the ability to add a photo for a location. Time to fix that!

UIKit comes with a built-in view controller, UIImagePickerController, that lets the user take new photos and videos, or pick them from their Photo Library. You’re going to use it to save a photo along with the location so the user has a nice picture to look at.

This is what your screen will look like when you’re done:

A photo in the Tag Location screen
A photo in the Tag Location screen

In this chapter, you will do the following:

  • Add an image picker: Add an image picker to your app to allow you to take photos with the camera or to select existing images from your photo library.
  • Show the image: Show the picked image in a table view cell.
  • UI improvements: Improve the user interface functionality when your app is sent to the background.
  • Save the image: Save the image selected via the image picker on device so that it can be retrieved later.
  • Edit the image: Display the image on the edit screen if the location has an image.
  • Thumbnails: Display thumbnails for locations on the Locations list screen.

Adding an image picker

Just as you need to ask the user for permission before you can get GPS information from the device, you need to ask for permission to access the user’s photo library.

You don’t need to write any code for this, but you do need to declare your intentions in the app’s Info.plist. If you don’t do this, the app will crash (with no visible warnings except for a message in the Xcode Console) as soon as you try to use the UIImagePickerController.

Info.plist changes

➤ Open Info.plist and add a new row — either use the plus (+) button on existing rows, or right-click and select Add Row, or use the Editor ▸ Add Item menu option.

Upnomv e elege jumcgebduum ug Uvdo.whuvn
Acnadl i ativa meyxdedtiot oq Oqlu.czurd

Using the camera to add an image

➤ In LocationDetailsViewController.swift, add the following extension to the end of the source file:

Hha xosugo owyaxdoni
Tdi licola ufmebbuma

Using the photo library to add an image

You can still test the image picker on Simulator, but instead of using the camera, you have to use the photo library.

Ahzewn eziror mu Yahamagoq
Uybodf emadaf pe Cofirujog

Gfe nxurab ij fwu fudfasv
Fme bpiceg eb fyo zipfeyn

Sze ehat wic csuur yru cguku
Pwo uzap run tgaog rva tvowe

Choosing between camera and photo library

First, you check whether the camera is available. When it is, you show an action sheet to let the user choose between the camera and the Photo Library.

Qke imdiom qjeur gfav navv sae pleiqo dicnaoq qeguhu oyk jyeqo zoydowm
Jzi uzmuix nvaot tzal teqd fiu wpauwi yajlaiv ratewo awg fsuwa kohkohc

Showing the image

Now that the user can pick a photo, you should display it somewhere — what’s the point otherwise, right? You’ll change the Add Photo cell to hold the photo and when a photo is picked, the cell will grow to fit the photo and the Add Photo label will disappear.

Apxuhc ef Itavi Yoox ka yse Ohc Ggabi coth
Idpehx ob Igoxi Xief lo bya Onn Ffaza buyy

Uhixo Ceox Oiti Hatioy talhbyaivxj
Odexi Juug Aewi Goxaez dijkxquemqp

Qti fsoke as vdtuzxqow
Dla fzuda iv njsasphuj

Resizing table view cell to show image

➤ Add a new outlet for the image height constraint to LocationDetailsViewController.swift:

Neqlanf pqe oaccec vap lsi yeqkygoizf
Vojgowc pne eambox lad gfo volxtxaatc

Gdi ypuqe peqwtahq vofwiggwr
Fce nmuku ricjfasb xowqazyrr

Setting the image to display correctly

➤ Go to the storyboard and select the Image View (it may be hard to see on account of it being hidden, but you can still find it in the Document Outline). In the Attributes inspector, set its Content Mode to Aspect Fit.

Jxorqupp fmi onibu kiuq’t xudxoks kibe
Mrebxarl czu edake vaap’k hefvorg roxu

Zde ujkagc bisao iq fpa hgifu eg qasy ugyehh
Qme oszuwn virio um sho tdomi af zejd ujwehk

UI improvements

The user can take a photo — or pick one — now but the app doesn’t save it to the data store yet. Before you get to that, there are still a few improvements to make to the image picker.

Handling background mode

You saw in the Checklists app that the AppDelegate is notified by the operating system when the app is about to go to the background through its applicationDidEnterBackground(_:) method.

Removing notification observers

At this point, with iOS versions up to iOS 9.0, there’s one more thing you needed to do — you should tell the NotificationCenter to stop sending these background notifications when the Tag/Edit Location screen closes. You didn’t want NotificationCenter to send notifications to an object that no longer existed, that was just asking for trouble!

Cyu lemoyaurgkik xuyxead fxu faij pifqcahqen oym jku kbadife
Sja hemaxaokdmuj hihdaob zxi muus tumdruxvad uyy yqu sbozasi

Saving the image

The ability to pick photos is rather useless if the app doesn’t also save them. So, that’s what you’ll do here.

Data model changes

➤ Open the Data Model editor. Add a photoID attribute to the Location entity and give it the type Integer 32. This is an optional value — not all Locations will have photos — so make sure the Optional box is checked in the Data Model inspector.

Saving the image to a file

➤ In LocationDetailsViewController.swift, in the done() method, add the following in between where you set the properties of the Location object and where you save the managed object context:

Tfu rbepo ub ceqag in fxi agx’v Qebukebln goppuh
Fpa ztawa ex moref uj rpe oxn’k Ruzawexmt qirqoc

Verifying photoID in SQLite

If you have Liya or another SQLite inspection tool, you can verify that each Location object has been given a unique photoID value (in the ZPHOTOID column):

Mqu Guwawiog obfoxld qamc efuqoi hgeloIc bevoid ul Garo
Zyi Porabeub ijviphq lihp irihui cbogeEt hiziic ec Duxu

Editing the image

So far, all the changes you’ve made were for the Tag Location screen and adding new locations. Of course, you should make the Edit Location screen show the photos as well. The change to LocationDetailsViewController is quite simple.

Cleaning up on location deletion

Let’s add some code to remove the photo file, if it exists, when a Location object is deleted.

Thumbnails

Now that locations can have photos, it’s a good idea to show thumbnails for these photos in the Locations tab. That will liven up this screen a little… a plain table view with just a bunch of text isn’t particularly exciting.

Storyboard changes

➤ Go to the storyboard editor. In the prototype cell for the Locations scene, remove the leading Auto Layout constraint from each of the two labels, and set X = 76 in the View section of the Size inspector.

Gza kufru geap wugm kiw om uboho seir
Pku kepra weec fegt wof ig ohosa yaup

Code changes

➤ Go to LocationCell.swift and add the following method:

Egusox ad xza Hotukeoqt gaqku puig
Atopel iy byo Jaxaweilf qutwo buik

Extensions

So far you’ve used extensions on your view controllers to group related functionality together, such as delegate methods. But you can also use extensions to add new functionality to classes that you didn’t write yourself. That includes classes such as UIImage from the iOS frameworks.

Thumbnails via UIImage extension

You are going to add an extension to UIImage that lets you resize the image. You’ll use it as follows:

Zgo rsekor oce xxmokp zi yye zuqu ih jpe nlebcreacg
Dne ltewew ori czfoxc de pne cile ox cve fmoqrsaitd

Mji bhucjruipr sis hexo lyi haknaxt aqqolm xiria
Kdi zqegfyuocw gor sowe sbo foxxadt uprumk vuyuu

Ufjotx Ris lr. Aprawt Donf
Ubnajf Riz gc. Emfejn Nezd

Handling low-memory situations

The UIImagePickerController is very memory-hungry. Whenever the iPhone gets low on available memory, UIKit will send your app a “low memory” warning.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2026 Kodeco Inc.

You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now