Objective-C 和 Swift URL 編碼


URL 編碼是 iOS 應用開發中必不可少的一部分。很多時候,您需要對 URL 進行編碼才能與伺服器進行通訊。讓我們看看如何在 Swift 和 Objective-C 中對 URL 進行編碼的一些示例。

Swift 中的 URL 編碼

在 Swift 中,您可以使用 addingPercentEncoding(withAllowedCharacters:) 方法進行 URL 編碼。

Objective-C 中的 URL 編碼

在 Objective-C 中,您可以使用 stringByAddingPercentEncodingWithAllowedCharacters 方法進行 URL 編碼。

在 Objective-C 中編碼 URL

在 Objective-C 中,您可以使用 NSString 類的 stringByAddingPercentEncodingWithAllowedCharacters: 方法對 URL 字串進行編碼。這是一個示例

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

在 Swift 中編碼 URL

在 Swift 中,您可以使用 String 類的 addingPercentEncoding(withAllowedCharacters:) 方法對 URL 字串進行編碼。這是一個示例 -

示例

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)")
}

輸出

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

在這兩種情況下,allowedCharacters 變數都指定了允許出現在編碼後的 URL 中的字元集。URLQueryAllowedCharacterSet 是一個常用的用於編碼 URL 的字元集。

這是一個在 Swift 中使用 URL 編碼進行網路請求的示例

URL 編碼是網路通訊中必要的一步,以確保 URL 和資料得到正確處理和傳輸,而不會導致錯誤或歧義。您可以按照以下步驟在網路中使用 URL 編碼 -

  • 在將資料作為請求的一部分發送時,對包含在 URL 或請求正文中的任何查詢引數、表單資料或其他資料進行編碼。您可以使用適用於您的程式語言的適當編碼方法,如前面在本對話中所述。

  • 伺服器在接收資料作為響應時也可能提供編碼資料,例如 URL 中的查詢引數或特殊字元。必須使用適用於您的程式語言的正確解碼技術(例如 Java 中的 URLDecoder 或 Swift 中的 URLComponents)來解碼這些資料。

  • 在建立動態 URL 時,請確保使用正確的編碼方法對任何不尋常的字元、空格或查詢引數進行編碼。透過這樣做,您可以驗證您的 URL 是否格式正確,並有助於防止出現問題。

示例

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()
}

在此示例中,使用基本 URL 和查詢引數集合來構造 URLComponents 物件。然後,使用 addingPercentEncoding 方法對查詢引數值進行編碼,並將其作為查詢項放入 URLComponents 物件中。然後,在從 URL 建立的 URLRequest 中將 HTTP 方法設定為“GET”,並將請求透過 URLSession 傳送。在收到響應後,我們可以根據需要解碼資訊。

以下是 URL 編碼的一些常見用例

  • 當用戶在網站上提交表單時,表單資料通常作為 URL 中的查詢引數傳送。由於查詢引數可能包含特殊字元,因此必須在提交之前對其進行編碼。

  • 對 URL 中的特殊字元進行編碼:為了避免與 URL 的其他元素產生混淆,必須對諸如 &、?和 = 等特殊字元進行編碼。

  • URL 中的空格應謹慎編碼,因為它們可能會導致問題或被視為獨立的 URL 元件。為了避免這種情況,空格通常被編碼為“%20”。

結論

在 Objective-C 和 Swift 中,我們可以使用 stringByAddingPercentEncodingWithAllowedCharacters: 和 addingPercentEncoding(withAllowedCharacters:) 等方法對 URL 字串進行編碼。然後,我們可以使用編碼後的字串傳送請求和接收響應,並根據需要解碼資料。

更新於: 2023年4月11日

2K+ 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.