Unit 6: Web Services - Subjective Questions
INT372 — Iphone Application Programming • Practice Questions with Detailed Answers
20 questions
Define the MapKit framework. Explain its main features and role in an iPhone application.
MapKit is an Apple framework used to embed interactive maps and location-related features in iOS applications. It is imported using import MapKit.
Main features of MapKit:
- Displays standard, satellite, hybrid, and other supported map styles.
- Shows the user's current location after receiving permission.
- Supports zooming, scrolling, rotation, and pitch gestures.
- Displays points of interest using annotations and custom markers.
- Draws overlays such as circles, polygons, and routes.
- Monitors changes in the visible map region through
MKMapViewDelegate. - Supports local search, geocoding, directions, and route visualization.
The principal class is MKMapView. It can be created through Interface Builder or programmatically and added to a view controller's view hierarchy.
Describe how to display a map in an iOS application using MKMapView.
A map can be displayed by importing MapKit, creating an MKMapView, configuring it, and adding it to the view hierarchy.
import UIKit
import MapKit
class MapViewController: UIViewController {
private let mapView = MKMapView()
override func viewDidLoad() {
super.viewDidLoad()
mapView.frame = view.bounds
mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
mapView.mapType = .standard
view.addSubview(mapView)
}
}Important steps:
- Add
import MapKit. - Create an
MKMapViewobject. - Set its frame or Auto Layout constraints.
- Select an appropriate
mapType. - Add the map view to the view controller's view.
- Optionally assign an
MKMapViewDelegateto monitor events and customize map content.
When using a storyboard, an Map Kit View may instead be dragged onto the scene and connected through an IBOutlet.
Explain map regions, coordinates, and spans in MapKit. How can an application display a particular geographical area?
MapKit represents a geographical position using CLLocationCoordinate2D, which contains latitude and longitude values.
An MKCoordinateRegion consists of:
- Center: The geographical coordinate at the center of the map.
- Span: The latitude and longitude range visible around the center.
A smaller span produces a more zoomed-in view, while a larger span displays a wider area.
let coordinate = CLLocationCoordinate2D(
latitude: 28.6139,
longitude: 77.2090
)
let span = MKCoordinateSpan(
latitudeDelta: 0.05,
longitudeDelta: 0.05
)
let region = MKCoordinateRegion(
center: coordinate,
span: span
)
mapView.setRegion(region, animated: true)The application may also use setCenter(_:animated:) to change only the center. Region values should be chosen carefully because extremely small or large spans may create an unsuitable display scale.
Distinguish between the major map display types supported by MKMapView.
MKMapView supports multiple map display types through its mapType property.
- Standard (
.standard): Displays roads, place names, boundaries, and common points of interest. It is suitable for navigation and general location applications. - Satellite (
.satellite): Displays satellite or aerial imagery. It is useful for viewing terrain, buildings, and real-world surface details. - Hybrid (
.hybrid): Combines satellite imagery with road labels, place names, and other map information. - Satellite Flyover (
.satelliteFlyover): Provides satellite imagery with supported three-dimensional flyover presentation. - Hybrid Flyover (
.hybridFlyover): Combines flyover imagery with labels and map information. - Muted Standard (
.mutedStandard): Uses a less visually prominent standard style, making annotations and overlays easier to emphasize.
Example:
mapView.mapType = .hybridThe appropriate type depends on the purpose of the application. For example, a delivery application commonly uses .standard, while a terrain inspection application may prefer .satellite or .hybrid.
Explain how an iOS application displays and tracks the user's current location on a map.
Displaying the user's location requires both permission handling and MapKit configuration.
Procedure:
- Import
CoreLocationandMapKit. - Add an appropriate location usage description, such as
NSLocationWhenInUseUsageDescription, to the application's information property list. - Create a
CLLocationManager. - Request location authorization.
- Set
showsUserLocationtotrueon the map view. - Optionally update the visible region when a user location is received.
import MapKit
import CoreLocation
let locationManager = CLLocationManager()
func configureLocation() {
locationManager.requestWhenInUseAuthorization()
mapView.showsUserLocation = true
mapView.userTrackingMode = .follow
}Tracking modes include:
.none: Does not automatically follow the user..follow: Keeps the user's location visible..followWithHeading: Follows the location and rotates according to heading.
The application should check the authorization status and provide meaningful behavior when permission is denied or restricted. Location services should be used only when necessary because continuous tracking can consume battery power.
What are annotations in MapKit? Describe how to add and customize an annotation.
An annotation represents a point of interest at a geographical coordinate. It generally has a coordinate and may include a title and subtitle.
A simple annotation can be added using MKPointAnnotation:
let annotation = MKPointAnnotation()
annotation.coordinate = CLLocationCoordinate2D(
latitude: 19.0760,
longitude: 72.8777
)
annotation.title = "Mumbai"
annotation.subtitle = "Point of interest"
mapView.addAnnotation(annotation)Annotations can be customized through mapView(_:viewFor:) of MKMapViewDelegate:
func mapView(
_ mapView: MKMapView,
viewFor annotation: MKAnnotation
) -> MKAnnotationView? {
guard !(annotation is MKUserLocation) else { return nil }
let identifier = "PlaceMarker"
let view = mapView.dequeueReusableAnnotationView(
withIdentifier: identifier
) as? MKMarkerAnnotationView
?? MKMarkerAnnotationView(
annotation: annotation,
reuseIdentifier: identifier
)
view.annotation = annotation
view.canShowCallout = true
view.markerTintColor = .systemRed
view.glyphImage = UIImage(systemName: "mappin")
return view
}Reusing annotation views improves performance. The user-location annotation should normally be excluded so that MapKit can render it using its default appearance.
Explain the purpose of MKMapViewDelegate. Describe the delegate methods used to monitor changes in the visible map region.
MKMapViewDelegate allows an object, usually a view controller, to respond to map events and customize annotations and overlays.
The delegate is assigned as follows:
mapView.delegate = selfImportant methods for monitoring region changes include:
mapView(_:regionWillChangeAnimated:): Called before the visible region starts changing.mapViewDidChangeVisibleRegion(_:): Called repeatedly while the visible region is changing.mapView(_:regionDidChangeAnimated:): Called after the region change finishes.
func mapView(
_ mapView: MKMapView,
regionWillChangeAnimated animated: Bool
) {
print("Region change started")
}
func mapViewDidChangeVisibleRegion(_ mapView: MKMapView) {
let center = mapView.centerCoordinate
print("Current center: \(center.latitude), \(center.longitude)")
}
func mapView(
_ mapView: MKMapView,
regionDidChangeAnimated animated: Bool
) {
print("Region change completed")
}These methods can be used to update labels, save the current region, or request data for newly visible locations. Expensive network requests should generally be performed after the change completes or after applying a debounce mechanism.
Describe how MapKit can determine whether a map region change was caused by a user gesture or by application code.
MapKit's basic region-change delegate methods indicate whether a change is animated, but they do not directly state whether the change was initiated by the user. An application can inspect the gesture recognizers attached to MKMapView.
func mapView(
_ mapView: MKMapView,
regionWillChangeAnimated animated: Bool
) {
let causedByGesture = mapView.subviews
.flatMap { $0.gestureRecognizers ?? [] }
.contains {
$0.state == .began || $0.state == .changed
}
if causedByGesture {
print("The user moved or zoomed the map")
} else {
print("The region may have changed programmatically")
}
}Another common design is to maintain a Boolean flag before calling setRegion, setCenter, or camera-related methods programmatically.
Uses of this distinction include:
- Enabling a "Search this area" button after user movement.
- Preventing automatic recentering from interfering with manual exploration.
- Avoiding unnecessary web-service calls during application-controlled updates.
- Recording user interaction for interface behavior.
The result should be treated carefully because complex gestures and internal MapKit behavior may produce multiple callbacks.
What are overlays in MapKit? Compare annotations and overlays, and explain how a circular overlay is displayed.
Annotations identify individual points, whereas overlays represent shapes or areas covering part of a map.
Comparison:
- An annotation is associated mainly with one coordinate.
- An overlay may cover a line, route, polygon, or circular area.
- Annotation appearance is provided by
MKAnnotationView. - Overlay appearance is provided by an
MKOverlayRenderer.
Common overlays include MKCircle, MKPolyline, and MKPolygon.
let center = CLLocationCoordinate2D(
latitude: 12.9716,
longitude: 77.5946
)
let circle = MKCircle(center: center, radius: 1000)
mapView.addOverlay(circle)The delegate supplies a renderer:
func mapView(
_ mapView: MKMapView,
rendererFor overlay: MKOverlay
) -> MKOverlayRenderer {
if let circle = overlay as? MKCircle {
let renderer = MKCircleRenderer(circle: circle)
renderer.fillColor = UIColor.systemBlue.withAlphaComponent(0.2)
renderer.strokeColor = .systemBlue
renderer.lineWidth = 2
return renderer
}
return MKOverlayRenderer(overlay: overlay)
}This technique can display delivery zones, geofenced areas, service coverage, or regions returned by a web service.
Describe how to obtain directions and display a route between two locations using MapKit.
Routes are obtained using MKDirections. The application creates source and destination map items, configures a request, calculates directions, and displays the resulting polyline.
let sourcePlacemark = MKPlacemark(coordinate: sourceCoordinate)
let destinationPlacemark = MKPlacemark(coordinate: destinationCoordinate)
let request = MKDirections.Request()
request.source = MKMapItem(placemark: sourcePlacemark)
request.destination = MKMapItem(placemark: destinationPlacemark)
request.transportType = .automobile
request.requestsAlternateRoutes = false
let directions = MKDirections(request: request)
directions.calculate { [weak self] response, error in
guard let self,
error == nil,
let route = response?.routes.first else {
return
}
self.mapView.addOverlay(route.polyline)
self.mapView.setVisibleMapRect(
route.polyline.boundingMapRect,
edgePadding: UIEdgeInsets(top: 60, left: 30, bottom: 60, right: 30),
animated: true
)
}The route polyline must be rendered using MKPolylineRenderer:
if let polyline = overlay as? MKPolyline {
let renderer = MKPolylineRenderer(polyline: polyline)
renderer.strokeColor = .systemBlue
renderer.lineWidth = 5
return renderer
}The application should handle unavailable routes and errors, cancel outdated direction requests, and avoid repeatedly requesting routes during continuous map movement.
Explain geocoding and reverse geocoding in the context of displaying map information.
Geocoding converts a textual address into geographical coordinates. Reverse geocoding converts coordinates into a human-readable place or address.
Both operations can be performed using CLGeocoder.
Geocoding example:
let geocoder = CLGeocoder()
geocoder.geocodeAddressString("Chennai, India") { placemarks, error in
guard let coordinate = placemarks?.first?.location?.coordinate,
error == nil else {
return
}
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
annotation.title = "Chennai"
self.mapView.addAnnotation(annotation)
}Reverse geocoding example:
let location = CLLocation(latitude: 13.0827, longitude: 80.2707)
geocoder.reverseGeocodeLocation(location) { placemarks, error in
guard let place = placemarks?.first, error == nil else { return }
print(place.locality ?? "Unknown place")
}Geocoding is useful for address search, while reverse geocoding is useful when a user taps or moves a map pin. Requests should not be made continuously because geocoding services may limit excessive usage.
Define WKWebView and explain why it is preferred for displaying web content in modern iOS applications.
WKWebView is a class in the WebKit framework used to display and interact with web content inside an iOS application. It uses Apple's modern web-rendering engine.
It is imported using:
import WebKitReasons for using WKWebView:
- Provides fast and efficient web-page rendering.
- Runs web content in a separate process, improving application stability.
- Supports JavaScript execution.
- Provides navigation and user-interface delegate protocols.
- Supports communication between JavaScript and native Swift code.
- Allows configuration of website data, preferences, and content rules.
- Can load remote URLs, local HTML files, and HTML strings.
- Replaced older approaches such as the deprecated
UIWebView.
Although WKWebView can display web applications, developers should prefer native controls for primary application navigation when appropriate. Untrusted content must also be handled securely.
Describe how to create a WKWebView programmatically and load a remote web page.
A WKWebView can be created with a frame and a WKWebViewConfiguration, added to a view, and supplied with a URLRequest.
import UIKit
import WebKit
class WebViewController: UIViewController {
private var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
let configuration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: configuration)
webView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(webView)
NSLayoutConstraint.activate([
webView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
webView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
webView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
webView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
if let url = URL(string: "https://www.example.com") {
webView.load(URLRequest(url: url))
}
}
}Key points:
- Use secure
httpsURLs whenever possible. - Validate the URL before loading it.
- Use Auto Layout to support different screen sizes.
- Assign a navigation delegate to monitor loading and handle errors.
- App Transport Security may block insecure
httpresources unless a justified exception is configured.
Explain the different ways in which content can be loaded into a WKWebView.
WKWebView can load content from several sources.
1. Remote URL using URLRequest:
let url = URL(string: "https://www.example.com")!
webView.load(URLRequest(url: url))2. HTML string:
let html = "<html><body><h1>Welcome</h1></body></html>"
webView.loadHTMLString(html, baseURL: nil)A base URL may be supplied when the HTML references relative images, scripts, or style sheets.
3. Local file:
if let fileURL = Bundle.main.url(
forResource: "help",
withExtension: "html"
) {
webView.loadFileURL(
fileURL,
allowingReadAccessTo: fileURL.deletingLastPathComponent()
)
}4. Raw data:
The load(_:mimeType:characterEncodingName:baseURL:) method can display data with a specified MIME type and character encoding.
The method chosen depends on whether content comes from a web server, the application bundle, a generated HTML string, or downloaded data.
What is WKNavigationDelegate? Explain how it is used to monitor web-page loading and handle navigation failures.
WKNavigationDelegate allows an application to observe and control navigation in a WKWebView.
The delegate is assigned as follows:
webView.navigationDelegate = selfCommon callbacks include:
webView(_:didStartProvisionalNavigation:): Loading has started.webView(_:didCommit:): The web view has begun receiving content.webView(_:didFinish:): The page has loaded successfully.webView(_:didFail:withError:): A committed navigation failed.webView(_:didFailProvisionalNavigation:withError:): Navigation failed before content was committed.
func webView(
_ webView: WKWebView,
didStartProvisionalNavigation navigation: WKNavigation!
) {
activityIndicator.startAnimating()
}
func webView(
_ webView: WKWebView,
didFinish navigation: WKNavigation!
) {
activityIndicator.stopAnimating()
title = webView.title
}
func webView(
_ webView: WKWebView,
didFailProvisionalNavigation navigation: WKNavigation!,
withError error: Error
) {
activityIndicator.stopAnimating()
print(error.localizedDescription)
}These methods support loading indicators, error messages, navigation controls, analytics, and state updates.
Describe how navigation requests can be accepted, cancelled, or redirected using WKNavigationDelegate.
Before loading a resource, WKWebView asks its navigation delegate to decide whether the navigation should proceed. The application responds with a WKNavigationActionPolicy.
func webView(
_ webView: WKWebView,
decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void
) {
guard let url = navigationAction.request.url else {
decisionHandler(.cancel)
return
}
if url.scheme == "https" && url.host == "www.example.com" {
decisionHandler(.allow)
} else {
decisionHandler(.cancel)
}
}Possible policies:
.allow: Continues the navigation..cancel: Stops the navigation..download: Treats supported navigation as a download on compatible system versions and configurations.
An application may inspect the URL scheme, host, navigation type, or target frame. External links can be cancelled in the web view and opened with the system after validation. The decisionHandler must be called exactly once for every request; otherwise, navigation may remain blocked or the application may fail.
Explain how Swift code can execute JavaScript in a WKWebView and receive the result.
Swift can execute JavaScript using evaluateJavaScript(_:completionHandler:). The script runs in the context of the currently loaded page.
let script = "document.title"
webView.evaluateJavaScript(script) { result, error in
if let error {
print("JavaScript error: \(error.localizedDescription)")
return
}
if let title = result as? String {
print("Page title: \(title)")
}
}JavaScript may also change page content:
webView.evaluateJavaScript(
"document.body.style.backgroundColor = 'lightblue';"
)Important considerations:
- Execute scripts after the relevant document has loaded.
- Handle both optional results and errors.
- Avoid constructing scripts directly from untrusted input because it can introduce injection vulnerabilities.
- Returned JavaScript values are converted into compatible Foundation types where possible.
- For structured communication, message handlers or modern asynchronous JavaScript APIs are often better than manually concatenating script strings.
Explain two-way communication between JavaScript and native Swift code using WKScriptMessageHandler.
WKScriptMessageHandler allows JavaScript running in a web page to send a message to native Swift code.
Native configuration:
class WebViewController: UIViewController, WKScriptMessageHandler {
var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
let controller = WKUserContentController()
controller.add(self, name: "nativeHandler")
let configuration = WKWebViewConfiguration()
configuration.userContentController = controller
webView = WKWebView(frame: view.bounds, configuration: configuration)
view.addSubview(webView)
}
func userContentController(
_ userContentController: WKUserContentController,
didReceive message: WKScriptMessage
) {
if message.name == "nativeHandler" {
print("Received: \(message.body)")
}
}
deinit {
webView?.configuration.userContentController
.removeScriptMessageHandler(forName: "nativeHandler")
}
}JavaScript call:
window.webkit.messageHandlers.nativeHandler.postMessage({
action: "showLocation",
latitude: 28.6139,
longitude: 77.2090
});Security and memory considerations:
- Validate the message name, type, and values.
- Never treat messages from untrusted pages as automatically safe.
- Restrict the domains that the web view can load.
- Remove handlers when they are no longer required.
- Avoid strong reference cycles, since the content controller may retain the message handler.
Discuss security, privacy, and performance considerations when using WKWebView in an iPhone application.
A WKWebView displays active web content, so it must be configured carefully.
Security considerations:
- Prefer
httpsand avoid unnecessary App Transport Security exceptions. - Validate URLs, schemes, hosts, redirects, and downloaded files.
- Do not load arbitrary untrusted HTML with privileged JavaScript interfaces.
- Validate every message received through
WKScriptMessageHandler. - Avoid inserting untrusted values directly into JavaScript strings.
- Disable or avoid unnecessary browser capabilities.
- Do not assume that content displayed in the web view is trustworthy.
Privacy considerations:
- Avoid collecting cookies or browsing data unnecessarily.
- Use
WKWebsiteDataStore.nonPersistent()when an ephemeral session is appropriate. - Clearly request permission before accessing location, camera, or other private resources.
- Remove stored website data when required by the application's privacy policy.
Performance considerations:
- Reuse a web view when appropriate instead of repeatedly creating one.
- Avoid loading unnecessarily large pages or scripts.
- Show a progress indicator using
estimatedProgress. - Stop loading and release delegates or message handlers when the web view is no longer needed.
- Handle process termination using appropriate delegate callbacks and reload only when necessary.
These practices reduce security risks, protect user information, and improve responsiveness.
Design an iPhone application that combines WKWebView and MapKit so that selecting a location in web content displays it on a native map. Explain the data flow and implementation.
The application can display a list or web-based search interface in WKWebView and a native MKMapView for geographical presentation.
Data flow:
- A web page displays a list of places.
- The user selects a place.
- JavaScript sends the place's latitude, longitude, and title through a script message handler.
- Swift validates the message.
- Swift creates an annotation and updates the map region.
MKMapViewDelegatemonitors subsequent map changes.
JavaScript message:
window.webkit.messageHandlers.locationHandler.postMessage({
title: "Selected Place",
latitude: 12.9716,
longitude: 77.5946
});Swift-side handling:
func userContentController(
_ userContentController: WKUserContentController,
didReceive message: WKScriptMessage
) {
guard message.name == "locationHandler",
let data = message.body as? [String: Any],
let latitude = data["latitude"] as? Double,
let longitude = data["longitude"] as? Double,
let title = data["title"] as? String,
(-90...90).contains(latitude),
(-180...180).contains(longitude) else {
return
}
let coordinate = CLLocationCoordinate2D(
latitude: latitude,
longitude: longitude
)
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
annotation.title = title
mapView.removeAnnotations(
mapView.annotations.filter { !($0 is MKUserLocation) }
)
mapView.addAnnotation(annotation)
let region = MKCoordinateRegion(
center: coordinate,
latitudinalMeters: 2000,
longitudinalMeters: 2000
)
mapView.setRegion(region, animated: true)
}Design considerations:
- Only trusted web domains should be allowed to send native commands.
- Coordinates must be range-checked before use.
- Script handlers should be removed when no longer needed.
- Map updates should occur on the main thread.
- Region-change callbacks can be used to request or display information about newly visible places.
This architecture combines the flexibility of web content with the performance and interaction quality of a native map.
Define the MapKit framework. Explain its main features and role in an iPhone application.
MapKit is an Apple framework used to embed interactive maps and location-related features in iOS applications. It is imported using import MapKit.
Main features of MapKit:
- Displays standard, satellite, hybrid, and other supported map styles.
- Shows the user's current location after receiving permission.
- Supports zooming, scrolling, rotation, and pitch gestures.
- Displays points of interest using annotations and custom markers.
- Draws overlays such as circles, polygons, and routes.
- Monitors changes in the visible map region through
MKMapViewDelegate. - Supports local search, geocoding, directions, and route visualization.
The principal class is MKMapView. It can be created through Interface Builder or programmatically and added to a view controller's view hierarchy.
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 →