Api Calling (Basic To Advance)

 What is Api Calling?

API calling in a mobile app refers to the process of making requests to external Application Programming Interfaces (APIs) from within the mobile application. APIs act as a bridge between the mobile app and external data sources or services, allowing the app to access and integrate relevant information and functionalities.


Api Calling in iOS/ Swift5 :-


Basically we need this normal steps written below to perform Api call in iOS apps.

1. URL Construction :

 - Think of this step as setting the destination for your data request. You need to know exactly where you want to send your request. This involves creating a URL that points to the API endpoint.


   - Create a `URL` object that represents the API endpoint you want to access.

   - Construct the URL by combining the base URL of the API and any necessary query parameters or path components.



2. URL Request Creation:


   - Create a `URLRequest` object to encapsulate the details of the API call, such as the HTTP method (GET, POST, PUT, DELETE), headers, and request body (if applicable).



3. URL Session and Task Creation:


   - Obtain a `URLSession` object, which manages the underlying network connection and provides a set of APIs for making the API call.

   - Create a `URLSessionDataTask` (or another appropriate task type) to represent the API call and execute it.


4. Asynchronous Execution:


   - API calls in iOS apps are typically performed asynchronously to avoid blocking the main UI thread.

   - The `URLSessionDataTask` is executed on a background thread, and the app's main thread continues to handle user interactions and UI updates.


5. Handling the Response:


   - When the API call completes, the `URLSessionDataTask` calls a completion handler with the response data, HTTP headers, and any encountered errors.

   - In the completion handler, you can parse the response data (often in JSON format) and update the app's UI or model accordingly.


6. Error Handling:


   - Check for any errors that may have occurred during the API call, such as network connectivity issues or server-side errors.

   - Implement appropriate error handling mechanisms to provide a good user experience, such as displaying error messages or retrying the API call.


7. Caching and Offline Support:


   - To improve performance and provide offline functionality, you can implement caching strategies to store and reuse API response data locally.

   - This may involve using technologies like Core Data, SQLite, or third-party caching libraries.



* Normal Get-Api Call For Understanding Api Work In Swift Language.


1. create url:

let apiUrl = URL(string: "https://api.example.com/data")!


2. create request:

var request = URLRequest(url: apiUrl) 
request.httpMethod = "GET"

3. create session

let session = URLSession.shared

4. create task block of api call:

let task = session.dataTask(with: request) { (data, response, error) in
    if let error = error { 
        print("Error: \(error.localizedDescription)"
        return 
     }
}

5. Execute this task:

task.resume()

6. Decode Api Response:

let task = session.dataTask(with: request) { (data, response, error) in
    if let error = error { 
        print("Error: \(error.localizedDescription)"
        return 
     }
    
        guard let data else{
            return
        }
    
            do
                let json = try JSONSerialization.jsonObject(with: responseData, options: []) 
                print("Response JSON: \(json)")
             } 
            catch
                print("Error decoding JSON: \(error.localizedDescription)"
             }
    
}



* Normal Post-Api Call For Understanding Api Work In Swift Language.


we are going to call json placeholder post api for study purpose and better explanation of post api.



 1. Define the URL


swift

guard let url = URL(string: "https://jsonplaceholder.typicode.com/posts") else {

    print("Invalid URL")

    return

}


you already know what is url from get api.


 2. Create URLRequest


swift

var request = URLRequest(url: url)

request.httpMethod = "POST"

request.setValue("application/json; charset=UTF8", forHTTPHeaderField: "ContentType")



URLRequest is a class that encapsulates the details of an HTTP request.


 Function:

   URLRequest(url:) creates a request object for the specified URL.

   httpMethod sets the HTTP method to "POST", indicating that the request will send data to the server.

   setValue(_:forHTTPHeaderField:) adds a header field to the request. Here, it sets the ContentType header to "application/json; charset=UTF8", indicating that the body of the request will be in JSON format.


 3. Create the Request Body


swift

- we are sending this body with request to run process or execute some task at server side.


let body: [String: Any] = [

    "title": "foo",

    "body": "bar",

    "userId": 1

]


do {

    request.httpBody = try JSONSerialization.data(withJSONObject: body, options: [])

} catch {

    print("Error encoding body to JSON: \(error)")

    return

}


The request body contains the data that will be sent to the server.


   body is a dictionary representing the data you want to send. In this case, it's a JSON object with fields "title", "body", and "userId".

   JSONSerialization.data(withJSONObject:options:) converts the dictionary to JSON data. This data is set as the httpBody of the request.

   docatch block handles potential errors that might occur during JSON serialization.


 4. Create and Start a URLSession Data Task


swift

let task = URLSession.shared.dataTask(with: request) { data, response, error in

    if let error = error {

        print("Error in request: \(error)")

        return

    }

    

    guard let data = data else {

        print("No data received")

        return

    }

    

    do {

        if let jsonResponse = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {

            print(jsonResponse)

        }

    } catch {

        print("Error decoding JSON response: \(error)")

    }

}

task.resume()



This block performs the actual network request and handles the response.


   URLSession.shared.dataTask(with:completionHandler:) creates a data task that performs the network request. completionHandler is a closure that is called when the request completes.

   Inside the closure:

     if let error = error checks if there was an error with the request and prints it if present.

     guard let data = data ensures that data was received. If not, it prints an error message and exits.

     JSONSerialization.jsonObject(with:options:) parses the JSON data into a Swift dictionary.

     The docatch block handles errors that might occur during JSON parsing.

   task.resume() starts the network request. Without calling resume(), the task will not execute.


 Additional Considerations


1. Network Permissions: Ensure your app has the appropriate permissions to access the network. This might involve configuring Info.plist if needed.


2. Error Handling: Proper error handling is crucial for debugging and user experience. This includes handling network errors, invalid responses, and JSON parsing errors.


3. Background Execution: Network tasks should be performed in the background to avoid blocking the main thread. URLSession handles this for you as it performs network requests asynchronously.


4. Security: When making network requests, ensure data is sent securely over HTTPS. Also, handle sensitive information appropriately and comply with privacy regulations.





Comments

Popular posts from this blog

Complete iOS Developer Guide - Swift 5 by @hiren_syl |  You Must Have To Know 😎 

Debugging

Swift Fundamentals You Can’t Miss! A List by @hiren_syl