如何等待完成dataTaskWithRequest - Swift?

时间:2016-06-12 23:10:41

标签: swift nsurlsession

如果需要,我尝试比较文件(磁贴)替换手机新文件中的旧文件。但是func returnPathFile中的pathDir被分配了对文件的引用,而没有等待检查和下载新文件。如何等到新文件的测试和加载(如果需要)完成后呢?

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()
}

1 个答案:

答案 0 :(得分:0)

尝试使用NSOperationQueue并相应地将您的操作添加到queue。此主题可能会帮助您NSOperation and NSOperationQueue working thread vs main thread