Get Document Directory Inbox file and move - ios

I have an incoming PDF attachment coming into my app. It's coming in as NSURL assigned in the AppDelegate:
func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool {
The file prints to the print log as:
Incoming File:
file:///private/var/mobile/Containers/Data/Application/65E4F19F-98DD-4A4E-8A49-E1C564D135D8/Documents/Inbox/Burrito.pdf
How can I get the file out of the DocumentDirectory Inbox folder where it is put by default for an incoming file? I tried to create a new folder called "Recipes" and then move it to this folder, but it won't I get the error:
Unable to create directory Error Domain=NSCocoaErrorDomain Code=516
"“Burrito-2.pdf” couldn’t be moved to “Documents” because an item with
the same name already exists."
UserInfo={NSSourceFilePathErrorKey=/private/var/mobile/Containers/Data/Application/D5C9B472-B880-4D68-BA0D-31BA545E2150/Documents/Inbox/Burrito.pdf,
NSUserStringVariant=(
Move ), NSDestinationFilePath=/var/mobile/Containers/Data/Application/D5C9B472-B880-4D68-BA0D-31BA545E2150/Documents/Recipes,
NSFilePath=/private/var/mobile/Containers/Data/Application/D5C9B472-B880-4D68-BA0D-31BA545E2150/Documents/Inbox/Burrito.pdf,
NSUnderlyingError=0x13912e0e0 {Error Domain=NSPOSIXErrorDomain Code=17
"File exists"}}
My code to move the file is:
// Incoming file
print("Incoming File: \(incomingFileTransfer)")
// File Manager
let filemgr = NSFileManager.defaultManager()
// Document Directory
var dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
// Documents Location
let docsDir = dirPaths[0] //as! String
print("Documents Folder: \(docsDir)")
print("------------------------")
// Create a new folder in the directory named "Recipes"
print("Creating new folder...")
let documentsPath = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0])
let newPath = documentsPath.URLByAppendingPathComponent("Recipes")
do {
try NSFileManager.defaultManager().createDirectoryAtPath(newPath.path!, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
NSLog("Unable to create directory \(error.debugDescription)")
}
print("New Path: \(newPath)")
print("------------------------")
// Moving item in folder
print("Moving PDf file to new folder...")
let startingPath = incomingFileTransfer
let endingPath = newPath
do {
try filemgr.moveItemAtURL(startingPath, toURL: endingPath)
} catch let error as NSError {
NSLog("Unable to create directory \(error.debugDescription)")
}
I'm new to Swift and have been research online and documentation on file management, but can't figure this out. I looked here but it is different and also in Objective-C; converting to Swift is hard for me. I'm using Xcode7 and Swift2, Thank you.

You get the errors when you run the application the second time and the directory is already created and the file has already been moved.
Apple highly recommends to use the URL related API of NSFileManager
First get the documents directory
// File Manager
let filemgr = NSFileManager.defaultManager()
// Document Directory
let docsDirURL = try! filemgr.URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
The try! statement is safe because the documents directory always exists.
Then check if the Recipes directory exists. If not, create it
let recipesURL = docsDirURL.URLByAppendingPathComponent("Recipes")
if !filemgr.fileExistsAtPath(recipesURL.path!) {
do {
try filemgr.createDirectoryAtURL(recipesURL, withIntermediateDirectories: false, attributes: nil)
print("Directory created at: \(recipesURL)")
} catch let error as NSError {
NSLog("Unable to create directory \(error.debugDescription)")
return
}
}
You can also check if the destination file exists
let incomingFileName = incomingFileTransfer.lastPathComponent!
let startingURL = incomingFileTransfer
let endingURL = recipesURL.URLByAppendingPathComponent(incomingFileName)
if !filemgr.fileExistsAtPath(endingURL.path!) {
do {
try filemgr.moveItemAtURL(startingURL, toURL: endingURL)
} catch let error as NSError {
NSLog("Unable to move file \(error.debugDescription)")
}
}

Related

iOS file path is changing at every launch/rerun the application

I have an issues in changing the file path at every launch of the app.
I have a file("AppConstant.json") in application bundle, and this file I need to copy into application document directory. I am successfully saving "AppConstant.json" file inside the created user folder "MyFolder" on Document directory.
But the problem is when I relaunch the application second time, it's not showing the same path. Also I am using relativepath, but still it not getting.
here is the code
// calling the directory
let stringAppConstant = copyFileFromBundleToDocumentDirectory(resourceFile: "AppConstant", resourceExtension: "json")
// saving or get exit file path
func copyFileFromBundleToDocumentDirectory(resourceFile: String, resourceExtension: String) -> String
{
var stringURLPath = "Error_URLPath"
let fileManager = FileManager.default
let docURL = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let destFolderPath = URL(string:docURL)?.appendingPathComponent("MyFolder")
let fileName = "\(resourceFile).\(resourceExtension)"
guard let newDestPath = destFolderPath, let sourcePath = Bundle.main.path(forResource: resourceFile, ofType: ".\(resourceExtension)"), let fullDestPath = NSURL(fileURLWithPath: newDestPath.absoluteString).appendingPathComponent(fileName) else {
return stringURLPath
}
if !fileManager.fileExists(atPath: newDestPath.path) {
do {
try fileManager.createDirectory(atPath: newDestPath.path,withIntermediateDirectories: true, attributes: nil)
print("Created folder successfully in :::", newDestPath.path)
} catch {
print("Error in creating folder :::",error.localizedDescription);
}
}
else {
print("Folder is already exist!")
}
if fileManager.fileExists(atPath: fullDestPath.path) {
print("File is exist in ::: \(fullDestPath.path)")
stringURLPath = fullDestPath.path
}
else {
do {
try fileManager.copyItem(atPath: sourcePath, toPath: fullDestPath.path)
print("Saved file successfully in :::", fullDestPath.path)
stringURLPath = fullDestPath.path
} catch {
print("Error in creating file ::: \(error.localizedDescription)")
}
}
return stringURLPath
}
Please help me, where I need to save the path in Sandbox. Is this right way what I implemented.
I am running in device and simulator, both path are different while relaunch
this is the path for first time launch:
/var/mobile/Containers/Data/Application/81B568A7-0932-4C3E-91EB-9DD62416DFE8/Documents/MyFolder/AppConstant.json
relaunch the application I am getting new path:
/var/mobile/Containers/Data/Application/3DAABAC3-0DF5-415B-82A5-72B204311904/Documents/MyFolder/AppConstant.json
NOTE: I create a sample project and I use this same code and it's working. But in existing project it's not working. I am using the same bundle id and profile only for both sample and project. Checked the file added reference, settings, version all are same.
Any idea?
The behavior that the container path changes periodically is normal.
These lines
let destFolderPath = URL(string:docURL)?.appendingPathComponent("MyFolder")
let fileName = "\(resourceFile).\(resourceExtension)"
guard let newDestPath = destFolderPath, let sourcePath = Bundle.main.path(forResource: resourceFile, ofType: ".\(resourceExtension)"), let fullDestPath = NSURL(fileURLWithPath: newDestPath.absoluteString).appendingPathComponent(fileName) else {
return stringURLPath
}
contain a lot of mistakes
URL(string is the wrong API for file paths, it's URL(fileURLWithPath).
The second parameter of path(forResource:ofType:) must not have a leading dot.
The API absoluteString is wrong as parameter of URL(fileURLWithPath
Not a real mistake but don't use NSURL in Swift.
It's highly recommended to use always the URL related API to concatenate paths and get the documents folder from FileManager. Further it's good practice to make the method throw the real error rather than returning a meaningless literal string. And NSSearchPathForDirectoriesInDomains is outdated and should not be used in Swift.
func copyFileFromBundleToDocumentDirectory(resourceFile: String, resourceExtension: String) throws -> URL
{
let sourceURL = Bundle.main.url(forResource: resourceFile, withExtension: resourceExtension)!
let fileManager = FileManager.default
let destFolderURL = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("MyFolder")
let fullDestURL = destFolderURL.appendingPathComponent(resourceFile).appendingPathExtension(resourceExtension)
if !fileManager.fileExists(atPath: destFolderURL.path) {
try fileManager.createDirectory(at: destFolderURL, withIntermediateDirectories: true, attributes: nil)
print("Created folder successfully in :::", destFolderURL.path)
try fileManager.copyItem(at: sourceURL, to: fullDestURL)
print("Saved file successfully in :::", fullDestURL.path)
} else {
print("Folder already exists!")
if fileManager.fileExists(atPath: fullDestURL.path) {
print("File exists in ::: \(fullDestURL.path)")
} else {
try fileManager.copyItem(at: sourceURL, to: fullDestURL)
print("Saved file successfully in :::", fullDestURL.path)
}
}
return fullDestURL
}
Edit 1:
Hi I created the new project and use the same code I posted in main, and it's working. But in the real project it not working.
Not sure what exactly going on in your project, try to debug it. It's part of development as well. :)
If you are in hurry to fix this issue in this weekend try to use the following code snippet.
// collect data from bundle
let constFileURL = Bundle.main.url(forResource: "AppConst", withExtension: "json")!
let data = try! Data(contentsOf: constFileURL)
// try to write data in document directory
do {
let constFileURL = try saveFileInDocumentDirectory(filePath: "MyFolder/AppConst.json", data: data)
// use your `constFileURL`
} catch (let error as FileOperationError) {
switch error {
case .fileAlreadyExists(let url):
let data = try! Data(contentsOf: url)
print(String(data: data, encoding: .utf8))
case .IOError(let error):
print("IO Error \(error)")
}
} catch {
print("Unknown Error \(error)")
}
// Helpers
enum FileOperationError: Error {
case fileAlreadyExists(url: URL)
case IOError(Error)
}
func saveFileInDocumentDirectory(filePath: String, data: Data) throws -> URL {
// final destination path
let destURLPath = fullURLPathOf(filePath, relativeTo: .documentDirectory)
// check for file's existance and throw error if found
guard FileManager.default.fileExists(atPath: destURLPath.path) == false else {
throw FileOperationError.fileAlreadyExists(url: destURLPath)
}
// Create Intermidiate Folders
let intermidiateDicPath = destURLPath.deletingLastPathComponent()
if FileManager.default.fileExists(atPath: intermidiateDicPath.path) == false {
do {
try FileManager.default.createDirectory(at: intermidiateDicPath, withIntermediateDirectories: true, attributes: nil)
} catch {
throw FileOperationError.IOError(error)
}
}
// File Writing
do {
try data.write(to: destURLPath, options: .atomic)
} catch {
throw FileOperationError.IOError(error)
}
return destURLPath
}
func fullURLPathOf(_ relativePath: String, relativeTo dic:FileManager.SearchPathDirectory ) -> URL {
return FileManager.default.urls(for: dic, in: .userDomainMask).first!.appendingPathComponent(relativePath)
}
Original Answer
Why don't you just return "MyFolder/\(fileName)" on successful file operation? If you need to access the path later you can always do that using FileManager APIs.
let docDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let constFilePath = docDir.appendingPathComponent("MyFolder/\(fileName)")
// Access const file data
do {
let fileData = try Data(contentsOf: constFilePath)
// Use you data for any further checking
} catch {
// Error in reading file data
print("Error in file data access : \(error)")
}

Download and view document in ios from firebase storage

I have a firebase storage link of a document which I want to download in my ios device's Document directory and then view it from there using QuickLook Module.
I am able to download document in iOS device but it is not saving with the name i am providing.
I want to create following directory structure and then need to save document in "doc" folder.
Documents/chat/doc
following code is to create "/chat/doc" inside Iphone's Document directory. Where folderName will contain "/chat/doc".
func createDocument(folderName: String ,completion: #escaping(Bool,String)->()){
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
if let documentsDirectory = path{
//
let docDirectoryPath = documentsDirectory.appending(folderName)
let fileManager = FileManager.default
if !fileManager.fileExists(atPath: docDirectoryPath) {
do {
try fileManager.createDirectory(atPath: docDirectoryPath,
withIntermediateDirectories: true,
attributes: nil)
//return path on success
completion(true,docDirectoryPath)
return
} catch {
print("Error creating folder in documents dir: \(error.localizedDescription)")
completion(false,error.localizedDescription)
return
}
}
completion(true,docDirectoryPath)
}
}
after creating folder i want to download document and need to store in newly created folder in Document Directory.
Following code will download document.
func downloadDocument(){
createDocument(folderName: "/chat/doc") { (status, path) in
if let docURL = self.documentURL{
if status{
//folder is created now download document
let docDownloadRef = Storage.storage().reference(forURL: docURL)
//get documents metadata from firebase to get document name
docDownloadRef.getMetadata { metadata, error in
if let error = error {
// Uh-oh, an error occurred!
} else {
//get document name from metadata
if let fileName = metadata?.name{
//create file system url to store document
let docsurl = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let myurl = docsurl.appendingPathComponent("chat/\(fileName)")
_ = docDownloadRef.write(toFile: myurl) { url, error in
if let error = error {
print(error.localizedDescription)
} else {
// Local file URL for document is returned
print("doc url \(url?.absoluteString)")
}
}
}
}
}
}else{
//folder is not created show document using online location
}
}
}
}
Ultimate goal is to achieve something like this "Documents/chat/doc/abc.doc"
but my code is not storing document using file name it stores like this "Documents/chat/doc" where doc is considered as a document not a folder.
Please help to let me know what I am doing wrong.
Thank you.
When you are creating url at below line, here you are missing the path for doc folder.
let myurl = docsurl.appendingPathComponent("chat/\(fileName)")
This will save to chat folder. You need to pass the same folder while creating i.e folderName: "/chat/doc" so it should be
let myurl = docsurl.appendingPathComponent("chat/doc/\(fileName)")

Copy Database after starting swift

this is my first DB Project, so i am facing some issues. Hopefully you can help me!
I am using FMDB to have access to an existing DB. When i try to execute a simpel Query like "Select * From films" it returns stuff like "no such table". I looked into the folder of the IPhone Simulator and found the DB, but it was empty. My next Step was, to include this Method:
func copyDatabaseIfNeeded() {
// Move database file from bundle to documents folder
let fileManager = FileManager.default
let documentsUrl = fileManager.urls(for: .documentDirectory,
in: .userDomainMask)
guard documentsUrl.count != 0 else {
return // Could not find documents URL
}
let finalDatabaseURL = documentsUrl.first!.appendingPathComponent("foo.db")
if !( (try? finalDatabaseURL.checkResourceIsReachable()) ?? false) {
print("DB does not exist in documents folder")
let documentsURL = Bundle.main.resourceURL?.appendingPathComponent("foo.db")
do {
try fileManager.copyItem(atPath: (documentsURL?.path)!, toPath: finalDatabaseURL.path)
} catch let error as NSError {
print("Couldn't copy file to final location! Error:\(error.description)")
}
} else {
print("Database file found at path: \(finalDatabaseURL.path)")
}
}
But this Method is not working. Im calling it from DidFinishLaunching.
This is the error message:
OverBurned/Library/Developer/CoreSimulator/Devices/B5EAE004-A036-4BD5-A692-C25EF3875D25/data/Containers/Bundle/Application/5ABA8D38-7625-4F98-83E9-4266A3E5B6B0/GameOne.app/foo.db, NSUnderlyingError=0x600000053230 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}
()
Am i using the wrong Method or is implemented wrong?
The error is clear. There is no foo.db in your app's resource bundle.
You do have lots of issues with the code you posted.
Your code to get the path to foo.db is far from ideal.
You do not properly deal with optionals.
Your variable names need to be improved. Example - the 2nd documentsURL implies it is a URL referencing the "Documents" folder. It is actually a URL to a file in the resource bundle.
There is no need for NSError.
Here is how I would write this code:
func copyDatabaseIfNeeded() {
// Move database file from bundle to documents folder
let fileManager = FileManager.default
guard let documentsUrl = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
let finalDatabaseURL = documentsUrl.appendingPathComponent("foo.db")
do {
if !fileManager.fileExists(atPath: finalDatabaseURL.path) {
print("DB does not exist in documents folder")
if let dbFilePath = Bundle.main.path(forResource: "foo", ofType: "db") {
try fileManager.copyItem(atPath: dbFilePath, toPath: finalDatabaseURL.path)
} else {
print("Uh oh - foo.db is not in the app bundle")
}
} else {
print("Database file found at path: \(finalDatabaseURL.path)")
}
} catch {
print("Unable to copy foo.db: \(error)")
}
}

Save and get image from folder inside Documents folder on iOS wrong path

On application launch I'm creating a folder inside the Documents directory, if there is none there already. This works great!
I'm downloading some images and would like to save them to use them later.
My problem is that my code seems to store the files in a documents directory that is not the same that would be on the next app launch.
I know that since iOS8 the documents directory can change from launch to launch. So I'm always retrieving a path to the Documents folder. Could someone answer me why this code can't get the path to the image correctly?
func requestImage(let url: String,let isbn: String, numberInRow: Int){
var documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
documentsPath.appendContentsOf("/bookImages")
print("Image folder path is: \(documentsPath)")
///var/mobile/Containers/Data/Application/E6B66A15-F166-46FE-A577-9B0D911F5C92/Documents/bookImages
let pathComponent = isbn.stringByAppendingString(".jpg")
print("Suggested filename: \(pathComponent)") //1234567891234.jpg
let imagePath = documentsPath.stringByAppendingString("/\(pathComponent)")
print("Image to be saved at: \(imagePath)")
// /var/mobile/Containers/Data/Application/E6B66A15-F166-46FE-A577-9B0D911F5C92/Documents/bookImages/9788202350420.jpg
if (data != nil){
NSFileManager.defaultManager().createFileAtPath(imagePath, contents: data!, attributes: ["YES" : "NSURLIsExcludedFromBackupKey"])
self.books[numberInRow].setValue(pathComponent, forKey: "imageurl")
}
}
When I would like to display these images I have this in the view controller
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
let imageFolderPath = documentsPath.stringByAppendingString("/bookImages")
if let image = bookData.valueForKey("imageurl") as? String
{
print("Imagepath: \(self.imageFolderPath)/\(image)")
// /var/mobile/Containers/Data/Application/DB1F6FE9-1071-41A6-9E87-2A3D32ECD2B9/Documents/bookImages/9788202350420.jpg
let imagePath = self.imagePath.stringByAppendingString("/\(image)")
reuseableCell.bookCover.image = UIImage(contentsOfFile: imagePath)
}
I removed a lot of code that was not relevant. Why can't the image be displayed be found?
If anyone understand the error code, it is here:
BOMStream BOMStreamWithFileAndSys(int, off_t, size_t, int, char *, BomSys *): read: No such file or directory
Edit:
On application launch I'm searching for files in the Documents/bookImages and the files are there.
let paths: NSArray = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true)
if let documentDirectory = paths.firstObject{
do{
var path = documentDirectory as! String
path.appendContentsOf("/bookImages")
let documents = try NSFileManager.defaultManager().contentsOfDirectoryAtPath(path)
for files in documents {
let urlForm = NSURL.fileURLWithPath((path) + "/" + files)
do{
try print("\(files): \(urlForm.resourceValuesForKeys([NSURLIsExcludedFromBackupKey])), with filepath: \(urlForm)")
//Prints out folder and files in the desired location
} catch let error as NSError{
print("Can't find key: \(error)")
}
}
}catch let error as NSError{
print("Can't retrieve contents: \(error)")
}
}
9788202350420.jpg: ["NSURLIsExcludedFromBackupKey": 0], with filepath: file:///var/mobile/Containers/Data/Application/DB7BA523-6F75-42CF-92E6- ED2AF171D1AA/Documents/bookImages/9788202350420.jpg
9788203193538.jpg: ["NSURLIsExcludedFromBackupKey": 0], with filepath: file:///var/mobile/Containers/Data/Application/DB7BA523-6F75-42CF-92E6-ED2AF171D1AA/Documents/bookImages/9788203193538.jpg
9788203254703.jpg: ["NSURLIsExcludedFromBackupKey": 0], with filepath: file:///var/mobile/Containers/Data/Application/DB7BA523-6F75-42CF-92E6-ED2AF171D1AA/Documents/bookImages/9788203254703.jpg
I suspect the issue is happening because you didn't created the bookImages folder in the document directory. NSFileManager won't create the directories or sub-directories automatically.
// Creating directory
do
{
try NSFileManager.defaultManager().createDirectoryAtPath(documentsPath, withIntermediateDirectories: true, attributes: nil)
}
catch let error as NSError
{
NSLog("\(error.localizedDescription)")
}
// Saving image
if (data != nil)
{
// Also it would be better to check the file creation status
let status = NSFileManager.defaultManager().createFileAtPath(imagePath, contents: data!, attributes: ["NSURLIsExcludedFromBackupKey" : "YES"])
if status
{
// File created
self.books[numberInRow].setValue(pathComponent, forKey: "imageurl")
}
else
{
// File creation failed, update your question on stack overflow, someone will surely help you to find the issue :)
}
}
You can initialize your path variables as global variables at the top of your class, then just modify them within your requestImage method.
Then when you want to retrieve those images, you can just use the same variable name to ensure that it is the exact same path.
EDIT*
I think you may need to be reading some NSData instead. You can use UIImagePNGRepresentation or UIImageJPEGRepresentation to write your file to the documents directory. I found a tutorial here

How to properly move In App Purchase download files from cache in iOS?

I am trying to set up an app with an In App Purchase that downloads content for 12 levels of a game when that respective pack is purchased.
I am stuck on how to properly move the downloaded images from the cache folder to the Documents folder. Here is my code so far:
func processDownload(sender: NSURL) {
//Convert URL to String, suitable for NSFileManager
var path:String = sender.path!
path = path.stringByAppendingPathComponent("Contents")
//Makes an NSArray with all of the downloaded files
let fileManager = NSFileManager.defaultManager()
var files: NSArray!
do {
files = try fileManager.contentsOfDirectoryAtPath(path)
} catch let err as NSError {
print("Error finding zip URL", err.localizedDescription)
}
//For each file, move it to Library
for file in files {
let pathSource: String = path.stringByAppendingPathComponent(file as! String)
let pathDestination: String = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true)[0]
//Remove destination files b/c not allowed to overwrite
do {
try fileManager.removeItemAtPath(pathDestination)
}catch let err as NSError {
print("Could not remove file", err.localizedDescription)
}
//Move file
do {
try fileManager.moveItemAtPath(pathSource, toPath: pathDestination)
print("File", file, "Moved")
}catch let err as NSError {
print("Couldn't move file", err.localizedDescription)
}
}
}
Everything actually works just fine except for the errors that are printing from the two do statements. When trying to remove any existing files of the same name in the first do block, I get the following error:
Could not remove file “Library” couldn’t be removed because you don’t have permission to access it.
This subsequently causes the next error from the next do statement to print because the original could not be removed.
Any ideas of why this is happening and how I can properly save the downloaded files elsewhere? Thanks.
I've found a proper working solution. This code will move all of the items in the downloaded zip folder to the Library directory.
func processDownload(sender: NSURL) {
//Convert URL to String, suitable for NSFileManager
var path: String = sender.path!
path = path.stringByAppendingPathComponent("Contents")
//Makes an NSArray with all of the downloaded files
let fileManager = NSFileManager.defaultManager()
var files: NSArray!
do {
files = try fileManager.contentsOfDirectoryAtPath(path)
} catch let err as NSError {
print("Error finding zip URL", err.localizedDescription)
}
//For each file, move it to Library
for file in files {
let currentPath: String = path.stringByAppendingPathComponent(file as! String)
var pathDestination: String = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true)[0]
pathDestination = pathDestination.stringByAppendingPathComponent(file as! String)
//Move file
do {
try fileManager.moveItemAtPath(currentPath, toPath: pathDestination)
print("File", file, "Moved")
}catch let err as NSError {
print("Couldn't move file", err.localizedDescription)
}
}
}
I can now make SKTextures in SpriteKit with these files like so:
var rippleTex = SKTexture(image: UIImage(contentsOfFile: NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true)[0].stringByAppendingPathComponent("P06_ripple.png"))!)

Resources