2
5

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] ログをファイルに保存する

Last updated at Posted at 2020-04-16

ファイルに保存する

位置情報のログを取る場合など、ログをファイルに保存したい

こんな感じでファイルに文字列を保存するLogクラス
(例:位置情報ログをCSVで保存する)

// 1
Log.write("timestamp,latitude,longitude,altitude\n")

// 2
Log.write("""
        \(formatDate(date: location.timestamp)),\
        \(location.coordinate.latitude),\
        \(location.coordinate.longitude),\
        \(location.altitude)\n
        """)
Log.swift

import Foundation

class Log {
    private static let file = "log.csv"

    static func write(_ log: String) {
        writeToFile(file: file, text: log)
    }

    private static func writeToFile(file: String, text: String) {
        guard let documentPath = 
            FileManager.default.urls(for: .documentDirectory,
                                     in: .userDomainMask).first else { return }

        let path = documentPath.appendingPathComponent(file)
        _ = appendText(fileURL: path, text: text)
    }

    private static func appendText(fileURL: URL, text: String) -> Bool {
        guard let stream = OutputStream(url: fileURL, append: true) else { return false }
        stream.open()

        defer { stream.close() }

        guard let data = text.data(using: .utf8) else { return false }

        let result = data.withUnsafeBytes {
            stream.write($0, maxLength: data.count)
        }

        return (result > 0)
    }
}

ファイルを抜き出す

Info.plist
Application supports iTunes file sharingを追加し、値をYESにする
Screen Shot 2020-04-17 at 1.20.26.png

MacとiPhoneを接続すると、Finder(or iTunes)にて、ファイルを抜き出すことができる

2
5
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
2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?