Ste*_*ick 6 ios nsurlsession swift ios8 ios9
使用NSURLSession后台配置时是否可以检测 DNS 查找失败?
如果我使用默认配置和完成处理程序,则错误参数中会报告 DNS 解析失败。但是,如果我使用后台配置,则永远不会报告失败并且永远不会调用委托方法。
该NSURLSessionTaskDelegate协议的 Apple 文档说:
服务器错误不会通过 error 参数报告。您的委托通过错误参数收到的唯一错误是客户端错误,例如无法解析主机名或连接到主机。
这表明我应该在那里看到 DNS 失败消息。下面的代码说明了这种行为。我已经在 iOS 8.4 和 9 设备和模拟器上进行了测试,并搜索了开发论坛、SO 和使用流行的搜索引擎,但结果是空的。我确定我一定遗漏了一些非常简单的东西。
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, NSURLSessionTaskDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let bgsesh = NSURLSession(configuration: NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("foobarbazqwux"), delegate: self, delegateQueue: nil)
let dfsesh = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: nil, delegateQueue: nil)
let url = NSURL(string: "http://foobarbaz.qwzx")!
let a = dfsesh.downloadTaskWithURL(url) { (url:NSURL?, resp:NSURLResponse?, err:NSError?) -> Void in
print(err)
/*
Optional(Error Domain=NSURLErrorDomain Code=-1003
"A server with the specified hostname could not be found."
UserInfo=0x146e8050 {
NSErrorFailingURLStringKey=http://foobarbaz.qwzx/,
_kCFStreamErrorCodeKey=8,
NSErrorFailingURLKey=http://foobarbaz.qwzx/,
NSLocalizedDescription=A server with the specified hostname could not be found.,
_kCFStreamErrorDomainKey=12,
NSUnderlyingError=0x14693ab0 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1003.)"
})
*/
}
a.resume()
let b = bgsesh.downloadTaskWithURL(url)
b.resume()
return true
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
// never runs, DNS failure is not reported for background config :-(
print("didCompleteWithError: \(task.taskIdentifier) \(error)")
}
// ... other delegate methods ...
}
Run Code Online (Sandbox Code Playgroud)
放URLSessionConfiguration.timeoutIntervalForResource。
资源超时间隔控制放弃之前等待整个资源传输的时间(以秒为单位)。
默认值为 7 天。
例如,
let conf = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("foobarbazqwux")
conf.timeoutIntervalForResource = 60 // seconds
let session = NSURLSession(configuration: conf, delegate: self, delegateQueue: nil)
Run Code Online (Sandbox Code Playgroud)
在这种情况下,如果 60 秒后仍然失败,系统将重试连接并调用委托。
根据@algrid 的评论进行编辑:
该值应考虑资源的传输时间。因此,这取决于下载/上传的资源大小和网络速度。
| 归档时间: |
|
| 查看次数: |
864 次 |
| 最近记录: |