Help us understand the problem. What is going on with this article?

iOS Read and write typed data arrays to/from bundle/local accessible storage (Swift 4.0+)

More than 1 year has passed since last update.

Read from bundle or local storage

Get url of Bundle

let url = Bundle.main.url(forResource: filename, withExtension: "")

Get path of local accessible storage

let path = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0] as String
let url = NSURL(fileURLWithPath: path) as URL

Get data from url

do {
    let data = try Data(contentsOf: url)
}
catch {
    print("failed to read", url)
}

Get string stored as Data

let str = String(data: data, encoding: String.Encoding.utf8)

Get typed array from data with a generic

static func dataToType<T>(data: Data) -> [T] {
    return data.withUnsafeBytes({ (pointer: UnsafePointer<T>) -> [T] in
        let buffer = UnsafeBufferPointer(start: pointer, count: data.count / MemoryLayout<T>.size)            
        return Array<T>(buffer)
    })
}

Get string array from data

do {
    let arrays = try JSONSerialization.jsonObject(with: data, options: []) as? [String]
} catch {
    print("failed to parse string array")
}

Write to local storage

Get data from typed value array

static func typeToData<T>(array: [T]) -> Data {
    return array.withUnsafeBufferPointer({ (pointer: UnsafeBufferPointer<T>) -> Data in
       return Data(buffer: pointer)
    })
}

Write data to url

do {
    try data.write(to: url, options: .atomic)
}
catch {
    print("failed to write")
}

Write array of strings as Data

do {
    let data = try JSONSerialization.data(withJSONObject: strings, options: [])
    try data.write(to: url, options: .atomic)
}
catch {
    print("failed to write string array")
}
cayozin
iOS/Android development (Swift/C++/Java/Kotlin/XML/Javascript), backend (php/mySQL) and Machine Learning (Python/Scala)
ayudante
いつもユーザー中心で技術者とコンサルタントがとことん考え抜く それがアユダンテです
https://ayudante.jp/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした