Unit 6: Web Services
I. Orientation — Web-Enabled iPhone Applications
Web services enable an iPhone application to retrieve, display, and interact with remotely supplied or location-based information. In this unit, MapKit presents geographic data through Apple Maps, while WKWebView embeds standards-based web content inside an application.
- Governing principle: Network and map operations are asynchronous because data, tiles, and resources may arrive after the user interface has appeared.
- Framework separation:
MapKitsupplies maps, annotations, overlays, geocoding-related types, and map interaction.CoreLocationobtains device location and authorization status.WebKitsuppliesWKWebViewand related navigation, configuration, and scripting APIs.
- User-interface rule: Changes to
MKMapView,WKWebView, labels, buttons, and other UIKit components must occur on the main thread. - Privacy rule: Location access requires a clear purpose string in
Info.plistand explicit user authorization. - Security rule: App Transport Security, or ATS, normally requires secure
HTTPSconnections. - Lifecycle rule: Delegates, observers, and loading operations should be attached and removed deliberately to prevent stale callbacks or memory problems.
- Failure handling: Applications must anticipate denied permission, unavailable location, invalid URLs, no network connection, server errors, and failed navigation.
- Performance convention: Map annotations, overlays, scripts, and web resources should be limited to what the visible interface actually needs.
II. MapKit Framework — Geographic Content and Map Interaction
MapKit is Apple’s framework for embedding interactive maps in an application. Its central UIKit component is MKMapView, which displays map tiles and geographic objects while reporting map and user interactions through MKMapViewDelegate.
A. Displaying maps and monitoring changes using MapKit Framework
Displaying and monitoring a map requires configuring an MKMapView, representing positions with coordinates, and responding to delegate callbacks when the visible region or user location changes.
- Framework import: A source file imports MapKit before using
MKMapView,MKCoordinateRegion,MKPointAnnotation, or related types.
import MapKit
import CoreLocation- Map view creation:
MKMapViewmay be added in Interface Builder or created programmatically; Auto Layout constraints normally attach it to the containing view.
let mapView = MKMapView(frame: .zero)
mapView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(mapView)
NSLayoutConstraint.activate([
mapView.topAnchor.constraint(equalTo: view.topAnchor),
mapView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
mapView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
mapView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
])- Map types: The
mapTypeproperty changes the visual presentation..standard: Road-oriented map with labels and points of interest..satellite: Satellite imagery..hybrid: Satellite imagery combined with roads and labels.
mapView.mapType = .standard- Coordinate representation:
CLLocationCoordinate2Dstores latitude and longitude in decimal degrees.latitude: Angular distance north or south of the equator, from-90to90.longitude: Angular distance east or west of the prime meridian, commonly from-180to180.
let coordinate = CLLocationCoordinate2D(
latitude: 13.0827,
longitude: 80.2707
)- Visible region:
MKCoordinateRegioncombines a center coordinate with a span.latitudeDelta: North–south extent in degrees.longitudeDelta: East–west extent in degrees.- Smaller deltas produce a closer zoom.
let span = MKCoordinateSpan(
latitudeDelta: 0.05,
longitudeDelta: 0.05
)
let region = MKCoordinateRegion(center: coordinate, span: span)
mapView.setRegion(region, animated: true)- Annotation model: An annotation marks a point and normally provides a coordinate, title, and subtitle.
MKPointAnnotationis suitable for simple markers.
let marker = MKPointAnnotation()
marker.coordinate = coordinate
marker.title = "Chennai"
marker.subtitle = "Tamil Nadu"
mapView.addAnnotation(marker)- Annotation presentation:
mapView(_:viewFor:)returns a reusable annotation view.MKMarkerAnnotationViewprovides a standard marker and callout.
func mapView(
_ mapView: MKMapView,
viewFor annotation: MKAnnotation
) -> MKAnnotationView? {
guard !(annotation is MKUserLocation) else { return nil }
let id = "PlaceMarker"
let view = mapView.dequeueReusableAnnotationView(
withIdentifier: id
) as? MKMarkerAnnotationView
?? MKMarkerAnnotationView(annotation: annotation,
reuseIdentifier: id)
view.annotation = annotation
view.canShowCallout = true
return view
}- Monitoring region changes: The map view delegate reports movement caused by gestures, zooming, or calls such as
setRegion.mapView(_:regionWillChangeAnimated:): Called before the visible region changes.mapViewDidChangeVisibleRegion(_:): Called repeatedly during movement and should contain only lightweight work.mapView(_:regionDidChangeAnimated:): Called after the region settles and is appropriate for updating data.
mapView.delegate = self
func mapView(
_ mapView: MKMapView,
regionDidChangeAnimated animated: Bool
) {
let center = mapView.centerCoordinate
print("Center: \(center.latitude), \(center.longitude)")
}- Visible-area measurement:
mapView.regionexpresses the visible coordinate region, whilemapView.visibleMapRectexpresses it as anMKMapRect. These values can determine which server-provided places should be requested. - Avoiding excessive requests:
mapViewDidChangeVisibleRegion(_:)may fire many times during one drag; remote searches should therefore be delayed, cancelled, or initiated only inregionDidChangeAnimated. - User-location display: Setting
showsUserLocationasks the map to display the location supplied by Core Location, but it does not itself replace permission management.
mapView.showsUserLocation = true- Authorization requirement: For foreground access,
Info.plistneedsNSLocationWhenInUseUsageDescription. The text must explain why location is required, such as locating the user on a delivery map. - Location manager:
CLLocationManagerrequests authorization and reports location-related state.
let locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()- Authorization monitoring:
locationManagerDidChangeAuthorization(_:)detects whether access became authorized, denied, restricted, or remained undetermined.
func locationManagerDidChangeAuthorization(
_ manager: CLLocationManager
) {
switch manager.authorizationStatus {
case .authorizedAlways, .authorizedWhenInUse:
mapView.showsUserLocation = true
case .denied, .restricted:
mapView.showsUserLocation = false
default:
break
}
}- User-location updates:
mapView(_:didUpdate:)receives an updatedMKUserLocation; the containedlocationmay initially benilwhile a fix is being obtained. - Overlays: An overlay represents an area or path rather than one point.
MKPolyline: A route or line.MKPolygon: A bounded area.MKCircle: A circular geographic region.mapView(_:rendererFor:): Supplies anMKOverlayRenderersuch asMKPolylineRenderer.
- Camera control:
MKMapCameracontrols center, altitude, pitch, and heading, supporting three-dimensional or direction-oriented map presentations.
B. Applications and Limitations
MapKit is most effective when geographic visualization is combined with careful permission handling, selective data loading, and realistic expectations about location accuracy.
- Typical applications: Store locators, ride tracking, delivery status, tourism guides, nearby-service searches, route displays, and geofenced interfaces use coordinates as a primary data key.
- Remote-service integration: The visible region’s center and span can be converted into query parameters for requesting only nearby records from a server.
- Location accuracy: GPS and network-derived coordinates may drift, especially indoors;
CLLocation.horizontalAccuracyexpresses estimated uncertainty in metres. - Battery impact: Continuous high-accuracy location updates consume power, so applications should stop updates when tracking is unnecessary.
- Permission denial: The application must remain useful without location access, for example by allowing manual place search.
- Map availability: Map tiles and search results may depend on network access; loading states and errors should not block the whole interface.
- Data density: Hundreds of overlapping markers reduce readability and performance; clustering can be enabled with an annotation view’s
clusteringIdentifier. - Delegate safety: Programmatic region changes also trigger delegate methods, so code must avoid feedback loops in which one callback repeatedly resets the map.
III. WKWebView — Embedded Web Content
WKWebView, provided by WebKit, is the standard component for displaying web pages in an iOS application. It uses a multiprocess web architecture and replaces the obsolete UIWebView.
A. WKWebView
WKWebView loads web resources, manages navigation history, executes JavaScript, and communicates loading state through properties and delegates.
- Creation and configuration: A
WKWebViewConfigurationis supplied at initialization; major configuration should be completed before creating the web view.
import WebKit
let configuration = WKWebViewConfiguration()
let webView = WKWebView(frame: .zero,
configuration: configuration)
webView.navigationDelegate = self- Remote URL loading: A valid
URLis wrapped inURLRequestand passed toload(_:).
if let url = URL(string: "https://www.apple.com") {
let request = URLRequest(url: url)
webView.load(request)
}- Local content loading:
loadHTMLString(_:baseURL:)displays an HTML string. ThebaseURLdetermines how relative stylesheet, script, and image paths are resolved.
let html = "<html><body><h1>Web Services</h1></body></html>"
webView.loadHTMLString(html, baseURL: nil)- Navigation controls: The web view maintains a back-forward list.
goBack()andgoForward(): Traverse page history.reload(): Requests the current page again.stopLoading(): Cancels the active navigation.canGoBackandcanGoForward: Indicate whether navigation buttons should be enabled.
- Navigation lifecycle:
WKNavigationDelegatereports important stages.didStartProvisionalNavigation: Loading has begun.didCommit: Initial content has arrived.didFinish: Navigation completed.didFailProvisionalNavigationordidFail: Loading failed.
func webView(
_ webView: WKWebView,
didFinish navigation: WKNavigation!
) {
print("Loaded: \(webView.url?.absoluteString ?? "unknown")")
}- Navigation policy:
decidePolicyForcan permit or cancel a request. The decision handler must be called exactly once.
func webView(
_ webView: WKWebView,
decidePolicyFor action: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void
) {
guard let scheme = action.request.url?.scheme,
scheme == "https" else {
decisionHandler(.cancel)
return
}
decisionHandler(.allow)
}- Progress monitoring:
estimatedProgressranges from0.0to1.0and can drive a progress indicator. It is Key-Value Observable and should be observed and cleaned up safely. - JavaScript execution:
evaluateJavaScript(_:completionHandler:)runs script in the current page and asynchronously returns a value or error.
webView.evaluateJavaScript("document.title") { result, error in
if let title = result as? String {
print(title)
}
}- JavaScript messages:
WKUserContentControllerenables page scripts to send structured messages to native code through registered message handlers. - Website data: Cookies, caches, and other records are managed through
WKWebsiteDataStore; persistent and nonpersistent stores support different privacy requirements. - New windows: Pages using
target="_blank"may require aWKUIDelegateimplementation because they request another web view. - Layout: Like a map view, a web view should use Auto Layout and respect safe areas when navigation bars or toolbars are present.
B. Applications and Limitations
WKWebView is appropriate for web-based features, but native code must still enforce navigation, privacy, and interface policies.
- Typical applications: Help pages, terms and conditions, authenticated portals, payment-provider pages, HTML reports, and hybrid application screens.
- ATS enforcement: Plain HTTP content is normally blocked; narrowly scoped exceptions are safer than disabling ATS broadly.
- Untrusted content: URLs and JavaScript messages must be validated because loaded pages may attempt unwanted navigation or send malformed data.
- External links: Telephone, mail, App Store, or unsupported schemes may be passed to the system through
UIApplication.openrather than loaded internally. - Authentication state: Cookies and sessions may persist depending on the selected
WKWebsiteDataStore; sensitive workflows may require explicit deletion. - Connectivity failures: Delegate errors should produce a useful retry interface instead of a blank view.
- Native-versus-web trade-off: Web content is easy to update remotely, while native UIKit controls generally provide better platform integration, accessibility consistency, and performance.
- Memory management: Script message handlers can create strong-reference cycles; handlers and observers should be removed when the owning controller is released.
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 →