0
0

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 5 years have passed since last update.

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

Last updated at Posted at 2018-12-13

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")
}
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?