Unit 6: Web Services

INT372 — Iphone Application Programming 9 min read

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:
    • MapKit supplies maps, annotations, overlays, geocoding-related types, and map interaction.
    • CoreLocation obtains device location and authorization status.
    • WebKit supplies WKWebView and 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.plist and explicit user authorization.
  • Security rule: App Transport Security, or ATS, normally requires secure HTTPS connections.
  • 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.
SWIFT
import MapKit
import CoreLocation
  • Map view creation: MKMapView may be added in Interface Builder or created programmatically; Auto Layout constraints normally attach it to the containing view.
SWIFT
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 mapType property 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.
SWIFT
mapView.mapType = .standard
  • Coordinate representation: CLLocationCoordinate2D stores latitude and longitude in decimal degrees.
    • latitude: Angular distance north or south of the equator, from -90 to 90.
    • longitude: Angular distance east or west of the prime meridian, commonly from -180 to 180.
SWIFT
let coordinate = CLLocationCoordinate2D(
    latitude: 13.0827,
    longitude: 80.2707
)
  • Visible region: MKCoordinateRegion combines a center coordinate with a span.
    • latitudeDelta: North–south extent in degrees.
    • longitudeDelta: East–west extent in degrees.
    • Smaller deltas produce a closer zoom.
SWIFT
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. MKPointAnnotation is suitable for simple markers.
SWIFT
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. MKMarkerAnnotationView provides a standard marker and callout.
SWIFT
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.
SWIFT
mapView.delegate = self

func mapView(
    _ mapView: MKMapView,
    regionDidChangeAnimated animated: Bool
) {
    let center = mapView.centerCoordinate
    print("Center: \(center.latitude), \(center.longitude)")
}
  • Visible-area measurement: mapView.region expresses the visible coordinate region, while mapView.visibleMapRect expresses it as an MKMapRect. 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 in regionDidChangeAnimated.
  • User-location display: Setting showsUserLocation asks the map to display the location supplied by Core Location, but it does not itself replace permission management.
SWIFT
mapView.showsUserLocation = true
  • Authorization requirement: For foreground access, Info.plist needs NSLocationWhenInUseUsageDescription. The text must explain why location is required, such as locating the user on a delivery map.
  • Location manager: CLLocationManager requests authorization and reports location-related state.
SWIFT
let locationManager = CLLocationManager()

locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
  • Authorization monitoring: locationManagerDidChangeAuthorization(_:) detects whether access became authorized, denied, restricted, or remained undetermined.
SWIFT
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 updated MKUserLocation; the contained location may initially be nil while 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 an MKOverlayRenderer such as MKPolylineRenderer.
  • Camera control: MKMapCamera controls 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.horizontalAccuracy expresses 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 WKWebViewConfiguration is supplied at initialization; major configuration should be completed before creating the web view.
SWIFT
import WebKit

let configuration = WKWebViewConfiguration()
let webView = WKWebView(frame: .zero,
                        configuration: configuration)
webView.navigationDelegate = self
  • Remote URL loading: A valid URL is wrapped in URLRequest and passed to load(_:).
SWIFT
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. The baseURL determines how relative stylesheet, script, and image paths are resolved.
SWIFT
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() and goForward(): Traverse page history.
    • reload(): Requests the current page again.
    • stopLoading(): Cancels the active navigation.
    • canGoBack and canGoForward: Indicate whether navigation buttons should be enabled.
  • Navigation lifecycle: WKNavigationDelegate reports important stages.
    • didStartProvisionalNavigation: Loading has begun.
    • didCommit: Initial content has arrived.
    • didFinish: Navigation completed.
    • didFailProvisionalNavigation or didFail: Loading failed.
SWIFT
func webView(
    _ webView: WKWebView,
    didFinish navigation: WKNavigation!
) {
    print("Loaded: \(webView.url?.absoluteString ?? "unknown")")
}
  • Navigation policy: decidePolicyFor can permit or cancel a request. The decision handler must be called exactly once.
SWIFT
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: estimatedProgress ranges from 0.0 to 1.0 and 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.
SWIFT
webView.evaluateJavaScript("document.title") { result, error in
    if let title = result as? String {
        print(title)
    }
}
  • JavaScript messages: WKUserContentController enables 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 a WKUIDelegate implementation 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.open rather 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.