テキストファイルの保存 (ファイルの出力)

swiftによるシンプルなテキストファイルの出力方法

アプリ内での処理では、ドキュメントルートパスはアプリのsandboxであるディレクトリ配下になります。 例えば以下のような場所に保存されることになります。

/Users/sample/Library/Containers/com.frog9.outputfile/Data/Documents

実際の処理は下記のコードのようになります。

// ドキュメントルートパスを取得
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)

// 配列になっているので、0番目を取得
let documentsDirectory = paths[0]

// URL型に変換
let docURL = URL(string: documentsDirectory)!

// ファイルパス(ファイル名まで記述) Stringとして定義
let filePath = docURL.absoluteString + "/sample.txt"

// 書き込むテキスト
let text = "サンプルテキスト"

// 書き込む処理
do {
   try FileManager.default.createFile(atPath: filePath,
                                   contents: text.data(using: .utf8),
                                   attributes: nil)
}
catch {
    print(error.localizedDescription)
}

書き込むテキストについては、ここに書いてもよいですし、長いテキストの場合は別の場所に定義しておいて変数を指定するのもありです。

ユーザーディレクトリへ直接保存する場合は、App Sandboxの権限で、File Access Typeを編集してから処理させるようにするとよいでしょう。


Category