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 pageshowhide
explore
- SwiftUI207 questions
- Views and Composition17 questions
- Visual Content18 questions
- Lists and Scrolling11 questions
- Modifiers and Layout Negotiation32 questions
- Sources of Truth30 questions
- Navigation Containers and Modals22 questions
- Animating State Changes16 questions
- User Input and Controls22 questions
- Accessible, Localized Interfaces11 questions
- Lifecycle and Previews16 questions
- Testability and Profiling12 questions
- UIKit36 questions
- View Controller Lifecycle6 questions
- Auto Layout & Constraints6 questions
- Table & Collection Views6 questions
- Responder Chain & Events6 questions
- Navigation & Presentation6 questions
- SwiftUI Bridging6 questions
- Swift Charts6 questions
- Lottieempty
- Combine6 questions
- RxSwiftempty
- Core Data33 questions
- Managed Object Model5 questions
- Persistent Stack Setup5 questions
- Managed Object Contexts6 questions
- Fetch Requests & Predicates5 questions
- Relationships & Faulting6 questions
- Migrations & Versioning6 questions
- SwiftData30 questions
- @Model & Schema Macros5 questions
- ModelContainer & Context5 questions
- @Query & Fetching4 questions
- Relationships & Graph6 questions
- Schema Migrations5 questions
- SwiftUI Integration5 questions
- Realmempty
- GRDBempty
- FileManager6 questions
- Keychain Services6 questions
- CloudKitempty
- iCloudempty
- URLSession6 questions
- Alamofireempty
- Moyaempty
- Nukeempty
- AuthenticationServices6 questions
- Universal Links & URL Entry5 questions
- Background Tasks6 questions
- User Notifications & Push6 questions
- Core Location6 questions
- Core Animation6 questions
- Core Graphics6 questions
- Core Imageempty
- AVFoundation6 questions
- Core Audioempty
- Core MLempty
- ARKitempty
- MapKitempty
- HealthKitempty
- GameKitempty
- CocoaPodsempty
- Carthageempty
- XCFrameworkempty
- Unified Logging6 questions
- swift-logempty
- CocoaLumberjackempty
- TestFlight6 questions
- XCTest6 questions
- XCUITest6 questions
- Swift Testing6 questions
questions
413 · 22 sectionsIn SwiftUI, how do you make an icon-only play button readable by VoiceOver, and what does SwiftUI already infer from Text, Image and Button?
basics
~20 sSwiftUI 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").
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?
basics
~20 sA 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.
In SwiftUI, how do you make a view fade or slide in and out when it is shown or hidden with transition(_:)?
basics
~10 sShow 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.
In SwiftUI, how do you bind a Toggle and a Picker over an enum to a settings screen's state?
basics
~20 sBind 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.
In SwiftUI, how do you respond to taps with onTapGesture, and when should a Button replace the tap gesture?
basics
~20 sAttach 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.
In UIKit, how do you pin a view to the safe area with layout anchors, and why must translatesAutoresizingMaskIntoConstraints be set to false first?
basics
~20 sBuild 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.
In a UIKit note editor, how do becomeFirstResponder(), resignFirstResponder() and endEditing(_:) decide whether the keyboard is on screen?
basics
~20 sUIKit 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.
In a UIKit app, how do you show a new SwiftUI checkout screen inside an existing UINavigationController, and how does data reach it?
basics
~20 sWrap 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.
In UIKit, how does a UITableView get its sections and rows from a UITableViewDataSource, and why must cells come from dequeueReusableCell(withIdentifier:for:)?
basics
~20 sA 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.
In Swift Charts, how do you plot a week of daily step counts from an array of structs as a bar chart?
basics
~20 sPass 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:.
In Swift Charts, what does foregroundStyle(by:) do that foregroundStyle(_:) does not, for steps split into walking and running?
basics
~10 sforegroundStyle(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.
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?
basics
~10 sAdd 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.
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?
basics
~20 sBind 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.
In Swift Charts, how do you show a year of daily step totals as a horizontally scrolling chart that opens on the latest week?
basics
~10 sFrom 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:)).
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?
basics
~20 sCombine'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:).
With Combine, how do debounce, removeDuplicates and receive(on:) shape an airport search field's queries, and which queue does each stage deliver on?
basics
~20 sdebounce(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.
With Combine, what does a new subscriber get from a PassthroughSubject, a CurrentValueSubject and an @Published property's $ publisher, and when?
basics
~20 sA 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.
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?
basics
~20 sSelf 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].
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?
basics
~20 sA 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.
In Core Data, how do you build an NSFetchRequest for one region's bird sightings, newest first, and what does executing it return?
basics
~20 sCreate 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.
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?
basics
~10 sClass 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.
In Core Data, how do you model a Course with many Lessons and Students taking many Courses, and why give each relationship an inverse?
basics
~20 sGive 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.
In Core Data, what does NSPersistentContainer build for you, and what must happen before its viewContext can save?
basics
~10 sNSPersistentContainer 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.
In Core Data, which queues do viewContext and a newBackgroundContext() context run on, and how do perform(_:), performAndWait(_:) and the async perform differ?
basics
~20 sviewContext 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.
In SwiftData, what is the difference between a ModelContainer and a ModelContext, and which one do you insert and delete models through?
basics
~20 sA 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.
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?
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.
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?
basics
~20 sDeclare @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.
In SwiftData, how do you declare that a Project model owns many Task models, with each task pointing back to its project?
basics
~20 sGive 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.
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?
basics
~10 sApply 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.
With FileManager on iOS, how do you find your app's Documents directory, write a file there and read it back?
basics
~10 sEvery 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:).
With FileManager on iOS, where should a document-scanning app keep scanned PDFs, page thumbnails and a downloaded text-recognition model, and why?
basics
~20 sScanned 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.
With FileManager on iOS, how does a scanning app share its latest scan with its share extension, and what breaks if misconfigured?
basics
~20 sAn 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.
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?
basics
~20 sThe 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.
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?
basics
~20 sAn 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.
With Keychain Services on iOS, how do you save, read and delete a member's refresh token using the SecItem functions?
basics
~10 sBuild 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.
With Keychain Services, why does SecItemAdd return errSecDuplicateItem when an app saves a refreshed token, and how should the save be written?
basics
~20 sA 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.
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?
basics
~20 sStore 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.
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?
basics
~20 sThe 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.
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?
basics
~20 sGive 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.
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?
basics
~10 sAwait 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.
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?
basics
~10 sGive 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.
With a background URLSession, how does an iOS transit app download offline timetable packs overnight and handle being relaunched when they finish?
basics
~20 sCreate 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.
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?
basics
~20 sCancelling 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.
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?
basics
~20 sASWebAuthenticationSession 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.
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?
basics
~10 sCreate 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.
In ASWebAuthenticationSession, what does prefersEphemeralWebBrowserSession change, when must you set it, and what does it cost your users?
basics
~20 sSetting 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.
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?
basics
~10 sFrom 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.
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?
basics
~20 sPasskey 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.
In a native iOS app, how does a universal link differ from a custom URL scheme link in how iOS verifies, routes and delivers it?
basics
~20 sA universal link is an ordinary https URL that iOS opens in the app only after the domain's apple-app-site-association file confirms the app, falling back to the browser otherwise. A custom scheme is unverified, and any app can register it.
When an iOS app is already running, which UIKit scene delegate method and which SwiftUI modifier receive a universal link and a custom-scheme URL?
basics
~10 sIn UIKit, scene(:continue:) receives a universal link as an NSUserActivity of type NSUserActivityTypeBrowsingWeb, and scene(:openURLContexts:) receives custom-scheme URLs. In SwiftUI, onOpenURL(perform:) receives both as a URL.
In an apple-app-site-association file, how do the applinks components decide which URLs open the iOS app, including exclusions and match order?
basics
~20 sEach applinks details entry names apps by team-prefixed ID and lists components patterns over path, query and fragment. iOS walks the patterns in order and the first match wins; exclude: true keeps that URL on the website.
In a scene-based UIKit zoo app, animal links work while the app runs but land on the home screen after a cold launch; why, and how do you fix it?
basics
~10 sOn a cold launch, a scene-based app gets the link in scene(:willConnectTo:options:), inside connectionOptions.userActivities for a universal link or urlContexts for a scheme URL, not in scene(:continue:). Read both sets there.
A zoo app's shared links to animal pages open in Safari instead of the iOS app; what makes iOS skip the app, and how do you find the cause?
basics
~20 siOS skips the app when a tap isn't treated as a universal link (same-domain tap in Safari, the app opening its own link) or verification fails: missing entitlement host, a redirected, wrong or unmatched apple-app-site-association file, or an outdated device copy.
In iOS's Background Tasks framework, what is the difference between BGAppRefreshTaskRequest and BGProcessingTaskRequest, and when do you use each?
basics
~20 sBGAppRefreshTaskRequest 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.
With BGTaskScheduler, what must a podcast app register, declare in Info.plist and submit before its episode-list refresh can ever run?
basics
~20 sList 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.
In iOS's Background Tasks framework, what must a launch handler do with expirationHandler and setTaskCompleted(success:), and what breaks when either is missing?
basics
~20 sAssign 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.
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?
basics
~20 sUse 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.
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?
basics
~10 sCheck 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.
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?
basics
~10 sCall 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.
With UserNotifications, how do UNUserNotificationCenterDelegate's willPresent and didReceive callbacks handle a concert reminder in the foreground and its action buttons?
basics
~10 suserNotificationCenter(: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.
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?
basics
~10 sCall 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.
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?
basics
~20 sAdd 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.
An iOS concert app's silent push to refresh set times never reaches application(_:didReceiveRemoteNotification:fetchCompletionHandler:) on testers' iPhones; what do you check?
basics
~20 sCheck 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.
In Core Location, how does an iOS app ask for when-in-use location permission, and what must its Info.plist contain first?
basics
~10 sAdd 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(_:).
In Core Location, how does CLLocationUpdate.liveUpdates differ from CLLocationManager's delegate updates, and how does each trade accuracy against battery?
basics
~10 sliveUpdates(:), 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.
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?
basics
~10 sCheck 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.
In Core Location, when a walker grants only approximate location, how do you request temporary full accuracy, and why can that request fail?
basics
~10 sWhen 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.
With Core Location's CLMonitor, how do you detect a walk entering the park, and which limits and relaunch rules apply?
basics
~20 sOpen 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.
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?
basics
~20 sEvery 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.
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?
basics
~20 sAn 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.
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?
basics
~20 sChanging 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.
In Core Animation, why does a breathing countdown's CADisplayLink keep its view controller alive, and how do you set its frame rate on iOS 15 and later?
basics
~20 sA CADisplayLink on a run loop is retained by it and retains its target until invalidate(), so an invalidate() in the target's deinit never runs. Invalidate when the countdown stops or use a weak proxy; set preferredFrameRateRange, iOS 15 and later.
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?
basics
~20 sHit 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.
In UIKit, how do you draw a rounded rectangle in a custom view's draw(_:), and how do you make it redraw?
basics
~10 sSubclass 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.
With UIGraphicsImageRenderer, how do you stamp a captured signature onto a delivery receipt photo, and what does the format's scale decide?
basics
~20 sCreate 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.
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?
basics
~20 ssetNeedsDisplay() 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.
In Core Graphics, how do you fill a rounded route-summary header with a CGGradient, and why wrap the clip in saveGState() and restoreGState()?
basics
~20 sClip 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.
In UIKit's draw(_:), why does a CGImage drawn with CGContext's draw(_:in:) come out upside down, and how do you fix it?
basics
~20 sQuartz'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.
With AVKit, how do you play a remote lesson video in AVPlayerViewController, and which AVAudioSession category keeps its sound on in silent mode?
basics
~20 sCreate 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.
In AVFoundation, how do you configure an AVCaptureSession to film a dance routine with camera and microphone, and where should startRunning() be called?
basics
~10 sCheck 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.
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?
basics
~20 sAVPlayer 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.
With AVFAudio, how do you record a spoken count-in as a voice note with AVAudioRecorder, starting from the microphone permission request?
basics
~10 sRequest 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.
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?
basics
~20 sLoad 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.
With iOS unified logging, why should an app write diagnostics with Logger(subsystem:category:) instead of print, and what do subsystem and category add?
basics
~20 sLogger 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.
With iOS unified logging, which Logger levels stay in memory only and which persist to disk, and how do you choose a level?
basics
~20 sDebug 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.
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?
basics
~20 sInterpolated 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.
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?
basics
~10 sRun 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.
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?
basics
~20 sCreate 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.
In TestFlight, how do internal and external testers differ, and how does a new build reach each kind of tester?
basics
~20 sInternal 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.
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?
basics
~20 sInternal 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.
In TestFlight, what does a build's Missing Compliance status mean, and how do you stop later builds of the app hitting it?
basics
~20 sMissing 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.
In TestFlight, how does a public link enroll external testers, and what do its tester limit and criteria actually control?
basics
~20 sA public link is created on an external group and lets anyone holding it join; Filter by Criteria limits enrollment by device and OS, and Tester Limit caps how many can join through it, from 1 to 10,000.
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?
basics
~20 sA 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.
In XCTest, what makes a method in an XCTestCase subclass a test, and when do setUp() and tearDown() run around it?
basics
~20 sA 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.
In XCTest, how do you test a service-record client's async fetch method and its completion-handler fetch method?
basics
~20 sCall 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.
In XCTest, why does XCTAssertEqual fail on a computed Double such as an average fuel consumption, and how does accuracy fix it?
basics
~10 sDouble 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.
In XCTest, how do XCTUnwrap, XCTAssertThrowsError and XCTSkip behave inside a test method marked throws?
basics
~20 sXCTUnwrap 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.
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?
basics
~20 sThe 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.
In XCUITest, how do you find a button by its accessibility identifier, tap it, and type text into a search field?
basics
~20 sQuery 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.
In XCUITest, how do launchArguments and launchEnvironment put the app into a known state, and why can't the test set that state directly?
basics
~20 sThe 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.
In XCUITest, why use waitForExistence(timeout:) instead of sleep, and why can an element that exists still fail isHittable?
basics
~20 swaitForExistence(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.
In XCUITest, how do you capture a screenshot of a receipt screen and keep it in the test results even when the test passes?
basics
~10 sCall 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.
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?
basics
~20 stap() 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.
In Swift Testing, how do you declare a test with @Test, check a result with #expect, and add a display name and traits?
basics
~20 sMark 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:).
In Swift Testing, when should a test use #require instead of #expect, and how does #expect(throws:) check for a specific error?
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.
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?
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.
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?
basics
~20 sSwift 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.
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?
basics
~20 sUsually 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.