• 请不要在回答技术问题时复制粘贴 AI 生成的内容
Auston
V2EX  ›  程序员

用 Swift 开发 http post 请求客户端时,怎么优先使用 ipv4?或者直接禁用 ipv6

  •  
  •   Auston · Feb 6, 2023 · 1312 views
    This topic created in 1283 days ago, the information mentioned may be changed or developed.

    最近遇到一个问题,用 swift 的 URLSession 库请求远程服务时,经常遇到数据传输慢的情况,在纯 ipv4 环境下就没有交互慢的问题,后来排查是因为 ipv6 导致的。

    让用户在纯 ipv4 网络下使用 app 根本不现实,让运维关闭服务器的 ipv6 解析也不现实,只能寄希望于代码端了。

    请问各位大佬,怎么在代码层面限制只使用 ipv4 进行交互?或者优先使用 ipv4 也行。

    有没有第三方库推荐的?

    3 replies    2023-02-06 15:02:15 +08:00
    xinJang
        1
    xinJang  
       Feb 6, 2023
    修改 hosts
    NouveauNom
        2
    NouveauNom  
       Feb 6, 2023
    自行测试

    let config = URLSessionConfiguration.default
    config.networkServiceType = .default
    //config.allowsCellularAccess = false
    config.connectionProxyDictionary = [:]
    config.ipv6Enabled = false
    let session = URLSession(configuration: config)

    let url = URL(string: "https://example.com/api")!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.httpBody = "request_data".data(using: .utf8)

    let task = session.dataTask(with: request) { (data, response, error) in
    // Handle response
    }
    task.resume()
    NouveauNom
        3
    NouveauNom  
       Feb 6, 2023
    忽略上面的回答。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3517 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 05:02 · PVG 13:02 · LAX 22:02 · JFK 01:02
    ♥ Do have faith in what you're doing.