teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

コメントへの回答追記

2018/07/31 05:17

投稿

razuma
razuma

スコア1313

answer CHANGED
@@ -1,4 +1,68 @@
1
1
  UIDocumentInteractionControllerのインスタンスをViewControllerのプロパティとして保持しておかないとうまくいかないようです。(参考URLの内容まま文章引用)
2
2
  (遠い記憶を遡ると前に何かのケースで同じようなパターンがあったのを思い出しました、あやうくハマりかけました・・・。)
3
3
 
4
- [【Swift】UIDocumentInteractionControllerで指定したアプリが開かないとき](http://6rats.blog62.fc2.com/blog-entry-206.html)
4
+ [【Swift】UIDocumentInteractionControllerで指定したアプリが開かないとき](http://6rats.blog62.fc2.com/blog-entry-206.html)
5
+
6
+ コメントへの回答追記:
7
+ UIDocumentInteractionControllerのurlの中身がおかしいのかもしれません。
8
+ 保存できたコードを以下に貼りますので試してみてください。
9
+ ```
10
+ class ViewController: UIViewController {
11
+
12
+ private var tapData: [[String]] = [["11", "22"]]
13
+
14
+ var documentInteraction: UIDocumentInteractionController!
15
+
16
+ override func viewDidLoad() {
17
+ super.viewDidLoad()
18
+
19
+ }
20
+
21
+ @IBAction func sendFile(_ sender: Any) {
22
+ createFile(fileArrData: tapData)
23
+ }
24
+
25
+ func createFile(fileArrData : [[String]]){
26
+
27
+ var fileStrData:String = ""
28
+ let fileName = "tapdata4.7inch.csv"
29
+
30
+ //StringのCSV用データを準備
31
+ for singleArray in fileArrData{
32
+ for singleString in singleArray{
33
+ fileStrData += "\"" + singleString + "\""
34
+ if singleString != singleArray[singleArray.count-1]{
35
+ fileStrData += ","
36
+ }
37
+ }
38
+ fileStrData += "\n"
39
+ }
40
+ print(fileStrData)
41
+
42
+ // DocumentディレクトリのfileURLを取得
43
+ let documentDirectoryFileURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last!
44
+
45
+ // ディレクトリのパスにファイル名をつなげてファイルのフルパスを作る
46
+ let FilePath = documentDirectoryFileURL.appendingPathComponent(fileName)
47
+
48
+ print("書き込むファイルのパス: (FilePath)")
49
+
50
+ do {
51
+ try fileStrData.write(to: FilePath, atomically: true, encoding: String.Encoding.utf8)
52
+ } catch let error as NSError {
53
+ print("failed to write: (error)")
54
+ }
55
+
56
+ documentInteraction = UIDocumentInteractionController()
57
+ documentInteraction.url = FilePath
58
+
59
+ if !(documentInteraction?.presentOpenInMenu(from: self.view.frame, in: self.view, animated: true))!
60
+ {
61
+ // 送信できるアプリが見つからなかった時の処理
62
+ let alert = UIAlertController(title: "送信失敗", message: "ファイルを送れるアプリが見つかりません", preferredStyle: .alert)
63
+ alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
64
+ self.present(alert, animated: true, completion: nil)
65
+ }
66
+ }
67
+ }
68
+ ```