Skip to content

Instantly share code, notes, and snippets.

@c-bata
Last active January 10, 2016 05:40
Show Gist options
  • Save c-bata/07fe214129eae732eef8 to your computer and use it in GitHub Desktop.
Save c-bata/07fe214129eae732eef8 to your computer and use it in GitHub Desktop.
Swift コードスニペット

現在時刻の取得

let dateFormatter: NSDateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "ja_JP")
dateFormatter.timeZone = NSTimeZone.systemTimeZone()
dateFormatter.dateFormat = "yyyy-MM-dd_HH-mm-ss"

dateFormatter.stringFromDate(NSDate())  # 2016-01-01_00-00-00 のように文字列がとれる

Documents Directoryの操作

書き込み

保存したファイルは、iTunesで端末を選択してAppのところから見れる。

let text = "hogehoge\n"
let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
let filePath = documentDirectory + "/" + "filename.dat"

do {
    try text.writeToFile(filePath, atomically: false, encoding: NSUTF8StringEncoding)
} catch _ {
    print("ファイル書き込み中に例外が発生しました")
}

ファイル一覧の取得

let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
let manager = NSFileManager()
do {
    let files = try manager.contentsOfDirectoryAtPath(documentDirectory)
    for file_name in files {
        print(file_name)
    }
} catch _ {
}

Documents Directory内のファイルを全削除

let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
let manager = NSFileManager()
do {
    let files = try manager.contentsOfDirectoryAtPath(documentDirectory)
    for file_name in files {
        try manager.removeItemAtPath(documentDirectory + "/" + file_name)
    }
} catch _ {
}

アラートダイアログ

UIAlertViewControllerを使う

let saveAlert: UIAlertController = UIAlertController(title: "Save", message: "Do you want to save it?", preferredStyle: .Alert)
let yesAction: UIAlertAction = UIAlertAction(title: "Yes", style: UIAlertActionStyle.Default, handler: { (action:UIAlertAction!) -> Void in
    print("Yes Clicked!")
})
let noAction: UIAlertAction = UIAlertAction(title: "No", style: UIAlertActionStyle.Default, handler: { (action:UIAlertAction!) -> Void in
    print("No Clicked!") 
})
saveAlert.addAction(noAction)
saveAlert.addAction(yesAction)

presentViewController(saveAlert, animated: true, completion: nil)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment