LoginSignup
100
95

More than 5 years have passed since last update.

swiftでファイルの書き込み

Last updated at Posted at 2014-08-03

ドキュメントへのファイルの書き込みを行う方法

saveFile(swift-v2.1)
// ドキュメントパス
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
// 保存するもの
let fileObject = "sample"
// ファイル名
let fileName = "file.txt"
// 保存する場所
let filePath = documentsPath + fileName

// 保存処理
do {
    try fileObject.writeToFile(filePath, atomically: true, encoding: NSUTF8StringEncoding)
} catch {
   // Failed to write file
}

【追記】
ついでにmp3の保存

saveMp3File(swift-v2.1)
let fileData = NSData(contentsOfURL:NSURL(string:"url")!)
let fileName = "test.mp3"
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
fileData!.writeToFile("\(documentsPath)/\(fileName)", atomically: true)

【追記】
ディレクトリの作り方
https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/index.html

createFolder(swift-v2.1)
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let directoryName = "test"  // 作成するディレクトリ名
let createPath = documentsPath + "/" + directoryName    // 作成するディレクトリ名を含んだフルパス

do {
    try NSFileManager.defaultManager().createDirectoryAtPath(createPath, withIntermediateDirectories: true, attributes: nil)
} catch {
    // Faild to wite folder
}

100
95
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
100
95