カメラで撮った写真を書き込みキーでiCloudにアップして、読み込みキーでiCloudからダウンロードして、imageに表示したい。保存形式は、ドキュメント方式です。
// // ViewController.swift // import UIKit //iCloud class ViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate { //定数 let BTN_WRITE1 = 2 //書き込み1 let BTN_READ1 = 3 //読み込み1 //変数 var _textField1: UITextField! //テキストフィールド1 var _textField3: UITextField! //テキストフィールド2 @IBOutlet weak var imageView: UIImageView! @IBAction func launchCamera(_ sender: UIBarButtonItem) { let camera = UIImagePickerControllerSourceType.camera if UIImagePickerController.isSourceTypeAvailable(camera) { let picker = UIImagePickerController() picker.sourceType = camera picker.delegate = self self.present(picker,animated: true) } } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { let image = info[UIImagePickerControllerOriginalImage] as! UIImage self.imageView.image = image UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil) self.dismiss(animated: true) } //==================== //UI //==================== //ロード完了時に呼ばれる override func viewDidLoad() { super.viewDidLoad() let dx: CGFloat = (UIScreen.main.bounds.size.width-320)/2 //ドキュメントのUIの生成 _textField1 = makeTextField(CGRect(x: dx+10, y: 140, width: 200, height: 32), text: "") self.view.addSubview(_textField1) let btnWrite1 = makeButton(CGRect(x: dx+10, y: 190, width: 190, height: 40), text: "ドキュメントの書き込み", tag: BTN_WRITE1) self.view.addSubview(btnWrite1) let btnRead1 = makeButton(CGRect(x: dx+210, y: 190, width: 90, height: 40), text: "読み込み", tag: BTN_READ1) self.view.addSubview(btnRead1) } //ボタンクリック時に呼ばれる func onClick(_ sender: UIButton) { if sender.tag == BTN_WRITE1 { DispatchQueue.global().async(execute: { let icloudURL = self.makeICloudURL("img_test") DispatchQueue.main.async(execute: { if icloudURL != nil { self.writeICloud1(icloudURL!) } else { self.showAlert("エラー", text: "iCloudのURLの取得に失敗") } }) }) } else if sender.tag == BTN_READ1 { DispatchQueue.global().async(execute: { let icloudURL = self.makeICloudURL("img_test") DispatchQueue.main.async(execute: { if icloudURL != nil { self.readICloud1(icloudURL!) } else { self.showAlert("エラー", text: "iCloudのURLの取得に失敗") } }) }) } } //テキストフィールドの初期化 func makeTextField(_ frame: CGRect, text: String) -> UITextField { let textField = UITextField() textField.frame = frame textField.text = text textField.borderStyle = UITextBorderStyle.roundedRect textField.keyboardType = UIKeyboardType.default textField.returnKeyType = UIReturnKeyType.done textField.delegate = self return textField } //テキストボタンの初期化 func makeButton(_ frame: CGRect, text: String, tag: Int) -> UIButton { let button = UIButton(type: UIButtonType.system) button.frame = frame button.setTitle(text, for: UIControlState()) button.tag = tag button.addTarget(self, action: #selector(onClick(_:)), for: UIControlEvents.touchUpInside) return button } //アラートの表示 func showAlert(_ title: String?, text: String?) { let alert = UIAlertController(title: title, message: text, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } //==================== //iCloud //==================== //iCloudのドキュメントのURLの生成(3) func makeICloudURL(_ fileName: String) -> URL? { //iCloudのディレクトリのURLの生成 let fileManager = FileManager.default let icloudURL = fileManager.url(forUbiquityContainerIdentifier: nil) if let docURL = icloudURL?.appendingPathComponent("Documents") { //ディレクトリがない時は生成 if fileManager.fileExists(atPath: docURL.path) == false { do { try fileManager.createDirectory(at: docURL, withIntermediateDirectories: true, attributes: nil) } catch _ { } } //iCloudのドキュメントのURLを返す return docURL.appendingPathComponent(fileName) } return nil } //iCloudへのドキュメントの書き込み(4) func writeICloud1(_ icloudURL: URL) { let document = ICloudDocument(fileURL: icloudURL) document.text = _textField1.text! document.save(to: icloudURL, for: UIDocumentSaveOperation.forCreating, completionHandler: {(success: Bool) in print("write document>\(success)") }) } //iCloudからのドキュメントの読み込み(5) func readICloud1(_ icloudURL: URL) { let document = ICloudDocument(fileURL: icloudURL) document.open(completionHandler: {(success: Bool) in print("read document>\(success)") self._textField1.text = document.text }) } //==================== //UITextFieldDelegate //==================== //改行ボタン押下時に呼ばれる func textFieldShouldReturn(_ sender: UITextField) -> Bool { //キーボードを閉じる self.view.endEditing(true) return true } }
// // ICloudDocument.swift // import UIKit //ドキュメント class ICloudDocument: UIDocument { var text = "" //テキスト //ドキュメント読み込み時に呼ばれる(6) override func load(fromContents contents: Any, ofType: String?) throws { self.text = (NSString(data: contents as! Data, encoding: String.Encoding.utf8.rawValue) as String?)! } //ドキュメント書き込み時に呼ばれる(7) override func contents(forType typeName: String) throws -> Any { if let value = self.text.data(using: String.Encoding.utf8) { return value } return Data() } }
宜しくお願い申し上げます。
AppDelegate.swiftもアップします。
swift3
1// 2// AppDelegate.swift 3// 4import UIKit 5 6@UIApplicationMain 7class AppDelegate: UIResponder, UIApplicationDelegate { 8 var window: UIWindow? //ウィンドウ 9 10 //アプリ起動完了時に呼ばれる 11 func application(_ application: UIApplication, 12 didFinishLaunchingWithOptions 13 launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 14 return true 15 } 16} 17
宜しくお願い申し上げます。
swift3での変更点は修正したつもりです。
let subjectTitle = ["おもち" ,"ごはん","パン"] let imgArray : NSMutableArray = [] for x in 0...subjectTitle.count { let filePath = localDocumentsPath + USDocInfo.NAME + "." + USDocInfo.ECTENSION + "." + subjectArray[x] // <- Use of unresolved identifier ‘subjectArray’ エラー let fileUrl = NSURL(fileURLWithPath:filePath) //ファイルの存在チェック isFileExists = FileManager.default.fileExists(atPath: filePath) document = USDocument(fileURL:fileUrl as URL) // if isFileExists{ // document.open(completionHandler: { (success:Bool) -> Void in if isFileExists{ let doc:USDocument = self.documentArray[self.x] as! USDocument // <- Value of type ‘ViewController’ has no member ‘documentArray’ エラー doc.open(completionHandler: { (success:Bool) -> Void in if success{ self.imgArray.addObject(self.document.img) // <- Value of type ‘ViewController’ has no member ‘imgArray’ エラー }else{ print("Documentを開けませんでした。") } }) }else{ print("Documentがありませんぬ") } }
エラーが発生します。大変申し訳ございませんが、今一度ご教授願います。