注意:这不是重复,因为我在swift工作,而不是Objective C,所以请不要将其标记为。
我有以下代码来下载文件:
func loadFileAsync(url: NSURL, name: String, completion:(path:String, error:NSError!) -> Void) {
let documentsUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first as NSURL!
let destinationUrl = documentsUrl.URLByAppendingPathComponent(name)
tempDocPath = destinationUrl.path!
if NSFileManager().fileExistsAtPath(destinationUrl.path!) {
print("file already exists [\(destinationUrl.path!)]")
completion(path: destinationUrl.path!, error:nil)
} else {
let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "GET"
let task = session.dataTaskWithRequest(request, completionHandler: { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
if (error == nil) {
if let response = response as? NSHTTPURLResponse {
print("response=\(response)")
if response.statusCode == 200 {
if data!.writeToURL(destinationUrl, atomically: true) {
print("file saved [\(destinationUrl.path!)]")
completion(path: destinationUrl.path!, error:error)
} else {
print("error saving file")
let error = NSError(domain:"Error saving file", code:1001, userInfo:nil)
completion(path: destinationUrl.path!, error:error)
}
}
}
}
else {
print("Failure: \(error!.localizedDescription)");
completion(path: destinationUrl.path!, error:error)
}
})
task.resume()
}
}
为了显示进度视图,我需要找到读取的字节数和预期读取的字节数?
答案 0 :(得分:1)
请勿使用dataTaskWithRequest(_, completionHandler:)
方法创建数据任务。而是使用dataTaskWithRequest(_)
,设置委托,并实现URLSession(_, dataTask:,data:)
委托方法并监控您收到的数据块的大小。