ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Mobile Application Development 2
    COMP4126
    Progress0 / 38 topics
    Topics
    1. Creating an iOS App: Understanding Xcode2. Using the Xcode interface builder and objects library3. Understanding view hierarchy and creating a custom app icon4. Outlets, Actions, and Views: Understanding outlets and actions5. Using text fields, buttons, labels, web views, and page controllers6. Using views with subviews and creating views using code7. Using View Controllers: Working with the single view template8. Exploring the app delegate and adding new view controllers9. Transitioning between multiple view controllers using animations10. Application Templates: Tabbar and master detail templates11. The iOS Keyboard: Customizing for different inputs12. Adjusting text field behaviors and dismissing the keyboard13. Detecting keyboard activities with notification center14. Using scroll view and responding to keyboard activities programmatically15. Working with Different iOS Devices (iPhone & iPad): Detecting device hardware16. Dynamically adjusting graphical layouts and creating universal apps17. Using Table Views: Understanding UITableView and UITableViewCell18. Working with UITableView data source and delegate19. Master detail template, drill-down menus, and navigation20. Using property lists for data persistence and creating multi-section tables21. Supporting Screen Rotations: Portrait and landscape modes22. Handling device rotation and forcing specific orientation23. Dynamically adjusting layouts based on rotation24. Working with Databases: Importing sqlite3 and creating a database25. Writing tables, inserting records, and bundling a database with your app26. Checking for database existence and reading/displaying data27. Using Animations & Video: NSTimer class and object transformations28. Rotation, scaling, translation, animating image arrays, and playing video29. Accessing Integrated iOS Apps: Email, Safari, and SMS30. Working with camera and photo library31. Using Web Services: Consuming and parsing XML and JSON32. Integrating Twitter and Facebook with iOS apps33. Working with iOS Maps and Location Services: MapKit and MKMapView34. Getting and displaying user location and directional information35. Displaying map annotations, disclosure buttons, and reverse geocoding36. Working with iCloud37. Working with the Accelerometer: Gyroscope and accelerometer38. Outputting sensor data and using the Shake API
    COMP4126›Using Web Services: Consuming and parsing XML and JSON
    Mobile Application Development 2Topic 31 of 38

    Using Web Services: Consuming and parsing XML and JSON

    4 minread
    678words
    Beginnerlevel

    🌐 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 load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time4 min
      Word count678
      Code examples0
      DifficultyBeginner