Objective-C 和 Swift URL 编码

swiftserver side programmingprogramming更新于 2025/8/14 9:52:17

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() {
    
    // 创建 URL 和 URLComponents 对象
    let urlString = "https://api.example.com/search"
    var urlComponents = URLComponents(string: urlString)
    // 编码查询参数
    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)
    }
    // 从 URLComponents 对象创建 URL 请求
    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
    
    // 发送请求并处理响应
    let task = URLSession.shared.dataTask(with: request) { data, request, error in
        // 根据需要解码响应数据
    }
    // 恢复任务
    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 字符串。然后,我们可以使用编码后的字符串发送请求和接收响应,并根据需要解码数据。



相关文章



关于我们 | 隐私条款 | 学习路线
返回顶部