25

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 imageUrl2 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.

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
veiko herne
  • 261
  • 1
  • 3
  • 7
  • Where does `imageUrl2` come from? And what does `asURL()`? And you might print the actual caught **error** rather than a generic string. – vadian Mar 23 '17 at 17:12
  • @vadian expresses some good questions. One more: *...experiences loading local data...* - local to what? Your project, a Framework, the OS file system...??? I'll add one more option looking at your URL - is this in the Photos library? Trust me, there are several places, each with a "best" way to get at them. –  Mar 23 '17 at 17:22
  • Possible duplicate of [how to load image from local path ios swift (by path)](http://stackoverflow.com/questions/37574689/how-to-load-image-from-local-path-ios-swift-by-path) – Nazmul Hasan Mar 23 '17 at 17:27
  • The answer is using NSData which was OK in Swift 2. Swift 3 demands me to use Data instead of NSData.. – veiko herne Mar 23 '17 at 17:48
  • to @vadian imageUrl is the string for the file and as Data object needs URL, I have to convert String to Url by using .asURL(). It's not a photo library, it's a image I store in app documents directory. Obviously I'm using the latest xCode to have Swift 3. – veiko herne Mar 23 '17 at 18:16
  • I know what it's supposed to be, but the the way to get the string could be wrong and the way to create the URL could also be wrong. Once again, print the error in the catch clause. The question is too broad. – vadian Mar 23 '17 at 22:20
  • to @vadian: The error could be empty, but I have seen "Invalid Url" as well. That's why I posted my Url String. – veiko herne Mar 24 '17 at 12:02
  • This is at least a hint. Then most likely the `asURL()` function creates an invalid URL – as suspected in very my first comment. Check that. – vadian Mar 24 '17 at 14:36

3 Answers3

30

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

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! (Further sample code.)

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
Dharmesh Siddhpura
  • 1,610
  • 12
  • 22
  • 1
    Using contentsOfFile will give me compile error: "Argument labels '(contentsOfFile:)' do not match any available overloads" – veiko herne Mar 23 '17 at 18:24
  • Use this method: Data(contentsOf: , options: ) – Dharmesh Siddhpura Mar 23 '17 at 18:29
  • Tried options: Data.ReadingOptions.uncachedRead or Data.ReadingOptions.mappedRead without any luck. Still same. – veiko herne Mar 23 '17 at 18:43
  • I have updated my answer for reading an image from document directory. I am using this in my current project. Hope this would be helpful now. – Dharmesh Siddhpura Mar 23 '17 at 19:48
  • 1
    Thanks Dharmesh. I'm reading data in a way you describe, but can't get it work. Can you confirm, that it works for you? What options do you use? Can you give me your sample URL? – veiko herne Mar 24 '17 at 10:48
  • I am using "UIImage(contentsOfFile: )" for reading image from my app's document directory which was downloaded earlier and saved in dir. And this works for me. – Dharmesh Siddhpura Mar 27 '17 at 15:15
18

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
    }
}
Lexi
  • 215
  • 3
  • 8
11

Swift 5 version.

func loadFileFromLocalPath(_ localFilePath: String) ->Data? {
   return try? Data(contentsOf: URL(fileURLWithPath: localFilePath))
}
SafeFastExpressive
  • 3,637
  • 2
  • 32
  • 39