Swift URLSession任务下载顺序

时间:2016-10-25 15:13:56

标签: ios background urlsession

我需要按顺序下载多个文件。我还希望将来有可能在每次下载之间设置一个时间间隔,以减少服务器负载(我从OpenStreetMap下载磁贴)。此下载必须能够在后台运行。

我目前正在这样做:

let config:URLSessionConfiguration = URLSessionConfiguration.background(withIdentifier:"offline-map-download");
config.sessionSendsLaunchEvents = true;
config.isDiscretionary = true;

let queue:OperationQueue = OperationQueue();
queue.name = "download";
queue.maxConcurrentOperationCount = 1;

let session = URLSession(configuration:config, delegate:self, delegateQueue:queue);

for i in 0 ..< 10 {

    let url:URL = URL(string:"http://tile.openstreetmap.org/7/63/\(i).png")!;

    print("add \(url) to queue");

    session.dataTask(with:url).resume();
}

这是我的代表的didCompleteWithError方法:

public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {

    print("received \(task.currentRequest!.url!)");
}

我希望&#34;收到&#34;日志打印的顺序与&#34;添加到队列&#34;相同。日志。事实并非如此。这是正常的吗?

更一般地说,我是否在正确的道路上进行后台下载(相当于Android服务)?目前我还没有真正的设备,而且我正在使用模拟器。当我按下主页按钮时,我的应用程序是否在后台运行(问这个是因为即使我使用URLSessionConfiguration.default配置,当我按下主页时,我的下载仍在继续)?

0 个答案:

没有答案