Objective-C and Swift URL encoding


URL encoding is an essential part of iOS app development. Many times, you will need to encode the URL to communicate with servers. Let's look at some examples of how you can encode an URL in Swift and Objective-C.

URL Encoding in Swift

In Swift, you can use the addingPercentEncoding(withAllowedCharacters:) method for URL encoding.

URL Encoding in Objective-C

In Objective-C, you can use the stringByAddingPercentEncodingWithAllowedCharacters method for URL encoding.

Encode a URL in Objective-C

In Objective-C, you can encode a URL string using the stringByAddingPercentEncodingWithAllowedCharacters: method of the NSString class. Here's an example

NSString *stringToEncode = @"https://www.exampleserver.com/complete path with spaces";
NSCharacterSet *allowedCharacters = [NSCharacterSet URLQueryAllowedCharacterSet];
NSString *encodedString = [stringToEncode stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];
NSLog(@"%@", encodedString); // Output: https://www.exampleserver.com/complete%20path%20with%20spaces

Encode a URL in Swift

In Swift, you can use the addingPercentEncoding(withAllowedCharacters:) method of the String class to encode a URL string. Here's an example −

Example

import Foundation
let stringToEncode = "https://www.exampleserver.com/complete path with spaces"
let allowedCharacters = CharacterSet.urlQueryAllowed
if let encodedString = stringToEncode.addingPercentEncoding(withAllowedCharacters: allowedCharacters) {
   print("Original URL: \(stringToEncode)")
   print("Encoded URL: \(encodedString)")
}

Output

Original URL: https://www.exampleserver.com/complete path with spaces
Encoded URL: https://www.exampleserver.com/complete%20path%20with%20spaces

In both cases, the allowedCharacters variable specifies the set of characters that are allowed to appear in the encoded URL. The URLQueryAllowedCharacterSet is a commonly used character set for encoding URLs.

Here's an example of using URL encoding in Swift for a networking request

URL encoding is a necessary step in network communication to ensure that URLs and data are correctly handled and transmitted without causing errors or ambiguity. Here are the steps you can follow to use URL encoding in networking −

  • When sending data as part of a request, encode any query parameters, form data, or other data that is included in the URL or body of the request. You can use the appropriate encoding method for your programming language, as described earlier in this conversation.

  • The server may also deliver encoded data when receiving data as a response, such as query parameters or special characters in URLs. The correct decoding technique for your programming languages, such as URLDecoder in Java or URLComponents in Swift, must be used to decode this data.

  • Make sure to use the proper encoding method to encode any unusual characters, spaces, or query parameters when creating dynamic URLs. By doing this, you can verify that your URLs are properly formed and help prevent issues.

Example

import Foundation
import UIKit
func sendSearchRequest() {
    
   // creating a URL and URLComponents object
   let urlString = "https://api.example.com/search"
   var urlComponents = URLComponents(string: urlString)
   // encode query parameters
   let queryItems = [
      URLQueryItem(name: "query", value: "tutorials point"),
      URLQueryItem(name: "limit", value: "20")
   ]
   urlComponents?.queryItems = queryItems.map { item in
      let encodedValue = item.value?.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
      return URLQueryItem(name: item.name, value: encodedValue)
   }
   // creating a URL request from the URLComponents object
   guard let url = urlComponents?.url else { return }
   var request = URLRequest(url: url)
   request.httpMethod = "GET"
    
   // URL: https://api.example.com/search?query=tutorials%2520point&limit=20
    
   // sending the request and handling the response
   let task = URLSession.shared.dataTask(with: request) { data, response, error in
      // Decode response data as needed
   }
   // resuming the task
   task.resume()
}

In this example, a basic URL and a collection of query parameters are used to construct a URLComponents object. The query parameter values are then encoded using the addingPercentEncoding method and put as query items in the URLComponents object. The HTTP method is then set to "GET" in a URLRequest that is created from the URL, and the request is sent through a URLSession. We can decode the information as necessary after we get the response.

Here are some common use cases for URL encoding

  • The form data is often sent as query parameters in the URL when a user submits a form on a website. Query parameters must be encoded before being submitted since they may contain special characters.

  • Encoding special characters in URLs: In order to prevent misunderstanding with other elements of the URL, special characters like ampersands, question marks, and equal signs must be encoded.

  • Spaces in URLs should be encoded carefully because they may lead to problems or be seen as independent URL components. Spaces are often encoded as "%20" to avoid this.

Conclusion

In Objective-C and Swift, we can use methods like stringByAddingPercentEncodingWithAllowedCharacters: and addingPercentEncoding(withAllowedCharacters:) to encode URL strings. We can then use the encoded strings to send requests and receive responses, and decode the data as needed.

Updated on: 11-Apr-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements