現在は写真を撮ってimageviewに表示するに止まっています。この写真をiCloudにアップして、imageCopyにダウンロードしたいのですが、写真のアップ/ダウンの方法がわかりません。
宜しくお願いいたします。
//
// AppDelegate.swift
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow? //ウィンドウ
//アプリ起動完了時に呼ばれる
func application(_ application: UIApplication,
didFinishLaunchingWithOptions
launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
return true
}
}
コードをここに入力
//
// 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!
@IBOutlet weak var imageCopy: 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()
}
}