Skip to content

Instantly share code, notes, and snippets.

@uruly
Last active April 10, 2018 06:50
Show Gist options
  • Save uruly/6bf7b906d6f598fa2614930e01a1dd22 to your computer and use it in GitHub Desktop.
Save uruly/6bf7b906d6f598fa2614930e01a1dd22 to your computer and use it in GitHub Desktop.
import UIKit
class DataManager{
//Documentに関する情報
struct MyDocInfo{
static let NAME = "document"
static let ECTENSION = "doc"
static var LOCAL_DOCUMENTS_PATH:String? = nil
}
//アプリのサンドボックスのパスを格納する変数
var localDocumentsPath:String{
if let dir = MyDocInfo.LOCAL_DOCUMENTS_PATH{
return dir
}else {
let dir = NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask, true)[0] + "/"
MyDocInfo.LOCAL_DOCUMENTS_PATH = dir
return dir
}
}
func openDocument(completion:@escaping (MyDocument)->()){
let filePath = localDocumentsPath + MyDocInfo.NAME + "." + MyDocInfo.ECTENSION
let fileURL = URL(fileURLWithPath:filePath)
//ファイルの存在チェック
let isFileExists = FileManager.default.fileExists(atPath: filePath)
let document = MyDocument(fileURL:fileURL)
if isFileExists{
document.open { (isSuccess) in
if isSuccess{
print("Documentを開きましたtext\(document.text!):\(document.date!)")
completion(document)
}else{
print("Documentを開けませんでした。")
}
}
}else {
print("ファイルがありません")
}
}
func saveDocument(text:String,date:Date,completion:@escaping ()->()) {
let filePath = localDocumentsPath + MyDocInfo.NAME + "." + MyDocInfo.ECTENSION
let fileURL = URL(fileURLWithPath:filePath)
let document = MyDocument(fileURL:fileURL)
//ここで保存したい内容を書く
document.text = text
document.date = date
document.save(to: fileURL, for: .forCreating) { (isSuccess) in
if isSuccess{
print("Documentを保存しました。text\(document.text)")
completion()
}else{
print("Documentを保存できませんでした")
}
}
}
func saveDocument(text:String,date:Date,img:UIImage,images:[UIImage],completion:@escaping ()->() ){
let filePath = localDocumentsPath + MyDocInfo.NAME + "." + MyDocInfo.ECTENSION
let fileURL = URL(fileURLWithPath:filePath)
let document = MyDocument(fileURL:fileURL)
//ここで保存したい内容を書く
document.text = text
document.date = date
document.img = img
document.images = images
document.save(to: fileURL, for: .forCreating) { (isSuccess) in
if isSuccess{
print("Documentを保存しました。text\(document.text)")
completion()
}else{
print("Documentを保存できませんでした")
}
}
}
}
import UIKit
class MyDocument: UIDocument {
//各データに対応したStatic定数を宣言
struct Keys{
static let IMG = "MyDocument.img"
static let TEXT = "MyDocument.text"
static let DATE = "MyDocument.date"
static let IMAGES = "MyDocument.imgarray"
}
//記録したい内容を保持するメンバ変数を宣言
var img:UIImage!
var text:String!
var date:Date!
var images:[UIImage]!
//上記の内容をひとまとめにするNSFileWrapper
var fileWrapper:FileWrapper?
override func load(fromContents contents: Any, ofType typeName: String?) throws {
//引数で渡されたcontentsをダウンキャストし、fileWrapperにつめる。
if let fileWrapper = contents as? FileWrapper {
self.fileWrapper = fileWrapper
let dict = fileWrapper.fileWrappers
if let fw = dict![Keys.IMG] as FileWrapper?,
let contents = fw.regularFileContents{
self.img = UIImage(data:contents)
}
if let fw = dict![Keys.TEXT] as FileWrapper?,
let contents = fw.regularFileContents{
self.text = String(data:contents,encoding:String.Encoding(rawValue: String.Encoding.utf8.rawValue))
}
if let fw = dict![Keys.DATE] as FileWrapper?,
let contents = fw.regularFileContents{
self.date = NSKeyedUnarchiver.unarchiveObject(with: contents) as! Date
}
if let fw = dict![Keys.IMAGES] as FileWrapper?,let contents = fw.regularFileContents{
self.images = NSKeyedUnarchiver.unarchiveObject(with: contents) as! [UIImage]
}
}
}
override func contents(forType typeName: String) throws -> Any {
if self.fileWrapper == nil{
//空のディクショナリを渡す
self.fileWrapper = FileWrapper(directoryWithFileWrappers: [:])
}
if let text = self.text,
let data = text.data(using: String.Encoding.utf8){
let fw = FileWrapper(regularFileWithContents: data)
fw.preferredFilename = Keys.TEXT
self.fileWrapper?.addFileWrapper(fw)
}
if let img = self.img,
let data = UIImageJPEGRepresentation(img, 1.0){
let fw = FileWrapper(regularFileWithContents: data)
fw.preferredFilename = Keys.IMG
self.fileWrapper?.addFileWrapper(fw)
}
if let date = self.date{
let data = NSKeyedArchiver.archivedData(withRootObject: date)
let fw = FileWrapper(regularFileWithContents: data)
fw.preferredFilename = Keys.DATE
self.fileWrapper?.addFileWrapper(fw)
}
if let images = self.images{
let data = NSKeyedArchiver.archivedData(withRootObject: images)
let fw = FileWrapper(regularFileWithContents:data)
fw.preferredFilename = Keys.IMAGES
self.fileWrapper?.addFileWrapper(fw)
}
return self.fileWrapper!
}
}
import UIKit
class ViewController:UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let dataManager = DataManager()
//Documentが保存されていれば表示
dataManager.openDocument { (doc) in
print(doc.text)
}
}
@IBAction func btnTapped(_ sender: UIButton) {
let dataManager = DataManager()
//適当にボタンを押した時に保存
dataManager.saveDocument(text: "hogehoge", date: Date()) {
print("save完了!")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment