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

标签 swift nsurlsession

如有必要,我会尝试比较文件(图 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/

相关文章:

ios - 为什么uploadTaskWithRequest :fromData: need a data argument?

ios - 删除索引路径错误处的行

ios - 我想在单个 View Controller 中使用两个 TableView 。但最终的返回类型应该是什么?

arrays - Swift3 错误 : Binary operator '<' cannot be applied to two 'ArraySlice<Int>' operands

iOS 后台上传 - 如果应用程序崩溃,如何验证收到的响应?

ios - URLSession 下载任务比互联网连接慢得多

swift - 我怎么知道 map View 上是否已经有注释

ios - 如何保护 iOS 应用程序中的 awsconfiguration.json 数据详细信息?

ios - 从 URL 和缓存中一张一张地加载和显示图像

ios - swift 错误 : ambiguous reference to member 'jsonObject(with:options:)