微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

swift 文件缓存

ios中也有沙盒的概念,就是本程序只能操作本程序中的沙盒部分的东西,如下图:


在哪里放APP文件呢,apple说是放在Documents

Where You Should Put Your App’s Files

To prevent the syncing and backup processes on iOS devices from taking a long time,be selective about where you place files. Apps that store large files can slow down the process of backing up to iTunes or iCloud. These apps can also consume a large amount of a user's available storage,which may encourage the user to delete the app or disable backup of that app's data to iCloud. With this in mind,you should store app data according to the following guidelines:

  • Put user data inDocuments/. User data generally includes any files you might want to expose to the user—anything you might want the user to create,import,delete or edit. For a drawing app,user data includes any graphic files the user might create. For a text editor,it includes the text files. Video and audio apps may even include files that the user has downloaded to watch or listen to later.

  • Put app-created support files in theLibrary/Application support/directory. In general,this directory includes files that the app uses to run but that should remain hidden from the user. This directory can also include data files,configuration files,templates and modified versions of resources loaded from the app bundle.

  • Remember that files inDocuments/andApplication Support/are backed up by default. You can exclude files from the backup by calling-[NSURL setResourceValue:forKey:error:]using theNSURLIsExcludedFromBackupKeykey. Any file that can be re-created or downloaded must be excluded from the backup. This is particularly important for large media files. If your application downloads video or audio files,make sure they are not included in the backup.

  • Put temporary data in thetmp/directory. Temporary data comprises any data that you do not need to persist for an extended period of time. Remember to delete those files when you are done with them so that they do not continue to consume space on the user’s device. The system will periodically purge these files when your app is not running; therefore,you cannot rely on these files persisting after your app terminates.

  • Put data cache files in theLibrary/Caches/directory. Cache data can be used for any data that needs to persist longer than temporary data,but not as long as a support file. Generally speaking,the application does not require cache data to operate properly,but it can use cache data to improve performance. Examples of cache data include (but are not limited to) database cache files and transient,downloadable content. Note that the system may delete theCaches/directory to free up disk space,so your app must be able to re-create or download these files as needed.

我在虚拟机上打印出来就是这个路径:

/Users/Ys/Library/Developer/CoreSimulator/Devices/$(code)/data/Containers/Data/Application/$(code)/Documents

翻译好麻烦,不翻译了

// refer to:

// 1https://developer.apple.com/library/prerelease/content/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/AccessingFilesandDirectories/AccessingFilesandDirectories.html#//apple_ref/doc/uid/TP40010672-CH3-SW1

// 2https://developer.apple.com/library/prerelease/content/documentation/Cocoa/Conceptual/Strings/Articles/readingFiles.html#//apple_ref/doc/uid/TP40003459-SW1

做了一点简单的实现:

protocol AbstractFile{
    func read(file :String) -> String
    func write(file :String,contents :String) -> Bool
    func del(file :String) -> Bool
    func list() -> [String]
}

//  Created by Yeshen on 15/7/9.
//  copyright (c) 2015年 Landow. All rights reserved.
//

import Foundation

class File :AbstractFile{
    let GoblePath: String = "Documents/"
    var Folder: String?
    
    init(folde: String){
        if let dirs : [String] = NSSearchPathForDirectoriesInDomains(
            NSSearchPathDirectory.DocumentDirectory,NSSearchPathDomainMask.AllDomainsMask,true) as [String] {
                if(dirs.count > 0){
                    Folder = (dirs[0] as Nsstring).stringByAppendingPathComponent(folde)
                    do {
                        try NSFileManager.defaultManager().createDirectoryAtPath(GoblePath,withIntermediateDirectories: true,attributes: nil)
                    } catch _ {
                    }
                }
        }
    }
    
    func read(file :String) -> String {
        if let path = Folder?.appendingPathComponent(file){
            if let contents = try? String(contentsOfFile: path,encoding: NSUTF8StringEncoding){
                return contents
            }
        }
        return Strings.empty
    }
    
    func write(file :String,contents :String) -> Bool{
        if let path = Folder?.appendingPathComponent(file){
            var error: NSError?
            do {
                try contents.writetoFile(path,atomically: false,encoding: NSUTF8StringEncoding)
            } catch let error1 as NSError {
                error = error1
            }
            return error == nil
        }
        return false
    }
    
    func del(file :String) -> Bool{
        if let path = Folder?.appendingPathComponent(file){
            var error: NSError?
            do {
                try NSFileManager.defaultManager().removeItemAtPath(path)
            } catch let error1 as NSError {
                error = error1
            }
            return error == nil
        }
        return false
    }
    
    func list() -> [String]{
        var files:[String] = Array<String>()
        if let path = Folder{
            if let list = try? NSFileManager.defaultManager().contentsOfDirectoryAtPath(path){
                let array = NSArray(array: list)
                for item in array{
                    files.append(item.description)
                }
            }
        }
        return files
    }
    
}

    func appendingPathComponent(path:String) -> String{
        return (self as Nsstring).stringByAppendingPathComponent(path)
    }

简单的调用测试如下:

        let file = File(folde: Consts.file.con)
        print(file.write(IO.N.CurTime,contents: Time.getNow().description))
        print(file.read(IO.N.CurTime))
        print(file.del(IO.N.CurTime))
        print(file.list())

log:

true

1466668253.0

true

[]

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐