Unit 5: iPhone Project Templates - Subjective Questions
INT372 — Iphone Application Programming • Practice Questions with Detailed Answers
20 questions
Define a navigation controller in iPhone application programming. Explain its role in managing navigation between view controllers.
Navigation controller: A UINavigationController is a container view controller that manages a stack of view controllers.
- The first view controller in the stack is called the root view controller.
- New view controllers are added using the
pushViewControllermethod. - The current view controller can be removed using the
popViewControllermethod. - It automatically provides a navigation bar containing a title and navigation buttons.
- It maintains the user's navigation history and supports back navigation.
Navigation controllers are useful for applications that require hierarchical navigation, such as moving from a list screen to a detail screen.
Explain how to create and use a navigation controller in an iPhone application.
A navigation controller can be created in Interface Builder or programmatically.
Programmatic steps:
- Create the initial view controller.
- Initialize a
UINavigationControllerwith the initial view controller as its root. - Set the navigation controller as the application's root view controller.
- Use
pushViewControllerto display another screen. - Use
popViewControllerto return to the previous screen.
Example:
let detailController = DetailViewController()
navigationController?.pushViewController(detailController, animated: true)The navigation controller manages the view controller stack and automatically updates the navigation bar when screens are pushed or popped.
Explain the concept of Auto Layout in iOS and describe the purpose of constraints.
Auto Layout is a rule-based layout system used to position and size interface elements on different screen sizes and orientations.
Constraints define relationships between views. They may specify:
- Horizontal and vertical positions.
- Width and height.
- Margins and alignment.
- Relationships between neighboring views.
For example, a label may be constrained to remain centered horizontally and positioned a fixed distance below an image view. Auto Layout uses these relationships to calculate the final frames of views at runtime. It supports different iPhone sizes, multitasking layouts, Dynamic Type, and device rotation without requiring separate fixed layouts.
Describe the process of designing a responsive user interface using Auto Layout constraints.
A responsive interface can be designed with Auto Layout by following these steps:
- Add the required views to the view hierarchy.
- Define horizontal and vertical constraints for every view.
- Specify sufficient constraints for position and size.
- Use safe-area guides for content that should avoid the status bar, notch, or home indicator.
- Set content hugging and compression resistance priorities when views compete for space.
- Use stack views to simplify the layout of vertically or horizontally arranged controls.
- Test the layout on different screen sizes and orientations.
A view should have an unambiguous position and size. Missing or conflicting constraints can cause warnings and unexpected layouts.
Distinguish between frame-based layout and Auto Layout in iPhone applications.
Frame-based layout:
- Positions views using explicit coordinates and dimensions.
- Is simple for fixed layouts.
- Requires manual adjustment for different screen sizes and orientations.
- May produce overlapping or incorrectly sized views on other devices.
Auto Layout:
- Positions views using constraints and relationships.
- Adapts automatically to different screen sizes.
- Supports rotation, localization, Dynamic Type, and accessibility requirements.
- Can involve more initial configuration and may produce conflicts if constraints are incorrect.
Auto Layout is generally preferred for modern iPhone applications because it provides better adaptability and maintainability.
Explain how audio files can be played in an iPhone application using AVAudioPlayer.
AVAudioPlayer is used to play local audio files such as MP3, AAC, or WAV files.
General procedure:
- Import the
AVFoundationframework. - Obtain the URL of the audio file from the application bundle.
- Initialize an
AVAudioPlayerobject with the URL. - Prepare the player for playback.
- Call
play()to start playback. - Use
pause()orstop()to control playback.
Example:
import AVFoundation
var audioPlayer: AVAudioPlayer?
if let url = Bundle.main.url(forResource: "music", withExtension: "mp3") {
audioPlayer = try? AVAudioPlayer(contentsOf: url)
audioPlayer?.prepareToPlay()
audioPlayer?.play()
}The player should normally be retained as a property so that it remains available during playback.
Describe the important considerations when implementing audio playback in an iPhone application.
Important considerations for audio playback include:
- Configure the audio session with an appropriate category, such as playback or ambient.
- Handle interruptions caused by phone calls, alarms, or other applications.
- Check whether the audio file exists and handle loading errors.
- Retain the audio player for the duration of playback.
- Provide controls for play, pause, stop, and volume where required.
- Use the delegate to detect completion or playback errors.
- Consider background audio only when it is required and configure the application capabilities correctly.
- Release or replace the player when it is no longer needed.
Proper audio-session management improves reliability and prevents unexpected conflicts with other audio sources.
Explain how video files are played in an iPhone application using AVPlayerViewController.
AVPlayerViewController provides a ready-made interface for playing video content.
Procedure:
- Import
AVKitandAVFoundation. - Obtain the URL of a local or remote video file.
- Create an
AVPlayerusing the URL. - Create an
AVPlayerViewController. - Assign the player to the controller.
- Present the controller and start playback.
Example:
import AVKit
import AVFoundation
if let url = URL(string: "https://example.com/video.mp4") {
let player = AVPlayer(url: url)
let playerController = AVPlayerViewController()
playerController.player = player
present(playerController, animated: true) {
player.play()
}
}The controller supplies standard playback controls and adapts the video display to the available screen space.
Compare the use of AVAudioPlayer and AVPlayer in iPhone applications.
AVAudioPlayer and AVPlayer are both media playback classes, but they are intended for different requirements.
| Feature | AVAudioPlayer | AVPlayer |
|---|---|---|
| Main purpose | Local audio playback | Audio and video playback |
| Typical content | MP3, WAV, AAC files | Local or streamed media |
| Streaming support | Limited for basic use | Designed to support streaming |
| Video display | Not supported | Supported through AVPlayerViewController |
| Control | Simple playback controls | Supports time-based and advanced media control |
| Common use | Music effects and sound files | Movies, podcasts, and network media |
AVAudioPlayer is suitable for simple local audio, while AVPlayer is more appropriate for video and streaming media.
Define UICollectionView and explain its main components.
UICollectionView is a flexible view used to display a collection of items in customizable layouts such as grids, lists, and horizontally scrolling galleries.
Its main components are:
- Collection view: Displays the content.
- Cell: Represents an individual item.
- Data source: Supplies the number of sections, items, and cell content.
- Delegate: Handles selection, highlighting, scrolling, and interaction events.
- Layout object: Determines item size, spacing, insets, and arrangement.
- Supplementary views: Display section headers or footers.
The collection view reuses cells to reduce memory usage and improve scrolling performance.
Describe the steps required to implement a basic UICollectionView displaying a list of items.
The basic implementation involves the following steps:
- Add a
UICollectionViewto the view hierarchy. - Create or register a collection-view cell class.
- Set the view controller as the collection view's data source and delegate.
- Implement
numberOfItemsInSection. - Implement
cellForItemAt. - Configure each cell using the corresponding data item.
- Implement selection behavior if required.
Example:
func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return items.count
}
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: "Cell", for: indexPath)
cell.backgroundColor = .systemBlue
return cell
}Cell reuse is important because only the cells currently needed on screen are maintained efficiently.
Explain how UICollectionViewFlowLayout controls the appearance of a collection view.
UICollectionViewFlowLayout arranges collection-view items in a line-based flow. It can be configured using properties such as:
itemSize: Defines the width and height of each item.minimumLineSpacing: Sets spacing between rows or columns.minimumInteritemSpacing: Sets spacing between items in the same line.sectionInset: Adds padding around a section.scrollDirection: Specifies vertical or horizontal scrolling.- Header and footer reference sizes: Define supplementary-view dimensions.
The layout can be assigned during initialization or through the collection view's collectionViewLayout property. A custom layout can be created when the standard flow arrangement is insufficient.
What is UIToolbar? Explain how it is implemented and used in an iPhone application.
UIToolbar is a horizontal bar that contains toolbar items representing actions available in the current context.
Implementation steps:
- Create a toolbar in Interface Builder or programmatically.
- Create
UIBarButtonItemobjects for the required actions. - Assign target-action methods to actionable items.
- Arrange the items using the toolbar's
itemsproperty. - Use flexible-space items to distribute controls.
- Position the toolbar using Auto Layout or place it within a navigation interface.
Example:
let saveItem = UIBarButtonItem(
barButtonSystemItem: .save,
target: self,
action: #selector(saveData)
)
let flexibleSpace = UIBarButtonItem(
barButtonSystemItem: .flexibleSpace,
target: nil,
action: nil
)
toolbar.setItems([saveItem, flexibleSpace], animated: false)Toolbars are useful for frequent actions such as saving, editing, sharing, or filtering.
Explain the purpose of flexible spaces, fixed spaces, and custom items in a UIToolbar.
Toolbar items control both the actions and spacing of a toolbar.
- Flexible space: Expands to occupy available space and can push items toward opposite sides.
- Fixed space: Provides a specified amount of spacing between items.
- System item: Supplies a standard action and appearance, such as add, edit, save, or cancel.
- Custom item: Allows a custom view, such as a segmented control, search field, or progress indicator.
- Title item: Displays text when a textual command or status is required.
Using these item types makes toolbar layouts predictable and allows controls to adapt to different screen widths.
Define UITabBar and explain the role of a tab bar controller in an iPhone application.
UITabBar is a control that displays a row of tab-bar items, while UITabBarController manages multiple view controllers organized as separate tabs.
- Each tab represents a major section of the application.
- A tab-bar item usually contains an icon and a title.
- Selecting a tab displays its associated view controller.
- The tab bar remains available while switching between sections.
- Each tab can maintain its own navigation controller and navigation history.
Tab-based navigation is appropriate when the application has several top-level destinations, such as Home, Search, Favorites, and Settings.
Describe how to implement a tab-based application using UITabBarController.
A tab-based application can be implemented as follows:
- Create a view controller for each major application section.
- Assign a title and
UITabBarItemto each view controller. - Create a
UITabBarController. - Assign the view controllers to its
viewControllersproperty. - Set the tab-bar controller as the root or present it from another controller.
- Use delegate methods when selection behavior must be customized.
A tab may contain a navigation controller instead of a plain view controller. This allows users to navigate within a tab while preserving the selected tab and its navigation stack.
Compare navigation-controller-based applications with tab-bar-controller-based applications.
Navigation-controller-based application:
- Represents a hierarchical flow of screens.
- Uses push and pop operations.
- Provides a back button and navigation history.
- Is suitable for list-detail workflows.
Tab-bar-controller-based application:
- Represents independent top-level sections.
- Allows direct switching between sections.
- Usually keeps each section readily accessible.
- Is suitable for applications with several major features.
The two controllers can be combined. For example, each tab of a tab-bar controller may contain its own navigation controller. The choice depends on whether the application structure is primarily hierarchical, section-based, or a combination of both.
Explain SQLite and discuss why it is useful for data storage in iPhone applications.
SQLite is a lightweight, file-based relational database engine. It stores structured data in tables made up of rows and columns.
It is useful in iPhone applications because:
- It is embedded and does not require a separate database server.
- It stores data persistently between application launches.
- It supports SQL operations such as
SELECT,INSERT,UPDATE, andDELETE. - It is efficient for structured local data.
- It supports transactions and indexes.
- Its database is stored as a portable file in the application sandbox.
SQLite is suitable for offline data, cached server data, preferences requiring relational structure, and applications with moderate local data requirements.
Describe the steps for creating and opening an SQLite database in an iPhone application.
The general procedure for using SQLite is:
- Determine a writable path in the application's documents or application-support directory.
- Open the database using the SQLite API.
- Create required tables with
CREATE TABLEstatements. - Check and handle the return status of every database operation.
- Prepare SQL statements before execution.
- Bind values to parameters where required.
- Execute the statement and read returned rows.
- Finalize statements and close the database when appropriate.
A database should be created or opened during application initialization. Errors must be handled because database creation, file access, SQL syntax, and schema changes can all fail.
Explain the CRUD operations in SQLite and provide suitable SQL examples for an iPhone application.
CRUD represents the four basic database operations.
-
Create: Adds a new record.
sql
INSERT INTO Students (name, grade) VALUES (?, ?); -
Read: Retrieves records.
sql
SELECT id, name, grade FROM Students; -
Update: Changes an existing record.
sql
UPDATE Students SET grade = ? WHERE id = ?; -
Delete: Removes a record.
sql
DELETE FROM Students WHERE id = ?;
In iPhone applications, values should be bound to placeholders rather than concatenated into SQL strings. Parameter binding improves security, handles special characters correctly, and reduces the risk of SQL injection.
Define a navigation controller in iPhone application programming. Explain its role in managing navigation between view controllers.
Navigation controller: A UINavigationController is a container view controller that manages a stack of view controllers.
- The first view controller in the stack is called the root view controller.
- New view controllers are added using the
pushViewControllermethod. - The current view controller can be removed using the
popViewControllermethod. - It automatically provides a navigation bar containing a title and navigation buttons.
- It maintains the user's navigation history and supports back navigation.
Navigation controllers are useful for applications that require hierarchical navigation, such as moving from a list screen to a detail screen.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →