iOS
Swift
swift4

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

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