書籍を購入してリストを入力したのですが、エラーが発生して動作しません。
大変申し訳ありませんが、どこが悪いのかご教授願います。
swift3
1// 2// ViewController.swift 3// ICloudDemo 4// 5import UIKit 6 7class ViewController: UIViewController{ 8 9 // Documentに関する情報 10 struct USDocInfo { 11 static let NAME = "usdoc_test" 12 static let EXTENSION = "us" 13 static var LOCAL_DOCUMENTS_PATH:String? = nil 14 static var ICLOUD_CONTAINER_PATH:String? = nil 15 } 16 17 // アプリのサンドボックスのパスを格納する変数 18 var localDocumentsPath: String { 19 if let dir = USDocInfo.LOCAL_DOCUMENTS_PATH { 20 return dir 21 } else { 22 let dir = NSSearchPathForDirectoriesInDomains( 23 .documentDirectory, 24 .userDomainMask, 25 true)[0] + "/" 26 27 USDocInfo.LOCAL_DOCUMENTS_PATH = dir 28 return dir 29 } 30 } 31 32 var iCloudContainerPath: String? { 33 return USDocInfo.ICLOUD_CONTAINER_PATH 34 } 35 36 var document: USDocument! 37 var documentURL: URL { return document.fileURL } 38 var isFileExists = false 39 40 let query = NSMetadataQuery() 41 42 43 override func viewDidLoad() { 44 super.viewDidLoad() 45 // Do any additional setup after loading the view, typically from a nib. 46 47 query.searchScopes = [ 48 NSMetadataQueryUbiquitousDocumentsScope, 49 NSMetadataQueryAccessibleUbiquitousExternalDocumentsScope] 50 51 query.predicate = NSPredicate(format: "%K LIKE '*'", NSMetadataItemFSNameKey) 52 53 DispatchQueue.global(qos: .default).async(execute: { 54 if let url = FileManager.default.url(forUbiquityContainerIdentifier: nil) { 55 print("iCloudコンテナのURL:\(url)") 56 USDocInfo.ICLOUD_CONTAINER_PATH = url.path + "/Documents/" 57 self.iCloudContainerDidInitialize() 58 } 59 }) 60 } 61 62 63 override func viewWillAppear(_ animated: Bool) { 64 super.viewWillAppear(animated) 65 NotificationCenter.default.addObserver(self, selector: #selector(ViewController.iCloudDocumentDidChange(_:)), name: NSNotification.Name.UIDocumentStateChanged, object: self.document) 66 } 67 68 69 override func viewWillDisappear(_ animated: Bool) { 70 super.viewWillDisappear(animated) 71 NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIDocumentStateChanged, object: self.document) 72 } 73 74 75 override func didReceiveMemoryWarning() { 76 super.didReceiveMemoryWarning() 77 // Dispose of any resources that can be recreated. 78 } 79 80 81 func iCloudContainerDidInitialize() { 82 let filePath = iCloudContainerPath! + USDocInfo.NAME + "." + USDocInfo.EXTENSION 83 let fileUrl = URL(fileURLWithPath: filePath) 84 createDocument(fileUrl) 85 } 86 87 88 func createDocument(_ fileUrl: URL?) { 89 90 let localFilePath = localDocumentsPath + USDocInfo.NAME + "." + USDocInfo.EXTENSION 91 let localFileUrl = URL(fileURLWithPath : localFilePath) 92 let doc = USDocument(fileURL : localFileUrl) 93 94 doc.place = "自宅" 95print("自宅") 96 doc.save(to: localFileUrl, for: .forCreating, completionHandler: { (success:Bool) in 97 // "fatal error: unexpectedly found nil while unwrapping an Optional value" 98print("pass") 99 if success { 100 print("Documentデータを保存しました。") 101 102 } else { 103 print("Documentデータを保存できませんでした。") 104 } 105 106 }) 107 108 } 109 110 111 func iCloudDocumentDidChange(_ notification: Notification) { 112 if self.document.documentState.contains(.inConflict){ 113 do{ 114 try NSFileVersion.removeOtherVersionsOfItem(at: self.document.fileURL) 115 } catch let error { 116 print("エラー内容:\(error)") 117 } 118 if let conflicts = NSFileVersion.unresolvedConflictVersionsOfItem(at: self.document.fileURL){ 119 for fileVersion in conflicts { 120 fileVersion.isResolved = true 121 } 122 } 123 } 124 } 125}
もう一つのファイルです。
swift3
1// 2// USDocument.swift 3// ICloudDemo 4// 5 6import UIKit 7 8class USDocument: UIDocument { 9 10 // Static定数の宣言 11 struct USFileWrapperKeys { 12 static let IMG = "USDocuemnt.img" 13 static let PLACE = "USDocument.place" 14 static let DATE = "USDocument.date" 15 static let DETAIL = "USDocument.detail" 16 } 17 18 // 記録したい内容を保持するメンバ変数を宣言します 19 var img:UIImage? 20 var place:String? 21 var date:Date? 22 var detail:String? 23 24 25 26 // 上記、Documentの内容をひとまとめにパッケージするNSFileWrapperもメンバ変数として宣言します 27 var fileWrapper:FileWrapper? 28 29 // MARK: - 書き込み用のメソッド 30 31 override func contents(forType typeName: String) throws -> Any { 32 33 if self.fileWrapper == nil { 34 // 空のDictonaryを渡している 35 self.fileWrapper = FileWrapper(directoryWithFileWrappers:[:]) 36 } 37 38 if let place = self.place 39 , let data = place.data(using: String.Encoding.utf8) 40 { 41 let fw = FileWrapper(regularFileWithContents:data) 42 fw.preferredFilename = USFileWrapperKeys.PLACE 43 self.fileWrapper?.addFileWrapper(fw) 44 } 45 46 if let img = self.img 47 , let data = UIImageJPEGRepresentation(img, 1.0) 48 { 49 let fw = FileWrapper(regularFileWithContents:data) 50 fw.preferredFilename = USFileWrapperKeys.IMG 51 self.fileWrapper?.addFileWrapper(fw) 52 } 53 54 if let date = self.date { 55 let data = NSKeyedArchiver.archivedData(withRootObject: date) 56 let fw = FileWrapper(regularFileWithContents:data) 57 fw.preferredFilename = USFileWrapperKeys.DATE 58 self.fileWrapper?.addFileWrapper(fw) 59 } 60 61 if let detail = self.detail 62 , let data = detail.data(using: String.Encoding.utf8) 63 { 64 let fw = FileWrapper(regularFileWithContents:data) 65 fw.preferredFilename = USFileWrapperKeys.DETAIL 66 self.fileWrapper?.addFileWrapper(fw) 67 } 68 69 return self.fileWrapper as Any 70 } 71 72}
回答1件
あなたの回答
tips
プレビュー