skip to content

Native iOS / Apple

Native Apple app development in Swift with SwiftUI and UIKit, plus the persistence, networking, media and testing frameworks around them. iOS loops probe this whole surface, end to end.

on this pageshow

explore

questions

413 · 22 sections

In SwiftUI, how do you make an icon-only play button readable by VoiceOver, and what does SwiftUI already infer from Text, Image and Button?

level: juniorimportance: must knowfreq 78%
basics
~20 s

SwiftUI reads a Text's string, gives a Button its label content plus the button trait, and skips Image(decorative:). An icon-only button needs a spoken name: give it a title and hide it with .labelStyle(.iconOnly), or add .accessibilityLabel("Play").

open as a page

In SwiftUI, why does Text("Welcome back") show a translation while Text(hotelName) with a String variable does not, and what does Text(verbatim:) do?

level: juniorimportance: must knowfreq 76%
basics
~20 s

A string literal passed to Text becomes a LocalizedStringKey and is looked up in the app's strings; a String variable selects the StringProtocol initializer and is shown as written. Text(verbatim:) shows a literal without any lookup.

open as a page

In SwiftUI, how do you make a view fade or slide in and out when it is shown or hidden with transition(_:)?

level: juniorimportance: must knowfreq 70%
basics
~10 s

Show the view inside an if, attach transition(.opacity) or transition(.move(edge: .top)) to it, and toggle the Boolean inside withAnimation. SwiftUI then animates the view in on insertion and out on removal.

open as a page

In SwiftUI, how do you bind a Toggle and a Picker over an enum to a settings screen's state?

level: juniorimportance: must knowfreq 75%
basics
~20 s

Bind a Toggle to a Bool with Toggle("Title", isOn: $flag) and a Picker to an enum with Picker("Title", selection: $choice); give every row a tag of that enum type, which ForEach over an Identifiable enum does for you.

open as a page

In SwiftUI, how do you respond to taps with onTapGesture, and when should a Button replace the tap gesture?

level: juniorimportance: must knowfreq 70%
basics
~20 s

Attach onTapGesture(count:perform:) to a view to run code on a tap, or on a double tap with count: 2. When the view behaves like a button, use Button instead: it brings the standard button behaviour and accessibility users expect.

open as a page

In UIKit, how do you pin a view to the safe area with layout anchors, and why must translatesAutoresizingMaskIntoConstraints be set to false first?

level: juniorimportance: must knowfreq 80%
basics
~20 s

Build constraints from anchors against view.safeAreaLayoutGuide and switch them on together with NSLayoutConstraint.activate(_:). A view created in code turns its autoresizing mask into constraints by default, and those fight yours, so set translatesAutoresizingMaskIntoConstraints to false.

open as a page

In UIKit, how do you push and pop screens on a UINavigationController, and where does the Back button's title come from?

level: juniorimportance: must knowfreq 82%
basics
~10 s

A UINavigationController keeps a stack of view controllers: pushViewController(_:animated:) adds one on top, popViewController(animated:) removes the top one and popToRootViewController(animated:) returns to the first. The Back title comes from the previous screen's navigationItem.

open as a page

In a UIKit note editor, how do becomeFirstResponder(), resignFirstResponder() and endEditing(_:) decide whether the keyboard is on screen?

level: juniorimportance: must knowfreq 70%
basics
~20 s

UIKit shows the keyboard as the first responder's input view: becomeFirstResponder() on a text field or text view brings it up, resignFirstResponder() hides it, and endEditing(_:) resigns whichever view in a subtree is first responder.

open as a page

In a UIKit app, how do you show a new SwiftUI checkout screen inside an existing UINavigationController, and how does data reach it?

level: juniorimportance: must knowfreq 78%
basics
~20 s

Wrap the SwiftUI view in a UIHostingController(rootView:) and push that controller like any other. Data goes in through the root view's initializer or the rootView property, and events come back through closures or a shared model.

open as a page

In UIKit, how does a UITableView get its sections and rows from a UITableViewDataSource, and why must cells come from dequeueReusableCell(withIdentifier:for:)?

level: juniorimportance: must knowfreq 80%
basics
~20 s

A UITableView asks its dataSource for section and row counts, then calls tableView(_:cellForRowAt:) only for rows about to appear. dequeueReusableCell(withIdentifier:for:) returns a recycled or new cell of a registered type, so a long list keeps only about a screenful of cells.

open as a page

In Swift Charts, how do you plot a week of daily step counts from an array of structs as a bar chart?

level: juniorimportance: must knowfreq 55%
basics
~20 s

Pass the array to Chart and return one BarMark per element, giving x and y as PlottableValues built with .value("Day", entry.day, unit: .day) and .value("Steps", entry.steps); the elements must be Identifiable or you supply id:.

open as a page

In Swift Charts, what does foregroundStyle(by:) do that foregroundStyle(_:) does not, for steps split into walking and running?

level: middleimportance: should knowfreq 45%
basics
~10 s

foregroundStyle(by:) maps a data value to a colour through a scale, so each activity gets its own style, a legend appears and LineMarks split into series; foregroundStyle(_:) paints every mark one fixed ShapeStyle.

open as a page

In Swift Charts, how do you draw a 10,000-step goal line across a weekly bar chart and stop the y-axis rescaling every week?

level: middleimportance: should knowfreq 40%
basics
~10 s

Add one RuleMark(y: .value("Goal", 10_000)) beside a ForEach of BarMarks inside Chart { }, label it with annotation, and fix the axis with chartYScale(domain: 0...15_000) so it stops following each week's data.

open as a page

In Swift Charts on iOS 17 and later, how do you let a user scrub a heart-rate line chart with a finger and mark the selected sample?

level: seniorimportance: should knowfreq 35%
basics
~20 s

Bind chartXSelection(value:) to an optional Date; the chart writes the x value under the finger, you look up the nearest sample, and an if let in the Chart builder draws a RuleMark(x:) with an annotation for the reading.

open as a page

In Swift Charts, how do you show a year of daily step totals as a horizontally scrolling chart that opens on the latest week?

level: seniorimportance: nice to knowfreq 25%
basics
~10 s

From iOS 17, add chartScrollableAxes(.horizontal), set chartXVisibleDomain(length:) to one week in seconds, open with chartScrollPosition(initialX:) at the latest week's start, and snap with chartScrollTargetBehavior(.valueAligned(matching:)).

open as a page

With Combine, why does a sink on a view model's @Published property stop delivering values when you don't keep the AnyCancellable it returns?

level: juniorimportance: must knowfreq 80%
basics
~20 s

Combine's sink returns an AnyCancellable, and an AnyCancellable calls cancel() when it is deinitialized. If nothing keeps it, the subscription ends at once and later values never arrive; keep it in a property or with store(in:).

open as a page

With Combine, how do debounce, removeDuplicates and receive(on:) shape an airport search field's queries, and which queue does each stage deliver on?

level: middleimportance: must knowfreq 70%
basics
~20 s

debounce(for:scheduler:) passes a value only after the field has been quiet for the interval, delivering on that scheduler; removeDuplicates() then drops a query equal to the previous one; receive(on:) moves later stages to a scheduler such as DispatchQueue.main.

open as a page

With Combine, what does a new subscriber get from a PassthroughSubject, a CurrentValueSubject and an @Published property's $ publisher, and when?

level: middleimportance: should knowfreq 62%
basics
~20 s

A PassthroughSubject has no current value: a subscriber sees only later sends, and sends with no subscriber are dropped. A CurrentValueSubject and an @Published $ publisher send their current value on subscription, then each change; @Published sends in willSet, before the property changes.

open as a page

With Combine, why does a view model that calls assign(to:on: self) or captures self in sink, storing the token in its own Set, never deinit?

level: seniorimportance: should knowfreq 58%
basics
~20 s

Self owns the AnyCancellable, which keeps the subscriber, which holds self strongly: assign(to:on:) keeps its object and a sink keeps what its closure captures. An @Published upstream never completes, so the loop stays; use assign(to: &$property) (iOS 14) or [weak self].

open as a page

With Combine, why does a flight search that flatMaps each query into a request stop for good after one failed request and show stale results, and how do you fix both?

level: seniorimportance: should knowfreq 55%
basics
~20 s

A failed inner publisher fails the whole flatMap stream, and a catch or replaceError at the end only sends a fallback and finishes. Handle errors inside each query's publisher, then use map plus switchToLatest so a new query cancels the previous request.

open as a page

In Core Data, how do you build an NSFetchRequest for one region's bird sightings, newest first, and what does executing it return?

level: juniorimportance: must knowfreq 80%
basics
~20 s

Create an NSFetchRequest<Sighting> for the entity, set a predicate such as region == %@ and an NSSortDescriptor on the date, descending, then call the context's fetch(_:), which throws or returns a [Sighting] array, empty when nothing matches.

open as a page

In Core Data's model editor, what do the Class Definition, Category/Extension and Manual/None codegen settings generate for an entity, and when do you pick each?

level: juniorimportance: must knowfreq 66%
basics
~10 s

Class Definition generates the NSManagedObject subclass and its @NSManaged properties at build time; Category/Extension generates only the properties extension and you write the class; Manual/None generates nothing, so you own both files.

open as a page

In Core Data, how do you model a Course with many Lessons and Students taking many Courses, and why give each relationship an inverse?

level: juniorimportance: must knowfreq 72%
basics
~20 s

Give Lesson a to-one course and Course a to-many lessons, set each as the other's inverse, and pair Student.courses with Course.students for many-to-many. With inverses set, Core Data updates the other side whenever you change one.

open as a page

In Core Data, what does NSPersistentContainer build for you, and what must happen before its viewContext can save?

level: juniorimportance: must knowfreq 75%
basics
~10 s

NSPersistentContainer loads the managed object model it is named after, builds the persistent store coordinator and a main-queue viewContext. Nothing persists until loadPersistentStores(completionHandler:) has added each store description and reported every store's error.

open as a page

In Core Data, which queues do viewContext and a newBackgroundContext() context run on, and how do perform(_:), performAndWait(_:) and the async perform differ?

level: middleimportance: must knowfreq 78%
basics
~20 s

viewContext is a main-queue context for the UI; newBackgroundContext() returns a new private-queue context for imports. perform(:) queues a block and returns, performAndWait(:) blocks until it ends, and async perform suspends and returns its result.

open as a page

In SwiftData, what is the difference between a ModelContainer and a ModelContext, and which one do you insert and delete models through?

level: juniorimportance: must knowfreq 75%
basics
~20 s

A ModelContainer owns the schema and the persistent store; a ModelContext is the in-memory workspace where you insert, delete, edit and save models. You call insert(:) and delete(:) on a context, often the container's mainContext.

open as a page

In SwiftData, what does marking a class with the @Model macro give you, and why must a model be a class rather than a struct?

level: juniorimportance: must knowfreq 75%
basics
~20 s

@Model makes a class persistable: it adds PersistentModel and Observable conformance and rewrites each stored property to read and write SwiftData's backing data. It must be a class because PersistentModel is class-only and a context tracks each instance by identity.

open as a page

With SwiftData's @Query, how do you show a library's books in a SwiftUI List sorted by title, and when does that list update?

level: juniorimportance: must knowfreq 75%
basics
~20 s

Declare @Query(sort: \Book.title) var books: [Book] in the view and hand books to List. The query fetches from the environment's model context and stays in sync, so inserts, deletes and edits redraw the list without a refetch.

open as a page

In SwiftData, how do you declare that a Project model owns many Task models, with each task pointing back to its project?

level: juniorimportance: must knowfreq 65%
basics
~20 s

Give Project an array property of the task model and give the task an optional Project property. Name the pairing with @Relationship(inverse:) on one of the two, and SwiftData keeps both ends of the link in sync.

open as a page

In a SwiftUI app using SwiftData, how do you install the model container with the modelContainer modifier and reach the model context from a view?

level: juniorimportance: must knowfreq 72%
basics
~10 s

Apply modelContainer(for: Entry.self) to the WindowGroup or the root view. SwiftData builds the container and puts its main-actor ModelContext into the environment, and any descendant reads it with @Environment(.modelContext) to insert and delete models.

open as a page

With FileManager on iOS, how do you find your app's Documents directory, write a file there and read it back?

level: juniorimportance: must knowfreq 75%
basics
~10 s

Every iOS app writes only inside its own sandbox container. Get Documents from URL.documentsDirectory (iOS 16) or FileManager.default.urls(for: .documentDirectory, in: .userDomainMask), append a file name, write with Data.write(to:options:) and read back with Data(contentsOf:).

open as a page

With FileManager on iOS, where should a document-scanning app keep scanned PDFs, page thumbnails and a downloaded text-recognition model, and why?

level: middleimportance: must knowfreq 70%
basics
~20 s

Scanned PDFs go in Documents, which is backed up. Thumbnails go in Library/Caches, which is not backed up and may be emptied when storage is low. The model goes in Library/Application Support, marked isExcludedFromBackup because it can be downloaded again.

open as a page

With FileManager on iOS, how does a scanning app share its latest scan with its share extension, and what breaks if misconfigured?

level: middleimportance: should knowfreq 45%
basics
~20 s

An app and its extension have separate sandboxes, so shared files live in an App Group container. Give both targets the same App Groups entitlement and call containerURL(forSecurityApplicationGroupIdentifier:), which returns nil on iOS for a wrong identifier.

open as a page

With FileManager on iOS, why does a scanning app's background task fail to read its scan index while the phone is locked, though the same read works with the app open?

level: seniorimportance: should knowfreq 30%
basics
~20 s

The index was written with FileProtectionType.complete, which makes a file unreadable while the device is locked. Files that locked-phone background work needs should use completeUntilFirstUserAuthentication, readable after the first unlock since boot, while user documents can stay complete.

open as a page

With FileManager on iOS, a scanning app saved each scan's absolute path in its database, and after an app update the scans seem gone: why, and what fixes it?

level: seniorimportance: should knowfreq 40%
basics
~20 s

An iOS app's container path is not guaranteed to survive an update, reinstall or restore, so stored absolute paths name a folder that no longer exists. Store a base folder plus a relative path and rebuild the URL from URL.documentsDirectory.

open as a page

With Keychain Services on iOS, how do you save, read and delete a member's refresh token using the SecItem functions?

level: juniorimportance: must knowfreq 75%
basics
~10 s

Build a dictionary with kSecClass set to kSecClassGenericPassword plus kSecAttrService and kSecAttrAccount, then call SecItemAdd with kSecValueData, SecItemCopyMatching with kSecReturnData, and SecItemDelete; each returns an OSStatus to check.

open as a page

With Keychain Services, why does SecItemAdd return errSecDuplicateItem when an app saves a refreshed token, and how should the save be written?

level: middleimportance: must knowfreq 60%
basics
~20 s

A generic password with the same kSecAttrService, kSecAttrAccount, access group and synchronizable flag already exists, so SecItemAdd refuses a second one. Write the save as SecItemUpdate with the new kSecValueData, calling SecItemAdd only when the update returns errSecItemNotFound.

open as a page

With Keychain Services, how do you require Face ID before a car-sharing app reads its digital-key secret, and why does the read fail after the member re-enrols Face ID?

level: seniorimportance: must knowfreq 60%
basics
~20 s

Store the secret with a SecAccessControl built by SecAccessControlCreateWithFlags using .biometryCurrentSet, and read it with an LAContext under kSecUseAuthenticationContext. Re-enrolling Face ID invalidates such an item, so the app must delete it and re-provision after sign-in.

open as a page

With Keychain Services, why does a car-sharing app's background token refresh get errSecInteractionNotAllowed while the phone is locked or freshly rebooted, and how do you fix it?

level: seniorimportance: must knowfreq 55%
basics
~20 s

The token has the default kSecAttrAccessibleWhenUnlocked class, so a locked phone yields errSecInteractionNotAllowed. Store it as kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly and treat the status as retry later: before the first unlock after a reboot, no supported class is readable.

open as a page

With Keychain Services, how does a car-sharing app share its digital-key secret with its widget extension, and what breaks when the access group is wrong?

level: middleimportance: should knowfreq 35%
basics
~20 s

Give the app and the widget extension the same Team ID-prefixed keychain-access-groups entry, and add and query the item with kSecAttrAccessGroup set to it. Otherwise the item lands in the app's private group and the widget gets errSecItemNotFound.

open as a page

With URLSession's async data(for:) on iOS, how do you fetch and decode a JSON list, and why must you check the HTTP status code yourself?

level: juniorimportance: must knowfreq 82%
basics
~10 s

Await URLSession.shared.data(for: request), cast the returned URLResponse to HTTPURLResponse, require a 200-299 statusCode, then decode the Data. data(for:) throws when the transfer fails, not because the server answered 404 or 500.

open as a page

With URLSession on iOS, how do URLSession.shared, a default configuration and an ephemeral configuration differ, and which suits an incognito trip planner?

level: middleimportance: must knowfreq 66%
basics
~20 s

URLSession.shared is a fixed singleton with no delegate, using the shared cache, cookie and credential stores. A default configuration starts the same but is customisable. An ephemeral one keeps private stores in memory only, which suits an incognito planner.

open as a page

With URLSession, how do you set URLCache and URLRequest.CachePolicy so a transit app's live departures are never stale while its timetable still loads offline?

level: middleimportance: should knowfreq 52%
basics
~10 s

Give live-departure requests cachePolicy .reloadIgnoringLocalCacheData so URLCache never answers them, and give timetable requests .returnCacheDataElseLoad. URLCache can be purged, so a timetable that must work offline belongs in a downloaded file.

open as a page

With a background URLSession, how does an iOS transit app download offline timetable packs overnight and handle being relaunched when they finish?

level: seniorimportance: should knowfreq 46%
basics
~20 s

Create the session from URLSessionConfiguration.background(withIdentifier:) with a delegate, start download tasks, and let the system transfer them. On relaunch, recreate the session with the same identifier, move each file in didFinishDownloadingTo, and call the stored completion handler after urlSessionDidFinishEvents.

open as a page

With URLSession, a transit app's vehicle-position stream and an old completion-handler request keep running after the screen closes; how does cancellation reach each, and what error arrives?

level: seniorimportance: should knowfreq 58%
basics
~20 s

Cancelling the Swift Task cancels an awaiting data(for:) or bytes(for:) call; a dataTask(with:completionHandler:) task ignores it, so keep that task and call cancel(). Either way a cancellation error, usually URLError .cancelled, arrives and the UI should ignore it.

open as a page

With ASWebAuthenticationSession, why does an iOS app run its web sign-in there instead of in its own WKWebView, and how does the result come back?

level: juniorimportance: must knowfreq 70%
basics
~20 s

ASWebAuthenticationSession shows the sign-in page in a secure system browser view that can reuse the user's Safari login, and the app never touches the page; the final redirect to the callback URL reaches the app's completion handler.

open as a page

With Sign in with Apple in AuthenticationServices, how do you request a member's name and email, and why check getCredentialState(forUserID:completion:) on each launch?

level: middleimportance: must knowfreq 65%
basics
~10 s

Create an ASAuthorizationAppleIDProvider request with requestedScopes [.fullName, .email], run it through ASAuthorizationController, and keep the credential's user identifier; on launch, getCredentialState(forUserID:completion:) says whether that Apple ID authorization is still authorized, revoked or not found.

open as a page

In ASWebAuthenticationSession, what does prefersEphemeralWebBrowserSession change, when must you set it, and what does it cost your users?

level: middleimportance: should knowfreq 50%
basics
~20 s

Setting prefersEphemeralWebBrowserSession to true before start() asks the browser neither to use the member's existing browsing data nor to keep what this sign-in creates, so each sign-in starts clean and the member must type credentials again.

open as a page

In AuthenticationServices on iOS 17.4 and later, how does ASWebAuthenticationSession.Callback let a web sign-in finish on an https URL, and what must be set up?

level: middleimportance: should knowfreq 40%
basics
~10 s

From iOS 17.4, init(url:callback:completionHandler:) takes an ASWebAuthenticationSession.Callback; .https(host:path:) ends the session when the page navigates to that host and path, and the host must be associated with the app through a webcredentials associated domain.

open as a page

In AuthenticationServices, a passkey sign-in through ASAuthorizationPlatformPublicKeyCredentialProvider returns an error with no sheet for members who have a passkey on the website; what do you check, and how should the requests be set up?

level: seniorimportance: should knowfreq 40%
basics
~20 s

Passkey requests need the relying party's domain in a webcredentials associated domain, with an apple-app-site-association file listing the app; without it the request returns an error. Then check the relyingPartyIdentifier matches, and that the device actually holds a credential.

open as a page

In iOS's Background Tasks framework, what is the difference between BGAppRefreshTaskRequest and BGProcessingTaskRequest, and when do you use each?

level: juniorimportance: must knowfreq 60%
basics
~20 s

BGAppRefreshTaskRequest asks iOS for a brief background launch to fetch small content updates; BGProcessingTaskRequest asks for minutes of deferrable work such as maintenance, which runs only while the device is idle. iOS decides when either runs.

open as a page

With BGTaskScheduler, what must a podcast app register, declare in Info.plist and submit before its episode-list refresh can ever run?

level: middleimportance: must knowfreq 55%
basics
~20 s

List the identifier in BGTaskSchedulerPermittedIdentifiers with the fetch background mode, register its launch handler before the app finishes launching, then submit a BGAppRefreshTaskRequest, and submit a fresh one on every run because each request runs once.

open as a page

In iOS's Background Tasks framework, what must a launch handler do with expirationHandler and setTaskCompleted(success:), and what breaks when either is missing?

level: seniorimportance: must knowfreq 45%
basics
~20 s

Assign expirationHandler to cancel the work quickly, and call setTaskCompleted(success:) exactly once when the work ends on any path. Without a handler the system marks the task failed; without completion the app burns its time and may be killed.

open as a page

Between UIKit's beginBackgroundTask(withName:expirationHandler:) and iOS 26's BGContinuedProcessingTaskRequest, which do you use for a transcript export a podcast listener starts and then leaves, and why?

level: seniorimportance: should knowfreq 30%
basics
~20 s

Use UIKit's beginBackgroundTask(withName:expirationHandler:) to finish a short job, seconds of work, as the app leaves the foreground. A multi-minute export the listener tapped belongs in iOS 26's BGContinuedProcessingTaskRequest, which keeps running with visible, cancellable progress.

open as a page

A podcast app's BGTaskScheduler episode refresh never seems to run during testing; how do you diagnose it, and how do you force a launch and an expiration from the debugger?

level: seniorimportance: should knowfreq 35%
basics
~10 s

Check that register returns true during launch and that submission succeeds, reading the BGTaskScheduler.Error code, on a real device. Then, paused in LLDB after a successful submit, call the private _simulateLaunchForTaskWithIdentifier: and _simulateExpirationForTaskWithIdentifier: methods.

open as a page

With UserNotifications, how does an iOS app ask for notification permission and schedule a one-off local reminder two hours before a concert's doors open?

level: juniorimportance: must knowfreq 75%
basics
~10 s

Call requestAuthorization(options:) on UNUserNotificationCenter.current() with .alert, .sound and .badge, then build UNMutableNotificationContent, a UNCalendarNotificationTrigger for two hours before doors open, and add a UNNotificationRequest with a stable identifier.

open as a page

With UserNotifications, how do UNUserNotificationCenterDelegate's willPresent and didReceive callbacks handle a concert reminder in the foreground and its action buttons?

level: middleimportance: must knowfreq 70%
basics
~10 s

userNotificationCenter(:willPresent:withCompletionHandler:) runs while the app is in the foreground and returns options such as .banner, .list and .sound; userNotificationCenter(:didReceive:withCompletionHandler:) runs when the person taps or picks an action, and switches on actionIdentifier.

open as a page

In UIKit, how does an iOS app register with APNs for a device token, and what should it do with that token on every launch?

level: middleimportance: should knowfreq 62%
basics
~10 s

Call UIApplication's registerForRemoteNotifications() on every launch; APNs answers in application(_:didRegisterForRemoteNotificationsWithDeviceToken:) with a Data token that the app hex-encodes and sends to its server, or in didFailToRegisterForRemoteNotificationsWithError.

open as a page

With a UNNotificationServiceExtension, how does an iOS app add a seat-map image to a push, and what happens when the download outlasts its time?

level: seniorimportance: should knowfreq 35%
basics
~20 s

Add a Notification Service Extension target, send the push with mutable-content: 1 and alert text, download the image in didReceive(_:withContentHandler:), attach it as a UNNotificationAttachment and call the handler; near the roughly 30-second limit, serviceExtensionTimeWillExpire() must deliver fallback content.

open as a page

An iOS concert app's silent push to refresh set times never reaches application(_:didReceiveRemoteNotification:fetchCompletionHandler:) on testers' iPhones; what do you check?

level: seniorimportance: should knowfreq 55%
basics
~20 s

Check that Background Modes has Remote notification enabled, that aps holds only content-available: 1 with no alert, sound or badge, and that the handler calls its completion handler on every path; then remember iOS throttles silent pushes and skips force-quit apps.

open as a page

In Core Location, how does an iOS app ask for when-in-use location permission, and what must its Info.plist contain first?

level: juniorimportance: must knowfreq 75%
basics
~10 s

Add NSLocationWhenInUseUsageDescription to Info.plist, then call requestWhenInUseAuthorization() on a CLLocationManager while its authorizationStatus is notDetermined. The system prompts once and reports the answer through locationManagerDidChangeAuthorization(_:).

open as a page

In Core Location, how does CLLocationUpdate.liveUpdates differ from CLLocationManager's delegate updates, and how does each trade accuracy against battery?

level: middleimportance: must knowfreq 62%
basics
~10 s

liveUpdates(:), added in iOS 17, returns an async sequence of CLLocationUpdate values tuned by one LiveConfiguration. The delegate API pushes arrays to locationManager(:didUpdateLocations:) and is tuned with desiredAccuracy, distanceFilter, activityType and automatic pausing.

open as a page

A dog-walking app's route recording stops minutes after the walker locks the iPhone; what in Core Location do you check, and in what order?

level: seniorimportance: must knowfreq 58%
basics
~10 s

Check that UIBackgroundModes includes location, that a CLLocationManager sets allowsBackgroundLocationUpdates to true or a liveUpdates loop holds a CLBackgroundActivitySession started in the foreground, and that automatic pausing has not ended updates.

open as a page

In Core Location, when a walker grants only approximate location, how do you request temporary full accuracy, and why can that request fail?

level: middleimportance: should knowfreq 45%
basics
~10 s

When accuracyAuthorization is .reducedAccuracy, call requestTemporaryFullAccuracyAuthorization(withPurposeKey:) with a key from NSLocationTemporaryUsageDescriptionDictionary. It fails with CLError.Code.promptDeclined if the key is missing, the app already has full accuracy, or it runs in the background.

open as a page

With Core Location's CLMonitor, how do you detect a walk entering the park, and which limits and relaunch rules apply?

level: seniorimportance: should knowfreq 38%
basics
~20 s

Open a monitor with await CLMonitor("name"), add a CLMonitor.CircularGeographicCondition with an identifier, and iterate monitor.events for .satisfied and .unsatisfied states. An app may monitor at most 20 conditions, and after a relaunch it must reopen the same-named monitor.

open as a page

In Core Animation, what is a UIView's backing CALayer, and why does setting cornerRadius alone not clip an image view's picture to a circle?

level: juniorimportance: must knowfreq 70%
basics
~20 s

Every UIView renders through a backing CALayer created from its layerClass, with the view as the layer's delegate. A layer's cornerRadius rounds only its background and border; the image in its contents is clipped once masksToBounds is true.

open as a page

In Core Animation, why does a breathing ring's CABasicAnimation on strokeEnd snap back to empty when it ends, and what are the two fixes?

level: middleimportance: must knowfreq 75%
basics
~20 s

An explicit CABasicAnimation changes only the displayed value, not the layer's model strokeEnd, and is removed when it ends, so the ring jumps back. Set the model value before adding the animation, or keep the animation with isRemovedOnCompletion false and fillMode forwards.

open as a page

In Core Animation, why does changing a standalone CAShapeLayer's strokeEnd animate by itself while a view's backing layer does not, and how does CATransaction control it?

level: middleimportance: should knowfreq 60%
basics
~20 s

Changing an animatable property on a standalone layer runs its implicit action, a 0.25-second animation by default. A view's backing layer asks the view, its delegate, which supplies none outside a UIView animation block. CATransaction sets duration, timing, completion, or disables actions.

open as a page

In Core Animation, taps on the visible edge of a breathing app's bubble layer miss while it shrinks on an exhale; why, and how do you hit-test what is on screen?

level: seniorimportance: should knowfreq 50%
basics
~20 s

Hit testing a layer reads the model layer, which already holds the animation's end values, while the screen shows the presentation layer. Call presentation() on the moving layer and hit-test or read its frame there, with the touch converted into the superlayer's coordinates.

open as a page

In UIKit, how do you draw a rounded rectangle in a custom view's draw(_:), and how do you make it redraw?

level: juniorimportance: must knowfreq 70%
basics
~10 s

Subclass UIView, override draw(:), build a UIBezierPath(roundedRect:cornerRadius:), set a colour with setFill() or setStroke() and call fill() or stroke(). To redraw, call setNeedsDisplay(); UIKit runs draw(:) on its next drawing cycle.

open as a page

With UIGraphicsImageRenderer, how do you stamp a captured signature onto a delivery receipt photo, and what does the format's scale decide?

level: middleimportance: must knowfreq 60%
basics
~20 s

Create a UIGraphicsImageRenderer with the receipt's size and a format, then call image(actions:): draw the photo, then stroke the signature path. The format's scale sets how many pixels each point becomes, which fixes the image's resolution and memory.

open as a page

In a UIKit signature pad that calls setNeedsDisplay() on every touch move, why does the ink lag on a large iPad, and how do you fix it?

level: seniorimportance: must knowfreq 58%
basics
~20 s

setNeedsDisplay() invalidates the whole bounds, so each touch repaints every pixel of the view and re-strokes a path that keeps growing, all on the main thread. Invalidate only the new segment with setNeedsDisplay(_:) and flatten finished strokes into a cached image.

open as a page

In Core Graphics, how do you fill a rounded route-summary header with a CGGradient, and why wrap the clip in saveGState() and restoreGState()?

level: middleimportance: should knowfreq 52%
basics
~20 s

Clip the context to the rounded path, then call drawLinearGradient(_:start:end:options:), which fills the whole current clip. The clip is part of the graphics state and only shrinks, so saveGState() before it and restoreGState() after let later drawing use the full view again.

open as a page

In UIKit's draw(_:), why does a CGImage drawn with CGContext's draw(_:in:) come out upside down, and how do you fix it?

level: seniorimportance: should knowfreq 45%
basics
~20 s

Quartz's default space has its origin at the bottom-left with y up; UIKit flips its contexts to top-left with y down. CGContext's draw(_:in:) places the image in Quartz terms, so it lands upside down. Draw a UIImage instead, or flip locally.

open as a page

With AVKit, how do you play a remote lesson video in AVPlayerViewController, and which AVAudioSession category keeps its sound on in silent mode?

level: juniorimportance: must knowfreq 72%
basics
~20 s

Create an AVPlayer from the URL, assign it to an AVPlayerViewController's player property, present the controller and call play(). Set the AVAudioSession category to .playback first; the default soloAmbient category is silenced by the Silent switch.

open as a page

In AVFoundation, how do you configure an AVCaptureSession to film a dance routine with camera and microphone, and where should startRunning() be called?

level: middleimportance: must knowfreq 62%
basics
~10 s

Check camera and microphone authorization, then between beginConfiguration() and commitConfiguration() add an AVCaptureDeviceInput per device and an AVCaptureMovieFileOutput, checking canAddInput and canAddOutput. Call startRunning() on a serial background queue, because it blocks.

open as a page

In a dance-class app, a phone call interrupts the AVPlayer lesson and playback never resumes afterwards; how do you diagnose and fix it with AVAudioSession?

level: seniorimportance: must knowfreq 48%
basics
~20 s

AVPlayer pauses itself when the call interrupts the audio session, but resuming is the app's job: observe the interruption notification, and on .ended with .shouldResume reactivate the session and call play(). On iOS 27, observe resumptionRecommendationNotification instead.

open as a page

With AVFAudio, how do you record a spoken count-in as a voice note with AVAudioRecorder, starting from the microphone permission request?

level: middleimportance: should knowfreq 50%
basics
~10 s

Request permission with AVAudioApplication.requestRecordPermission() (iOS 17), set the audio session to .playAndRecord and activate it, then create AVAudioRecorder with a file URL and a settings dictionary and call record(); stop() finishes the file.

open as a page

With AVFoundation, how do you join trimmed dance clips into one lesson video with AVMutableComposition and export it, and why might the result play sideways?

level: seniorimportance: should knowfreq 32%
basics
~20 s

Load each AVURLAsset's duration and tracks asynchronously, insert each clip's time range into composition tracks at a running cursor, copy the source track's preferredTransform, then export with AVAssetExportSession's export(to:as:). A missing preferredTransform makes it play sideways.

open as a page

With iOS unified logging, why should an app write diagnostics with Logger(subsystem:category:) instead of print, and what do subsystem and category add?

level: juniorimportance: must knowfreq 72%
basics
~20 s

Logger writes each message into the unified logging system with a level, a subsystem and a category, so it can be filtered, kept by severity and redacted for privacy. print emits plain text with none of that.

open as a page

With iOS unified logging, which Logger levels stay in memory only and which persist to disk, and how do you choose a level?

level: middleimportance: must knowfreq 62%
basics
~20 s

Debug and info normally stay in memory only; notice (the default), error and fault also go to the on-disk store until it fills and purges old entries. Pick the lowest level that survives until someone reads it.

open as a page

With iOS unified logging, a boat-rental app's collected logs show every renter ID as <private>; why, and how do you keep one renter's lines correlatable without revealing the ID?

level: seniorimportance: must knowfreq 58%
basics
~20 s

Interpolated strings default to .auto privacy, which redacts dynamic strings, so the ID appears as <private>. Log it with privacy: .private(mask: .hash): equal IDs then share a hash, which correlates lines without revealing the value.

open as a page

With iOS unified logging, how does support pull a renter's iPhone logs onto a Mac and filter them to the app, and what can an in-app OSLogStore export see?

level: seniorimportance: should knowfreq 30%
basics
~10 s

Run log collect --device on a Mac to get a .logarchive, then filter it in Console or log show by subsystem and category. In the app, OSLogStore(scope: .currentProcessIdentifier) reads only the current process's entries.

open as a page

With OSSignposter, how do you measure how long a boat-rental app's Bluetooth dock unlock takes, and what goes wrong when two unlocks overlap under one signpost ID?

level: seniorimportance: should knowfreq 32%
basics
~20 s

Create an OSSignposter, make a signpost ID per unlock, call beginInterval before sending the command and endInterval with the same name and returned state when the lock replies. Overlapping unlocks sharing the default .exclusive ID cannot be paired reliably.

open as a page

In TestFlight, how do internal and external testers differ, and how does a new build reach each kind of tester?

level: juniorimportance: must knowfreq 70%
basics
~20 s

Internal testers are App Store Connect users with access to the app, up to 100, and get builds without review; external testers, up to 10,000 per app, join by email or public link, and their builds may need TestFlight App Review.

open as a page

In TestFlight, why does a ski-resort app's first external build wait for TestFlight App Review when the internal QA group already has it?

level: middleimportance: should knowfreq 38%
basics
~20 s

Internal groups can test a build as soon as it is Ready to Submit, but the first build added to an external group goes to TestFlight App Review, which checks the build and its test information before external testers can install it.

open as a page

In TestFlight, what does a build's Missing Compliance status mean, and how do you stop later builds of the app hitting it?

level: middleimportance: should knowfreq 30%
basics
~20 s

Missing Compliance means the build has no export compliance answer for its encryption use. Answer the questions or attach approved documentation in TestFlight; declaring encryption use in Info.plist with ITSAppUsesNonExemptEncryption stops each new build asking.

open as a page

In TestFlight, season-pass testers of a ski-resort app say their beta build has disappeared mid-test; what happened, and how do you manage a build's lifetime?

level: seniorimportance: should knowfreq 28%
basics
~20 s

A TestFlight build is testable for up to 90 days and then becomes Expired, or someone clicked Expire Build; either way testers can no longer install it. Keep a newer build in the group before the window ends.

open as a page

In XCTest, what makes a method in an XCTestCase subclass a test, and when do setUp() and tearDown() run around it?

level: juniorimportance: must knowfreq 72%
basics
~20 s

A test is an instance method of an XCTestCase subclass whose name starts with test and that takes no parameters and returns nothing. Instance setUp() runs before every test method and tearDown() after it; the class versions run once per class.

open as a page

In XCTest, how do you test a service-record client's async fetch method and its completion-handler fetch method?

level: middleimportance: must knowfreq 78%
basics
~20 s

Call the async method from a test marked async throws and assert on the awaited result. For the completion handler, create an expectation, fulfil it in the callback, then await fulfillment(of:timeout:), or call wait(for:timeout:) from a synchronous test.

open as a page

In XCTest, why does XCTAssertEqual fail on a computed Double such as an average fuel consumption, and how does accuracy fix it?

level: juniorimportance: should knowfreq 55%
basics
~10 s

Double stores most decimals approximately, so (5.9 + 6.2 + 6.2) / 3 is 6.1000000000000005 and plain XCTAssertEqual fails. XCTAssertEqual(::accuracy:) passes when the two values differ by no more than the accuracy.

open as a page

In XCTest, how do XCTUnwrap, XCTAssertThrowsError and XCTSkip behave inside a test method marked throws?

level: middleimportance: should knowfreq 58%
basics
~20 s

XCTUnwrap records a failure and throws when its value is nil, so a throwing test stops cleanly instead of crashing. XCTAssertThrowsError fails unless its expression throws and passes the error to a closure. Throwing XCTSkip reports the test as skipped.

open as a page

An XCTest callback test passes even when its completion handler never runs, and later raises an exception when the handler fires twice; what is wrong with its expectations?

level: seniorimportance: should knowfreq 60%
basics
~20 s

The test never really waits on the expectation its callback fulfils, so it ends first and passes vacuously. The exception comes from fulfilling an expectation more often than expectedFulfillmentCount allows: expectation(description:) sets assertForOverFulfill to true.

open as a page

In XCUITest, how do you find a button by its accessibility identifier, tap it, and type text into a search field?

level: juniorimportance: must knowfreq 80%
basics
~20 s

Query from the XCUIApplication proxy, such as app.buttons["payButton"], then call tap(). For typing, tap the field so it has keyboard focus, then call typeText(_:). Identifiers beat labels because they don't change when the visible text does.

open as a page

In XCUITest, how do launchArguments and launchEnvironment put the app into a known state, and why can't the test set that state directly?

level: middleimportance: must knowfreq 68%
basics
~20 s

The UI test runs in its own process and sees only what accessibility exposes, so it can't touch the app's objects. It sets XCUIApplication's launchArguments and launchEnvironment before launch(), and the app reads them at startup to choose stubs and test data.

open as a page

In XCUITest, why use waitForExistence(timeout:) instead of sleep, and why can an element that exists still fail isHittable?

level: middleimportance: must knowfreq 75%
basics
~20 s

waitForExistence(timeout:) returns true as soon as the element exists and false at the timeout, so a test waits only as long as it needs. exists means the element is in the UI tree; isHittable also needs it onscreen and not covered.

open as a page

In XCUITest, how do you capture a screenshot of a receipt screen and keep it in the test results even when the test passes?

level: middleimportance: should knowfreq 32%
basics
~10 s

Call screenshot() on an XCUIElement or on XCUIScreen.main, wrap the XCUIScreenshot in XCTAttachment(screenshot:), and add it to the test. Set lifetime to .keepAlways, because the default .deleteOnSuccess throws it away when the test passes.

open as a page

An XCUITest tapping app.buttons["payButton"] fails now and then because the query matches two buttons; why does that happen, and how do you fix it?

level: seniorimportance: should knowfreq 55%
basics
~20 s

tap() resolves the query when it runs, and several matches raise an error. A second view sharing the identifier, like a sheet still animating away, causes it. Wait for that view to go, scope the query, or make identifiers unique.

open as a page

In Swift Testing, how do you declare a test with @Test, check a result with #expect, and add a display name and traits?

level: juniorimportance: must knowfreq 75%
basics
~20 s

Mark any function with @Test and check results with #expect(condition), which records a failure with the captured values and lets the test continue. @Test also takes an optional display-name string followed by traits such as .tags, .disabled or .enabled(if:).

open as a page

In Swift Testing, when should a test use #require instead of #expect, and how does #expect(throws:) check for a specific error?

level: middleimportance: must knowfreq 62%
basics
~20 s

#expect records a failure and lets the test continue; try #require records it, then throws to end the test, and unwraps optionals. #expect(throws:) given an error type or an equal error value passes only when its closure throws a match.

open as a page

In Swift Testing, how does @Test(arguments:) turn a table of currency-conversion cases into test cases, and what changes with two collections or zip?

level: middleimportance: should knowfreq 55%
basics
~20 s

@Test(arguments:) calls the function once per element, and each call is a separate test case reported with its arguments and run in parallel. Two collections produce every combination of their elements; zip pairs them by position instead.

open as a page

Swift Testing tests that pass one at a time fail when the whole target runs; why does parallel execution cause this, and what does .serialized fix and not fix?

level: seniorimportance: should knowfreq 45%
basics
~20 s

Swift Testing runs tests and parameterized cases in parallel by default, in one process, so tests sharing global state race. .serialized orders one suite's tests but not tests elsewhere; per-test state is the real fix.

open as a page

When adopting Swift Testing in an iOS codebase with thousands of XCTest tests, do you migrate everything, run both side by side, or write only new tests in it?

level: principalimportance: should knowfreq 35%
basics
~20 s

Usually run both side by side: one test target holds XCTest classes and @Test functions, so new tests use Swift Testing, old ones migrate when touched, and UI and performance tests stay on XCTest, which Swift Testing does not replace.

open as a page