load glb model in SCNScene swift - swift

I have a .glb file in document folder, how do I get the image and load into scnScene? like how I load a uiimage from document folder
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if let dirPath = paths.first
{
let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("Image2.png")
let image = UIImage(contentsOfFile: imageURL.path
is it possible to load .glb in SCNScene?
let scene = SCNScene(named: "latest.glb")

answering my own question, I used GLTFSceneKit
let path = FileManager.default.urls(for: .documentDirectory,
in: .userDomainMask)[0]
.appendingPathComponent("test.glb")
var scene: SCNScene
do {
let sceneSource = try GLTFSceneSource(url: path)
scene = try sceneSource.scene()
} catch {
print("\(error.localizedDescription)")
return
}

Related

loadImageFromDisk - function modyfication swift

im using the below code to load a downloaded image from disk, when the file exists I can load it as image. If it doesn't image returns as nil.
How could I modify the code to replace return nil with loading a placeholder image from my asset folder called default.png. So instead of returning nil, there is always an image return, either downloaded one that's trying to load or if it doesn't exist, my own asset image.
func loadImageFromDiskWith(fileName: String) -> UIImage? {
let documentDirectory = FileManager.SearchPathDirectory.documentDirectory
let userDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(documentDirectory, userDomainMask, true)
if let dirPath = paths.first {
let imageUrl = URL(fileURLWithPath: dirPath).appendingPathComponent(fileName)
let image = UIImage(contentsOfFile: imageUrl.path)
return image
}
return nil
}
You can do as below -
func loadImageFromDiskWith(fileName: String) -> UIImage {
let documentDirectory = FileManager.SearchPathDirectory.documentDirectory
let userDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(documentDirectory, userDomainMask, true)
var image = UIImage(named: "default") // Make sure there must be "default.png" in your main bundle.
if let dirPath = paths.first {
let imageUrl = URL(fileURLWithPath: dirPath).appendingPathComponent(fileName)
if FileManager.default.fileExists(atPath: imageUrl.path) { //Check here for file existence. It won't crash.
image = UIImage(contentsOfFile: imageUrl.path)
}
}
return image
}

How to download a file from URL using Alamofire to a custom folder

I'm using Alamofire to a download file from url, I'm getting filepath, but I'm not able to track down that filepath
let mjString = "https://wallpaperstock.net/wallpapers/thumbs1/42535.jpg"
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
print("destinationURLForFile *********** \(documentsURL)")
let fileURL = documentsURL.appendingPathComponent("42535.jpg")
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
Alamofire.download(mjString, to: destination).response { response in
// print(response)
if response.error == nil, let imagePath = response.destinationURL?.path {
let image = UIImage(contentsOfFile: imagePath)
self.mjImage.image = image
print("imagePath = \(imagePath)")
}
}
file:///var/mobile/Containers/Data/Application/4CE55219-8244-4021-B113-1BB00B8F5B10/Documents/42535.jpg
I want that file to a custom folder, if it is possible. Any help would be appreciated.
The Output what i get is,
file:///var/mobile/Containers/Data/Application/4CE55219-8244-4021-B113-1BB00B8F5B10/Documents/42535.jpg
Append Path Component
just simply change
let fileURL = documentsURL.appendingPathComponent("42535.jpg")
to
let fileURL = documentsURL.appendingPathComponent("/yourFolder/42535.jpg")
EDIT
You can load this image with this function:
func loadImageFromDocumentDirectory(nameOfImage : String, folder: String) -> UIImage {
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if let dirPath = paths.first{
let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("\(folder)/\(nameOfImage)")
if FileManager.default.fileExists(atPath: (imageURL.path)) {
if let image = UIImage(contentsOfFile: imageURL.path) {
return image
}
}
}
//Load default image if img doesnt exist.
return UIImage.init(named: "something.jpg")!
}
Just simply use it like:
imageView.image = loadImageFromDocumentDirectory(nameOfImage : "42535.jpg", folder: "yourFolder")

Getting EXC_BAD_ACCESS when using UIImage(contentsOfFile: )

I am currently using UIImage(contentsOfFile: path) if a function to return image of a file path but it is getting me EXC_BAD_ACCESS.
I have searched a lot and found some things about auto releasing and solutions in Objective-C but I couldn't find anything for Swift. What should I do in Swift?
Check for nil:
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if let dirPath = paths.first {
let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("Image2.png")
let image = UIImage(contentsOfFile: imageURL.path)
// Do whatever you want with the image
}

Get images from Document Directory not file path Swift 3

This is how I saved the images
let format = DateFormatter()
format.dateFormat="MMMM-dd-yyyy-ss"
let currentFileName = "\(format.string(from: Date())).img"
print(currentFileName)
// Save Images
let fileMgr = FileManager.default
let dirPath = fileMgr.urls(for: .documentDirectory, in: .userDomainMask)[0]
let imageFileUrl = dirPath.appendingPathComponent(currentFileName)
do {
try UIImagePNGRepresentation(returnedImages)!.write(to: imageFileUrl)
print("Image Added Successfully")
} catch {
print(error)
}
Below is code I am using to retrieve images, But I am getting the URL instead of the image file to populate tableview. Any help would be appreciated
let fileManager = FileManager.default
let imageUrl = fileManager.urls(for: .documentDirectory, in: .userDomainMask) [0].appendingPathComponent("img")
print("Your Images:\(imageUrl)")
It's simply because your image's name is invalid. Use the debugger to find the exact value of imageUrl, I bet it's something like this .../Documents/img. What you want is more like .../Documents/Sep-04-2017-12.img
You'd have to store currentFileName in the view controller so you can reference it later.
Also, your naming strategy is pretty fragile. Many images can end up sharing one name.
If you have a folder full of images, you can iterate on that folder to get back the img files:
let fileManager = FileManager.default
let documentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
let directoryContents = try! fileManager.contentsOfDirectory(at: documentDirectory, includingPropertiesForKeys: nil)
for imageURL in directoryContents where imageURL.pathExtension == "img" {
if let image = UIImage(contentsOfFile; imageURL.path) {
// now do something with your image
} else {
fatalError("Can't create image from file \(imageURL)")
}
}
Try using this
func getImage(){
let fileManager = FileManager.default
let imagePAth = (self.getDirectoryPath() as NSString).appendingPathComponent("apple.jpg") // saved image name apple.jpg
if fileManager.fileExists(atPath: imagePAth){
self.lockbackImageview.image = UIImage(contentsOfFile: imagePAth)
}else{
print("No Image")
self.lockbackImageview.image = UIImage.init(named: "1.jpg")
}
}

Delete multiple files in Document Directory

I am trying to create a function that I can delete multiple files in Document Directory with a given file Extension.
So far I have the function below but I can I complete it on older to delete the files founds?
static func searchFilesDocumentsFolder(Extension: String) {
let documentsUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
do {
let directoryUrls = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(documentsUrl, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions())
//print(directoryUrls)
let Files = directoryUrls.filter{ $0.pathExtension == Extension }.map{ $0.lastPathComponent }
print("\(Extension) FILES:\n" + Files.description)
} catch let error as NSError {
print(error.localizedDescription)
}
}
for file in Files {
try NSFileManager.defaultManager().removeItemAtPath(file)
}
For Swift 3 and Swift 4.0
let fileManager : FileManager = FileManager.default
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths : NSArray = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true) as NSArray
let documentsDirectory = paths.object(at: 0) as! NSString
print(documentsDirectory)
let contents : NSArray = try! fileManager.contentsOfDirectory(atPath: documentsDirectory as String) as NSArray
let enumerator : NSEnumerator = contents.objectEnumerator()
while let element = enumerator.nextObject() as? String
{
let fileName = element as NSString
if fileName.pathExtension == "m4a"
{
let pathOfFile = documentsDirectory.appendingPathComponent(fileName as String)
try! fileManager.removeItem(atPath: pathOfFile)
}
}