Swiftでファイル操作をするにはNSFileManager
を利用するのが一般的です。iOSでデータを永続化する方法は、NSUserDefaults
やCoreDataがありますが、一時的に/tmpや/Library/Cachesに保存する場合、アプリ内領域に保存するためにはNSFileManagerを使います。
NSFileManagerによるデータの永続化
iOS Storage Guidlineによると、
Only documents and other data that is user-generated, or that cannot otherwise be recreated by your application, should be stored in the /Documents directory and will be automatically backed up by iCloud.
Data that can be downloaded again or regenerated should be stored in the /Library/Caches directory. Examples of files you should put in the Caches directory include database cache files and downloadable content, such as that used by magazine, newspaper, and map applications.
Data that is used only temporarily should be stored in the /tmp directory. Although these files are not backed up to iCloud, 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.
と書いてあります。つまり、
- ユーザが生成したデータで、ダウンロードなどで再取得できないものはDocumentsディレクトリに保存する。そうすれば自動でiCloudにもバックアップされる。
- 再取得可能なもの(例:マガジン、ダウンロード可能なコンテンツ、マップなど)は、/Library/Cachesに、一時的なものは/tmpに保存する。
といったところでしょうか。
ファイル操作
移動
let manager = NSFileManager()
manager.moveItemAtPath(filePath, toPath: toPath, error: nil)
コピー
let manager = NSFileManager()
let manager.copyItemAtPath(srcPath, toPath: toPath, error: nil)
削除
let manager = NSFileManager()
manager.removeItemAtPath(filePath, error: nil)
ファイルの存在
let manager = NSFileManager()
manager.fileExistsAtPath(path)
ファイルへの書き込みや読み込みを考えると少しめんどくさいので、ディレクトリ・ファイルIOを含めて簡単に操作できるライブラリをつくりました。
Filer
Filerを利用すると、プログラマがよく知っているls
、rm
、mv
、cp
、test
、cat
などのAPIでファイル操作をすることができます。