【问题标题】:iOS: throttle bandwidth of e.g. AlamofireiOS:限制带宽,例如阿拉莫菲尔
【发布时间】:2017-02-07 18:55:59
【问题描述】:

是否可以限制上传操作的带宽,例如Alamofire?

我想在用户使用应用程序时在后台上传数据并上传和下载更重要的内容。
因此,我想在特定条件下限制后台带宽情况。

到目前为止,我发现的唯一可能性是使用ASIHTTPRequest,它有一个maxBandwidthPerSecond 属性,但是那个库太旧了,我想使用更新的东西。

【问题讨论】:

标签: swift alamofire


【解决方案1】:

我找不到关于 Alamofire(快速部分)的任何信息,但您可以使用 AFNetwork

您可以从 link (AFNetworking/AFNetworking/AFURLRequestSerialization.h) 中看到来源报告:

/**
 Throttles request bandwidth by limiting the packet size and adding a delay for each chunk read from the upload stream.
 When uploading over a 3G or EDGE connection, requests may fail with "request body stream exhausted". Setting a maximum packet size and delay according to the recommended values (`kAFUploadStream3GSuggestedPacketSize` and `kAFUploadStream3GSuggestedDelay`) lowers the risk of the input stream exceeding its allocated bandwidth. Unfortunately, there is no definite way to distinguish between a 3G, EDGE, or LTE connection over `NSURLConnection`. As such, it is not recommended that you throttle bandwidth based solely on network reachability. Instead, you should consider checking for the "request body stream exhausted" in a failure block, and then retrying the request with throttled bandwidth.
 @param numberOfBytes Maximum packet size, in number of bytes. The default packet size for an input stream is 16kb.
 @param delay Duration of delay each time a packet is read. By default, no delay is set.
 */
- (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes
                                  delay:(NSTimeInterval)delay;

@end

您可以在 Objective-C 中构建您的自定义“NetworkManager”类,并轻松将其导入您的 swift 项目。

【讨论】:

    【解决方案2】:

    Chilkat API 提供了一个 CKOSocket(),可以像这样限制使用的带宽:

    //  To use bandwidth throttling, the connection should be made using the socket API.
    //  This provides numerous properties to customize the connection, such as
    //  BandwidthThrottleDown, BandwidthThrottleUp, ClientIpAddress, ClintPort, Http Proxy,
    //  KeepAlive, PreferIpv6, RequireSslCertVerify, SoRcvBuf, SoSndBuf, SoReuseAddr,
    //  SOCKS proxy, TcpNoSDelay, TlsPinSet, TlsCipherSuite, SslAllowedCiphers, etc.
    
    let socket = CkoSocket()
    var maxWaitMs: Int = 5000
    var success: Bool = socket.Connect("content.dropboxapi.com", port: 443, ssl: true, maxWaitMs: maxWaitMs)
    if success != true {
        print("\(socket.LastErrorText)")
        print("Connect Fail Reason: \(socket.ConnectFailReason.integerValue)")
        return
    }
    
    //  Set the upload bandwidth throttle rate to 50000 bytes per second.
    socket.BandwidthThrottleUp = 50000 
    

    Check this 获取更多文档。

    文档中的示例演示了如何通过 REST API 使用上传带宽限制。它将使用文件流将文件上传到 Drobox,并限制可用于传输的带宽。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-03
      • 1970-01-01
      • 2016-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-07
      相关资源
      最近更新 更多