ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCOMP4126Web Services Consuming…
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    COMP4126

    Mobile Application Development 2

    Progress0 / 38 done
    Topics38
    1Understanding Xcode2Using the Xcode interface builder and objects library3Understanding view hierarchy and creating a custom app icon
    4Understanding outlets and actions5Using text fields, buttons, labels, web views, and page controllers6Using views with subviews and creating views using code
    7Working with the single view template8Exploring the app delegate and adding new view controllers9Transitioning between multiple view controllers using animations
    10Tabbar and master detail templates
    11Customizing for different inputs12Adjusting text field behaviors and dismissing the keyboard13Detecting keyboard activities with notification center14Using scroll view and responding to keyboard activities programmatically
    15Detecting device hardware16Dynamically adjusting graphical layouts and creating universal apps
    17Understanding UITableView and UITableViewCell18Working with UITableView data source and delegate19Master detail template, drill-down menus, and navigation20Using property lists for data persistence and creating multi-section tables
    21Portrait and landscape modes22Handling device rotation and forcing specific orientation23Dynamically adjusting layouts based on rotation
    24Importing sqlite3 and creating a database25Writing tables, inserting records, and bundling a database with your app26Checking for database existence and reading/displaying data
    27NSTimer class and object transformations28Rotation, scaling, translation, animating image arrays, and playing video
    29Email, Safari, and SMS30Working with camera and photo library
    31Consuming and parsing XML and JSON32Integrating Twitter and Facebook with iOS apps
    33MapKit and MKMapView34Getting and displaying user location and directional information35Displaying map annotations, disclosure buttons, and reverse geocoding36Working with iCloud
    37Gyroscope and accelerometer38Outputting sensor data and using the Shake API
    4 min read
    Topic 31 of 38
    Topic Study Note Illustration
    31

    Using Web Services: Consuming and parsing XML and JSON

    A web service is a system that allows an iOS app to communicate with a server over the internet to send or receive data.

    🌐 Using Web Services in iOS: Consuming & Parsing XML and JSON (Xcode)


    βœ… 1. Definition

    πŸ”Ή Web Service

    A web service is a system that allows an iOS app to communicate with a server over the internet to send or receive data.

    πŸ‘‰ Example:

    • Weather apps
    • News apps
    • Social media apps

    πŸ”Ή Consuming Web Service

    It means requesting data from a server (API) and using it inside your app.


    πŸ”Ή Parsing

    Parsing means converting raw server data (JSON/XML) into usable Swift objects.


    🧠 2. Key Concepts

    πŸ”Ή API (Application Programming Interface)

    • A link between app and server
    • Example: weather API, Google API

    πŸ”Ή Data Formats

    • πŸ“¦ JSON (most common, lightweight)
    • πŸ“„ XML (older, structured format)

    πŸ”Ή URLSession

    • iOS class used to make network requests

    🌐 3. Consuming Web Services (General Flow)

    iOS App
       ↓
    URL Request
       ↓
    Server (API)
       ↓
    Response (JSON/XML)
       ↓
    Parsing
       ↓
    Display in App
    

    πŸ“¦ 4. Working with JSON


    πŸ”Ή What is JSON?

    JSON = JavaScript Object Notation It stores data in key-value format.

    Example JSON:

    {
      "name": "Ali",
      "age": 20
    }
    

    πŸ”Ή Step 1: Create URL Request

    let url = URL(string: "https://api.example.com/user")!
    

    πŸ”Ή Step 2: Fetch Data

    URLSession.shared.dataTask(with: url) { data, response, error in
        
        if let data = data {
            print(data)
        }
    }.resume()
    

    πŸ”Ή Step 3: Parse JSON

    if let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
        
        let name = json["name"] as? String
        let age = json["age"] as? Int
        
        print(name ?? "", age ?? 0)
    }
    

    πŸ“„ 5. Working with XML


    πŸ”Ή What is XML?

    XML = Extensible Markup Language It uses tags like HTML.

    Example XML:

    <user>
        <name>Ali</name>
        <age>20</age>
    </user>
    

    πŸ”Ή Step 1: Fetch XML Data

    let url = URL(string: "https://api.example.com/user.xml")!
    

    πŸ”Ή Step 2: Parse XML using XMLParser

    class XMLParserDelegateClass: NSObject, XMLParserDelegate {
        
        var currentElement = ""
        var name = ""
        var age = ""
        
        func parser(_ parser: XMLParser, foundCharacters string: String) {
            if currentElement == "name" {
                name += string
            } else if currentElement == "age" {
                age += string
            }
        }
        
        func parser(_ parser: XMLParser, didStartElement elementName: String,
                    namespaceURI: String?, qualifiedName qName: String?,
                    attributes attributeDict: [String : String] = [:]) {
            currentElement = elementName
        }
    }
    

    πŸ”Ή Step 3: Start Parsing

    let parser = XMLParser(contentsOf: url)!
    let delegate = XMLParserDelegateClass()
    
    parser.delegate = delegate
    parser.parse()
    

    πŸ“Š 6. JSON vs XML Comparison

    Feature JSON XML
    Size Small Large
    Speed Fast Slow
    Readability Easy Complex
    Usage Modern APIs Legacy systems

    πŸ’‘ 7. Example App

    🎯 Weather App

    • Sends request to API
    • Gets JSON response
    • Parses temperature, city, humidity
    • Displays in UI

    πŸ“Œ 8. Important Rules / Tips

    • Always use HTTPS URLs
    • Use background threads for network calls
    • Parse JSON safely (avoid force unwrapping)
    • Handle errors properly
    • Use Codable for modern JSON parsing

    πŸ”₯ Modern JSON Parsing (Best Practice)

    struct User: Codable {
        let name: String
        let age: Int
    }
    

    ⚠️ 9. Common Mistakes

    • ❌ Blocking main thread with network calls
    • ❌ Force unwrapping JSON values
    • ❌ Wrong API URL
    • ❌ Not handling errors
    • ❌ Using outdated parsing methods

    🧠 10. Best Practices

    • Use URLSession for networking
    • Use Codable for JSON parsing
    • Always handle optional values safely
    • Use background queues
    • Test APIs using Postman

    πŸ“ 11. Likely Exam Questions

    1. What is a web service in iOS?
    2. Differentiate JSON and XML.
    3. What is parsing in iOS?
    4. Write steps to consume a web API.
    5. What is URLSession used for?
    6. How do you parse JSON in Swift?
    7. What is XMLParser?
    8. Why is JSON preferred over XML?

    πŸ“š 12. Quick Revision Summary

    • Web service = server communication

    • Data formats:

      • JSON β†’ lightweight, modern
      • XML β†’ structured, older
    • Steps:

      1. Send request
      2. Get response
      3. Parse data
      4. Display in UI
    • Use URLSession for networking

    • Use Codable for modern JSON parsing


    ← Previous topic 30
    Working with camera and photo library
    Next topic 32 β†’
    Integrating Twitter and Facebook with iOS apps

    Past Papers

    Open this section to view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    4mremaining
    678words
    Beginnerlevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Mobile Application Development 2