I'm trying to set a JPG or PNG image in my IOS documents folder. I've been trying to use the initializers "contentsOfFile" and "named." Here's my script at the moment:
let myPng = filterd.first
print (myPng!) //the file path and name of the png
let nameIndex = myPng?.characters.index(of: "V")
let nameWithPng = String(myPng!.characters.suffix(from: nameIndex!)) //returns the name of the file with the extension
print (nameWithPng)
let pngIndex = nameWithPng.characters.index(of: ".")
let nameWOPng = String(nameWithPng.characters.prefix(upTo: pngIndex!)) //returns only the name of the file, no extension
print (nameWOPng)
let photo = UIImage.init(named: nameWOPng)
print (photo)
firstFrame.image = photo
Photo returns nil. The file it's trying to make a UIImage out of is a test PNG on my test phone. When I've tried 'contentsOfFile" I replace "nameWOPng" constant with "myPng." What am I doing wrong?
You don't use UIImage(named:) for this, because that's for loading assets (from your app bundle).
Don't use UIImage(contentsOfFile:) either, because it's a path-based API. There's no URL-based equivalent, which is an Apple clue that should be doing something else. In this case, use Data(contentsOf:options:) with a URL, which properly throws file system errors. Then use UIImage(data:) to convert the raw data to an image.
Generally, in modern iOS apps, you should avoid path-based APIs. If you use them, avoid using substrings to locate file system parts (such as file names and extensions). There are specific String methods for appending or removing file names and extensions.
Assuming "myPng" is a proper path to the file, URL(fileURLWithPath:myPng) will give you a URL for the file.