E
I'll bring the code of some functions that may be useful to you ( Swift 2.3).For example, a function to record binary data during the interim directory:func writeToTempFile(fileName : String, content : NSData) {
let tempDirectoryURL = NSURL.fileURLWithPath(NSTemporaryDirectory(), isDirectory: true)
let targetURL = tempDirectoryURL.URLByAppendingPathComponent(fileName)
content.writeToURL(targetURL!, atomically: true)
}
The function is similar to that of the time directory (in addition, the function provides a picture for the available data UIImageViewand then removes it from the temporary directory:func readReadFromTempFile(fileName : String) {
let tempDirectoryURL = NSURL.fileURLWithPath(NSTemporaryDirectory(), isDirectory: true)
let targetURL = tempDirectoryURL.URLByAppendingPathComponent(fileName)
let imageData = NSData.init(contentsOfURL: targetURL!)
dispatch_async(dispatch_get_main_queue(), {
self.img.image = UIImage.init(data: imageData!)
self.removeTmpFile(fileName)
})
}
With the following function, the contents of the interim directory may be obtained:func getAllTmpFilesList() -> [String] {
do {
let allTmpFiles = try NSFileManager.defaultManager().contentsOfDirectoryAtPath(NSTemporaryDirectory())
return allTmpFiles
} catch {
}
return [String]()
}
This function removes the file from the time director:func removeTmpFile(fileName : String) {
let tempDirectoryURL = NSURL.fileURLWithPath(NSTemporaryDirectory(), isDirectory: true)
let targetURL = tempDirectoryURL.URLByAppendingPathComponent(fileName)
do {
try NSFileManager.defaultManager().removeItemAtURL(targetURL!)
} catch {
}
}
As a result, all these functions can be combined into one:func loadImageFromURLAndSaveToTmp(url:String, fileName:String) {
NSURLSession.sharedSession().dataTaskWithURL(NSURL.init(string: url)!) {
(dat:NSData?, resp:NSURLResponse?, err:NSError?) in
if (dat == nil || err != nil) {
return
}
dispatch_async(dispatch_get_main_queue(), {
//self.img.image = UIImage(data: dat!) //Уберите комментарий, если вы хотите убедиться в том, что картинка была загружена корректно
})
//Записать полученный файл во временную директорию
self.writeToTempFile(fileName, content: dat!)
//Получить список временных файлов
let allTmpFiles = self.getAllTmpFilesList()
if (allTmpFiles.count > 0) {
//Прочитать первый найденный временный файл
self.readReadFromTempFile(allTmpFiles[0])
}
}.resume()
}
And call it from your code:loadImageFromURLAndSaveToTmp("http://ВашеИзображение.png", fileName: "tmpimage.png")
With regard to the disposal of temporary files after the completion of the application, I would not advise you to do so, as temporary files are erased after the device has been launched, and that's enough. But if you want to do this, there's another function you can call it, for example. applicationWillTerminate of yours. AppDelegate (or in another method AppDelegatefunc cleanTmpDirectory() {
do {
let tmpDirectory = try NSFileManager.defaultManager().contentsOfDirectoryAtPath(NSTemporaryDirectory())
for tmpFile in tmpDirectory {
try NSFileManager.defaultManager().removeItemAtURL(NSURL.init(string: "\(NSTemporaryDirectory())\(tmpFile)")!)
}
} catch {
}
}