Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active May 19, 2018 10:04
Show Gist options
  • Save KentarouKanno/c12c35dbff933f659da1 to your computer and use it in GitHub Desktop.
Save KentarouKanno/c12c35dbff933f659da1 to your computer and use it in GitHub Desktop.
FileManager

FileManager

★ FileManagerオブジェクトを取得(Singleton)

let fileManager = FileManager.default

★ 指定したPathから取得したものをNSData?型で返す

// Pathを生成
let path = Bundle.main.path(forResource: "sample", ofType: "txt")

let data = FileManager.default.contents(atPath: path!)

★ SandBox内にディレクトリを作成 → 画像をダウンロード → ディレクトリに保存 → 保存している画像を取得して表示

import UIKit

class ViewController: UIViewController {
    
    @IBOutlet weak var imageView: UIImageView!
    

    override func viewDidLoad() {
        super.viewDidLoad()
        
    
        let path = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first! + "/UserPhoto"
        //=> /var/mobile/Containers/Data/Application/XXXXX-XXXX-XXXX-XXXXXX/Library/Caches/UserPhoto
        
        do {
            
            // ディレクトリが存在するかどうかの判定
            if !FileManager.default.fileExists(atPath: path) {
                
                // ディレクトリが無い場合ディレクトリを作成する
                try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: false , attributes: nil)
            }
            
        } catch {
            // エラー処理
        }
        
        let imageURL = URL(string: "https://raw.githubusercontent.com/KentarouKanno/GistImage/master/Image/swift.png")
        let data = try? Data(contentsOf: imageURL!)
        
        // 保存するパス
        let savePath = path + "/swift.png"
        
        // ファイルに保存
        FileManager.default.createFile(atPath: savePath, contents: data, attributes: nil)
        
        
        // ファイルから読み込みんで表示
        if let image = UIImage(contentsOfFile: savePath) {
            imageView.image = image
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment