Get file path from NSBundle in Swift - swift

I have a file stored in:
/var/mobile/Containers/Data/Application/083EA15E7/Documents/myFile.zip
It got there after I downloaded it from a server.
If I know the file name is myFile.zip, how can I find it with NSBundle?
Like this:
if let URL = NSBundle.mainBundle().URLForResource("myFile", withExtension: "zip") {
// do stuff
}
currently this returns false, not sure how I can specify the whole path. Any ideas?

This item is not in your bundle, an item in your bundle is something that you add before compiling, such as assets, fonts etc.
iOS provides each app with a sandbox. In that sandbox, the Documents folder exists. To access files from the Documents folder try this:
let documentsURL = NSURL(
fileURLWithPath: NSSearchPathForDirectoriesInDomains(
.DocumentDirectory, .UserDomainMask, true).first!,
isDirectory: true
)
To get the file, you will need to get its path and append it to the documents path like so.
let URLToMyFile = documentsURL.URLByAppendingPathComponent("MyFile.zip")
To get the path as a string you can access the path property of the URL.
print(URLToMyPath.path!)
That will print out the path of your downloaded resource.

Tested on: xCode 8.3.2 & Swift 3.1
First drag your file (JPG, MP3, ZIP) inside your project folder and make sure Copy items if needed is checked and project/app is selected in Add to targets
Inside relevant ViewController
let fileName = "fileName"
let fileType = "fileType"
if let filePath = Bundle.main.path(forResource: fileName, ofType: fileType) {
print(filePath)
}
If you need to get the file URL you can use NSBundle method
if let fileURL = Bundle.main.url(forResource: fileName, withExtension: fileType) {
print(fileURL)
}
Also NSBundle method pathForResource has an initializer that you can specify in which directory your files are located like:
if let filePath = Bundle.main.path(forResource: fileName, ofType: fileType, inDirectory: "filesSubDirectory") {
print(filePath)
}
And for getting file URL:
if let fileURL = Bundle.main.url(forResource: fileName, withExtension: fileType, subdirectory: "filesSubDirectory") {
print(fileURL)
}

run time created file are stored in Document directory not in NSBundle. NSBundle stores the files like System file you put in your Xcode project while your developing
Here is the example
This code is fully tested on Swift 2.0
let file = "myFile.zip"
if let dir : NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
//path will be stored here
let sPath = dir.stringByAppendingPathComponent(file);
print(sPath) // printing the file path
}

Related

How to save video data to document directory in swift?

I want to save video data to document directory.
I know how to create document directory my folder.
But how to save data that document directory??
let fileManager = FileManager.default
if let tDocumentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first {
let filePath = tDocumentDirectory.appendingPathComponent("\(FOLDER_NAME)")
if !fileManager.fileExists(atPath: filePath.path) {
do {
try fileManager.createDirectory(atPath: filePath.path, withIntermediateDirectories: true, attributes: nil)
} catch {
print("Couldn't create document directory")
}
}
print("Document directory is \(filePath)")
}
Now, I have (FOLDER_NAME) folder. But How to save video data to (FOLDER_NAME) folder??
And How to I get saved video file path?
I apologize for my stupidity.
In your Info.plist, add the following permissions:
Supports opening documents in place: YES
Application supports iTunes file sharing: YES
let videoFilename = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] + "/" + getFileName() //return your filename from the getFileName function
videoNSData.write(toFile: videoFilename, atomically: true)
Then, inside Files, you can get a folder named with your app name, where you can access your saved video file (with the specified filename).

How to read data from a file in the App's bundle I macOS?

I'm trying to read the data from a txt file on macOS. I use String(contentsOf:) and Bundle.main.path(forResource:) like I would on iOS. However, this doesn't work on macOS. I have tried several solutions from other posts but because of macOS they don't seem to work.
Thanks in advance.
Edit:
My code:
let path = Bundle.main.path(forResource: "file", ofType: "txt")! // no error
let url = URL(string: path)! // no error
let contents: String
do {
contents = try String(contentsOf: url)
} catch {
print(error) // Error Domain=NSCocoaErrorDomain Code=262 "The file couldn’t be opened because the specified URL type isn’t supported."
contents = "ERROR"
}
print(contents)
I can save the data to a folder on disk, but I want to ship this file with my app.
URL(string is the wrong API. It's only for URL strings starting with a scheme (http://, file://)
For file system paths you have to use URL(fileURLWithPath.
But in this situation there is a much better way
Replace
let path = Bundle.main.path(forResource: "file", ofType: "txt")!
let url = URL(string: path)! // no error
with
let url = Bundle.main.url(forResource: "file", withExtension: "txt")

In Swift 3, how to display images from link to local file directory in tableviewcell

I want to save images in local file not on server and displays those images in UItableviewcell via link to that file\folder.
I am not sure what path i used to save in database. I am saving imagefolder in desktop.But that path: /desktop/imagefolder/image.jpg not working.
iOS apps have access only to sandbox , that mean you write only in the folder Document , Temp and Library . See the documentation.
Here an exemple how to write and read an image in documents directory.
let documentsDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let path = "\(documentsDirectory)/image.png"
let image = UIImage(contentsOfFile: path)
And now how to save:
let image = ...
let documentsDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let path = "\(documentsDirectory)/image.png"
if let data = UIImagePNGRepresentation(image!) {
try? data.write(to: URL(fileURLWithPath: path))
}

Replace folder in file system using Swift

How can I copy and paste the entire content of a folder using Swift on a OS X? If the destinationPath already contains the folder, than it should replace it.
I tried
let appSupportSourceURL = NSURL(string: appSupportSourcePath)
let appSupportDestinationURL = NSURL(string: appSupportDestinationPath+"/"+appSupportFileName)
if (fileManager.isReadableFileAtPath(appSupportSourcePath)){
do {
try fileManager.copyItemAtURL(appSupportSourceURL!, toURL: appSupportDestinationURL!)}
catch{
}
}
but I realised, that this only works for files. I am trying to replace a whole folder.
I know Apple encourages new code to use the URLs to specify file system path. However NSFileManager is an old class and it's still in transition between the old string-based path and the new URL-based paradigm. Try this:
let appSupportSourcePath = "..."
let appSupportDestinationPath = "..."
let fileManager = NSFileManager.defaultManager()
do {
// Delete if already exists
if fileManager.fileExistsAtPath(appSupportDestinationPath) {
try fileManager.removeItemAtPath(appSupportDestinationPath)
}
try fileManager.copyItemAtPath(appSupportSourcePath, toPath: appSupportDestinationPath)
} catch {
print(error)
}
Edit: method with NSURL
let appSupportSourceURL = NSURL(fileURLWithPath: "...", isDirectory: true)
let appSupportDestionURL = NSURL(fileURLWithPath: "...", isDirectory: true)
try! NSFileManager.defaultManager().copyItemAtURL(appSupportSourceURL, toURL: appSupportDestionURL)

path to an audio file in resources folder in Xcode swift

In swift how can I get the file path for a test audio File that i have copied into the resources folder in Xcode
The code I have gives file not found. Am I looking in the right Directories with NSSearchPathForDirectoriesInDomains? Any help much appreciated!
let name = "test.wav"
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
let filePath = paths.stringByAppendingPathComponent(name)
let checkValidation = NSFileManager.defaultManager()
if (checkValidation.fileExistsAtPath(filePath)) {
print("found .wav")
} else {
print("file not found")
}
i just found this that works.
let name = "test.wav"
let soundPath = (NSBundle.mainBundle().resourcePath! as NSString).stringByAppendingPathComponent(name)
let soundURL = NSURL.fileURLWithPath(soundPath)