1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Swift】2次元配列をCSVファイルに変換してUIActivityで共有したい!

Last updated at Posted at 2020-05-31

2次元配列をCSVファイルに変換してえ!

2次元配列をユーザーに渡したい時ってあるよね?
あれ、、意外とない、、?今ぱっと考えたけど全然思いつかない😇
とりまそういうこともたまにあるよね!
というわけで2次元配列をCSVに変換して、ついでにUIActivityで共有する方法までまとめてみました!!!!✨

2次元配列 → CSV

まず2次元配列とファイル名を決める

ViewController.swift
    var fruitsArray : [[String]] = [["りんご","150円"],["みかん","120円"],["バナナ","180円"]]
    var fileName = "fruits"

ボタンも作る!

ViewController.swift
    @IBAction func button(){

    }

2次元配列をCSVに変換!
Documentsの直下に配置しましょ!

ViewController.swift
func createFile(fileName : String, fileArrData : [[String]]){
        let filePath = NSHomeDirectory() + "/Documents/" + fileName + ".csv"
        print(filePath)
        var fileStrData:String = ""
        
        //StringのCSV用データを準備
        for singleArray in fileArrData{
            for singleString in singleArray{
                fileStrData += "\"" + singleString + "\""
                if singleString != singleArray[singleArray.count-1]{
                    fileStrData += ","
                }
            }
            fileStrData += "\n"
        }
        print(fileStrData)
        
        do{
            try fileStrData.write(toFile: filePath, atomically: true, encoding: String.Encoding.utf8)
            print("Success to Wite the File")
        }catch let error as NSError{
            print("Failure to Write File\n\(error)")
        }
    }

CSV → UIActivity

共有するファイルをNSURLで指定して、UIActivityを設定!

ViewController.swift
        let shareFile = NSURL(fileURLWithPath: filePath)
        
        let activityItems = [shareFile]
        
        let activityVC = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
        
        self.present(activityVC, animated: true, completion: nil)

まとめ!

ViewController.swift
import UIKit

class ViewController: UIViewController {
    
    var fruitsArray : [[String]] = [["りんご","150円"],["みかん","120円"],["バナナ","180円"]]
    var fileName = "fruits"

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    @IBAction func button(){
        createFile(fileName: fileName, fileArrData: fruitsArray)
    }
    
    func createFile(fileName : String, fileArrData : [[String]]){
        let filePath = NSHomeDirectory() + "/Documents/" + fileName + ".csv"
        print(filePath)
        var fileStrData:String = ""
        
        //StringのCSV用データを準備
        for singleArray in fileArrData{
            for singleString in singleArray{
                fileStrData += "\"" + singleString + "\""
                if singleString != singleArray[singleArray.count-1]{
                    fileStrData += ","
                }
            }
            fileStrData += "\n"
        }
        print(fileStrData)
        
        do{
            try fileStrData.write(toFile: filePath, atomically: true, encoding: String.Encoding.utf8)
            print("Success to Wite the File")
        }catch let error as NSError{
            print("Failure to Write File\n\(error)")
        }
        
        let shareFile = NSURL(fileURLWithPath: filePath)
        
        let activityItems = [shareFile]
        
        let activityVC = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
        
        self.present(activityVC, animated: true, completion: nil)
    }   
}

引用元・参考元

http://begigrammer.hatenablog.com/entry/2017/01/01/041039
https://qiita.com/nashirox/items/56894599013d712faa0a

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?