Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loading data object from local file in Swift 3

Tags:

ios

swift

swift3

I'm struggling to get an image file loaded in Swift 3. Here is the code:

do {
    let imageData = try Data(contentsOf: imageUrl2.asURL()) 
} catch { 
    print ("loading image file error") 
}

And the current Url String is:

file:///Users/veikoherne/Library/Developer/CoreSimulator/Devices/889A08D5-B8CC-458C-99FF-643A4BA1A806/data/Containers/Data/Application/F64ED326-7894-4EE7-AA3B-B1BB10DF8259/Documents/img2017-03-23 17:39:24.jpg

and obviously I have checked that this file exists and is valid image. It always ends up telling me "loading image file error". Anyone have experiences loading local data in Swift 3?

The answer mentioned was using NSData object and probably Swift 2. Current Swift 3 refuses to bridge NSData to Data, that's why I have to use Data.

like image 954
veiko herne Avatar asked Mar 23 '17 17:03

veiko herne


Video Answer


2 Answers

Loading data from local file you should use "contentsOfFile:" method.

Reference link: https://www.hackingwithswift.com/example-code/strings/how-to-load-a-string-from-a-file-in-your-bundle

So in case of reading data you can use:

Data(contentsOf: <URL>, options: <Data.ReadingOptions>)

Reading a plain text as a String, use:

String(contentsOfFile: <LocalFileDirPath>)

Reading an image from document directory, use:

UIImage(contentsOfFile: <LocalFileDirPath>)

Hope this would be helpful!

like image 52
Dharmesh Siddhpura Avatar answered Sep 30 '22 17:09

Dharmesh Siddhpura


I experienced the same issue when trying to retrieve a file that I just downloaded. If you have saved a file from some url like I did, this should work:

let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
let localUrl = documentDirectory.appendingPathComponent("somefile.txt")

if FileManager.default.fileExists(atPath: localUrl.path){
    if let cert = NSData(contentsOfFile: localUrl.path) {
        return cert as Data
    }
}
like image 44
Lexi Avatar answered Sep 30 '22 17:09

Lexi