gpt4 book ai didi

swift - 如何等待 dataTaskWithRequest 完成 - Swift?

转载 作者:行者123 更新时间:2023-11-30 13:20:41 25 4
gpt4 key购买 nike

如有必要,我会尝试比较文件(图 block ),以替换手机上的旧文件和网站上的新文件。但是 func pathDir 中的 returnPathFile 被分配了对文件的引用,而无需等待检查并下载新文件。我如何才能等到新文件的测试和加载(如果需要)完成?

let urls = { (x: UInt, y: UInt, zoom: UInt) -> NSURL in
let pathtodir = "tiles/\(zoom)/\(x)"
let pathtofile = "\(y).png"
let url = FileManagement.pathDir(pathtodir, file: pathtofile)
return url
}
layerTile = GMSURLTileLayer(URLConstructor: urls)
layerTile.map = self.viewMap!

分析iPhone中是否存在文件的方法:

class func pathDir(dir: String, file: String) -> NSURL {
var returnPathFile = NSURL(string: "http://****.***/\(dir)/\(file)")
let url = NSURL(string: "http://*****.***/\(dir)/\(file)")
let pathFile = applicTempDir().stringByAppendingPathComponent("\(dir)/\(file)")
let documentsUrl = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent("\(dir)/\(file)")
var attributesToInt: Int!

if filemgr.fileExistsAtPath("\(pathFile)") {
returnPathFile = NSURL(fileURLWithPath: pathFile)
let fileManager = NSFileManager.defaultManager()
do {
let attributes = try fileManager.attributesOfItemAtPath(pathFile)["NSFileCreationDate"] as! NSDate
attributesToInt = Int(attributes.timeIntervalSinceReferenceDate)
}
catch let error as NSError {
print("Ooops! Something went wrong: \(error)")
}
JsonData.isConnectedToNetwork(url!, dateFileOnTemp: attributesToInt, urlFileOnTemp: documentsUrl, pathFileOnTemp: pathFile, completion:{(path:String, error:NSError!) in
})
if filemgr.fileExistsAtPath("\(pathFile)") {
returnPathFile = NSURL(fileURLWithPath: pathFile)
return returnPathFile!
} else {
return returnPathFile!
}
}
}

方法主持人两个文件:

class func isConnectedToNetwork(url: NSURL, dateFileOnTemp: Int, urlFileOnTemp: NSURL, pathFileOnTemp: String, completion:(path:String, error:NSError!) -> Void) {
var dates: String!
let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "HEAD"
let task = session.dataTaskWithRequest(request, completionHandler: { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
if (error == nil) {
if let response = response as? NSHTTPURLResponse {
dates = response.allHeaderFields["Last-Modified"] as! String
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEE',' dd MMM yyyy HH':'mm':'ss 'GMT'"
dateFormatter.timeZone = NSTimeZone(abbreviation: "GMT")
let dateFileOnSite = dateFormatter.dateFromString(dates)
let dateFileOnSiteInt = Int(dateFileOnSite!.timeIntervalSinceReferenceDate)
if dateFileOnSiteInt > dateFileOnTemp {
FileManagement.reDelFile(pathFileOnTemp)
JsonData.reLoadFileAsync(url, destinationUrl: urlFileOnTemp as NSURL, completion:{(path:String, error:NSError!) in
})
}
}
}
else {
completion(path: urlFileOnTemp.path!, error:error)
}
})
task.resume()
}

方法加载新文件:

class func reLoadFileAsync(url: NSURL, destinationUrl: NSURL, completion:(path:String, error:NSError!) -> Void) {        
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 {
if response.statusCode == 200 {
if data!.writeToURL(destinationUrl, atomically: true) {
completion(path: destinationUrl.path!, error:error)
} else {
let error = NSError(domain:"Error saving file", code:1001, userInfo:nil)
completion(path: destinationUrl.path!, error:error)
}
}
}
}
else {
completion(path: destinationUrl.path!, error:error)
}
})
task.resume()
}

最佳答案

尝试使用NSOperationQueue并将您的操作相应地添加到队列。此线程可能对您有帮助 NSOperation and NSOperationQueue working thread vs main thread

关于swift - 如何等待 dataTaskWithRequest 完成 - Swift?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37779986/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com