The Alamofire readme indicates that you can download and save a file like this:
let destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)
Alamofire.download(.GET, "http://httpbin.org/stream/100", destination: destination)
...but I want to change the location where it is saved. How do I alter .DocumentDirectory to be my app's Application Support path on Mac OS X?
I can generate my app's local NSURL path like this:
let path = NSFileManager.defaultManager().URLsForDirectory(.ApplicationSupportDirectory, inDomains: .UserDomainMask)[0] as NSURL
let newPath = path.URLByAppendingPathComponent("MyApp/user-profile.png")
I'm unclear on how to use this with Alamofire's suggestedDownloadDestination.
Any ideas?
suggestedDownloadDestination will try to find an available directory, but in your case you already know the full path so you don't need it.
Just create a closure with your path:
let path = NSFileManager.defaultManager().URLsForDirectory(.ApplicationSupportDirectory, inDomains: .UserDomainMask)[0] as NSURL
let newPath = path.URLByAppendingPathComponent("MyApp/user-profile.png")
Alamofire.download(.GET, "http://httpbin.org/stream/100", { _ in newPath })
Related
I'm using:
let dialog = NSOpenPanel()
to get a file URL.
I'm then reading in the contents of the text file with:
let content = try String( contentsOf: dialog.url)
This works!
I'm then trying to read in another text file in the same directory with a different extension:
let b = dialog.url?.deletingPathExtension()
// Add the new file extension
let c = b?.appendingPathExtension("TSN")
let content2 = try String( contentsOf: c)
With this I get:
"The file “FLO5.TSN” couldn’t be opened because you don’t have permission to view it."
If I try and open the .tsn file with a URL from a NSOpenPanel() dialog result it works. I need to open several data files from this same directory with different extensions. Is there a way to do this?
set off sandbox!!)
Xcode 9 and later enables sandboxing by default, which severely limits interactions with the system.
Select your target, then Capabilities and set Downloads Folder to Read/Write:
In my case, solve it's startAccessingSecurityScopedResource
Example:
let selectedFile = try result.get() // get path to file
do {
// get access to open file
if selectedFile.startAccessingSecurityScopedResource() {
let path = selectedFile.path
let data = NSData(contentsOfFile: path)
print(data) // array bytes
selectedFile.stopAccessingSecurityScopedResource()
}
} catch {
// Couldn't read the file.
print(error.localizedDescription)
}
Apple wiki about this feature https://developer.apple.com/documentation/foundation/nsurl/1417051-startaccessingsecurityscopedreso
Is it possible to create a folder and have SpriteKit go through that folder, find each image (regardless of name), and create a SKShapeNode for each in that folder (regardless of how many there are)?
Assume all images are the same size, and all .png files ready to be used as unique images as textures for filling SKShapeNodes, and that all SKShapeNodes will be the same size.
I want to know, once done, how many shapes have been created, and have them uniquely named based on the name of the image of the texture used.
But all I'm reading seems to be about knowing how many images are there, and what their names are, before hand.
Clueless as to where to start searching about how to do this.
Update: no idea how to reference the "folder" with images:
I've dumped the images, with their very imaginative names [one, two, three, four, five etc. ], into a folder as "atlas", like this:
but as per Allessandro's wonderful answer, I have no idea how to address this "folder" and get at what's in it.
I think it's this line I'm getting completely wrong:
let folderPath = Bundle.main.path(forResource: "Images", ofType: nil)
I don't know what to replace "Images" with.
Update 2:
Found a much easier way to do this:
let myTextureAtlas = SKTextureAtlas(named: "demoArt")
print(myTextureAtlas)
print(myTextureAtlas.textureNames)
Too many requests , so I try to help you with some code:
Create a folder:
func createDir(folderName:String) {
let fileManager = FileManager.default
if let directory = fileManager.containerURL(forSecurityApplicationGroupIdentifier: "APP_GROUP_IDENTIFIER") {
let newDirectory = directory.appendingPathComponent(folderName)
try! fileManager.createDirectory(at: newDirectory, withIntermediateDirectories: false, attributes: nil)
}
}
Now you have your folder so you can decide to save a file or to copy one file from documents to this new directory. I make an example for the last one.
Copy a file:
let fileManager = FileManager.default
do {
try fileManager.copyItem(atPath: "hero.png", toPath: "subfolder/hero.swift")
}
catch let error as NSError {
print("Something went wrong: \(error)")
}
Now you want to know how to extract all files from a directory.
Extract all files from a directory:
func extractAllFile(atPath path: String, withExtension fileExtension:String) -> [String] {
let pathURL = NSURL(fileURLWithPath: path, isDirectory: true)
var allFiles: [String] = []
let fileManager = FileManager.default
if let enumerator = fileManager.enumerator(atPath: path) {
for file in enumerator {
if #available(iOS 9.0, *) {
if let path = NSURL(fileURLWithPath: file as! String, relativeTo: pathURL as URL).path
, path.hasSuffix(".\(fileExtension)"){
allFiles.append(path)
}
} else {
// Fallback on earlier versions
}
}
}
return allFiles
}
Usage:
let folderPath = Bundle.main.path(forResource: "Images", ofType: nil)
let allPngFiles = extractAllFile(atPath: folderPath!, withExtension: "png") // returns file path of all the png files inside the folder
After that, you can create an array of SKShapeNode based from allPngFiles using fillTexture with a SKTexture created from each image and give to each node the name of the file used (so you know at the end also how many nodes you have created from array.count).
Slightly different answer here. I'm not sure why one needs to create a directory and copy files over. In your screenshot you have a demoArt.atlas with 7 files (one.png, two.png, etc). You indicate you want to generate an SKShapeNode. It still isn't clear to me why you want SKShapeNode, but ignoring that, you just need to know the folder name. You'll notice how the folder is blue, which means it is a reference. This means that in the image, the folder is retained.
This would get you all the files in that directory:
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let texPath = NSURL(fileURLWithPath: documentsPath).appendingPathComponent("demoArt.atlas")
let filemanager:FileManager = FileManager()
// Error check/ensure path exists
let files = filemanager.enumerator(atPath:texPath!.path)
while let file = files?.nextObject() {
print(file)
// Create your SKShapeNode here, you can load file from this
// This is all relative path, so "file" would be one.png, two.png, etc. If you need the full path, you
// need to prepend texPath
}
Note the key diff here is not copying files over. Maybe I just don't understand the problem and why it would require the copy.
If you wanted to put that in an array you can. But here you'll have the file name of the texture which you would of course need to load.
Realistically, you want to load those textures asynchronously first, then construct your SKShapeNode.
I used swiftData to store information on sqlite database till today it will work fine and suddenly it created a new location of database as well as simulator location
when first time run it shows
/Users/div/Library/Developer/CoreSimulator/Devices/606D7F8E-2402-4782-ADEE-12725EDB203A/data/Containers/Data/Application/2DB733AF-2544-4256-B1E5-5E8725E51CDF/Documents/DataBase.db
second time
/Users/div/Library/Developer/CoreSimulator/Devices/606D7F8E-2402-4782-ADEE-12725EDB203A/data/Containers/Data/Application/551991FA-392A-40E9-810E-31CEFCD3069A/Documents/dataBase.db
third time
/Users/div/Library/Developer/CoreSimulator/Devices/606D7F8E-2402-4782-ADEE-12725EDB203A/data/Containers/Data/Application/03E4BE03-D6E7-47BF-A98D-A129DF09DD28/Documents/DataBase.db
i used this code
let fileManager = NSFileManager()
var Sourcepath = NSBundle.mainBundle().resourcePath?.stringByAppendingPathComponent("PhotoKeeper.db");
let docsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as String
let databaseStr = "DataBase.db"
let dbPath = docsPath.stringByAppendingPathComponent(databaseStr)
println(dbPath)
if(fileManager .fileExistsAtPath(dbPath) == false) {
var error:NSError?
fileManager.copyItemAtPath(Sourcepath!, toPath: dbPath, error: &error)
println(error)
}
my problem is every time new instance of database is created i.e. if i insert 2 row and compile and run the app it will create new database with zero row
You should save only relative path of your contents (document, db, ...) cause XCode with iOS8 (I suppose) changes application folder whenever you build and run it.
For example, you have your .db file in Documents, so just save your link as "DataBase.db". Then, when you need to access to this file, get the path as:
let documentsFolder = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as String
let dbPath = documentsFolder.stringByAppendingPathComponent("Database.db")
I want to open a text file in Swift and I managed to do it passing the full path as parameter:
let dados = String.stringWithContentsOfFile("/Users/aczuquim/Google Drive/Swift/Verdadeiro ou Falso/Verdadeiro ou Falso/Dados.txt", encoding: NSUTF8StringEncoding, error: nil)
Since, I added the file to the project, is there any way to use relative path?
When I use the relative path, a nil is returned.
UPDATE
In the playground, the line bellow works fine:
let dados = String.stringWithContentsOfFile("/Users/aczuquim/Google Drive/Swift/Verdadeiro ou Falso/Verdadeiro ou Falso/dados.txt", encoding: NSUTF8StringEncoding, error: nil)
But not the following ones (path is nil):
let bundle = NSBundle.mainBundle()
let path = bundle.pathForResource("dados", ofType: "txt")
Bundle resource:
Swift 3.0
if let bundle = Bundle.main().urlForResource("Info", withExtension: "plist") {
print("Path: \(bundle)")
}
Swift 2.0
let bundleURL = NSBundle.mainBundle()!.URLForResource("dados", withExtension: "txt")
println("\(bundleURL)")
If a nil is returned then the resource is not found and an error reported (note the exclamation mark after mainBundle). Check Build Phases - Copy Bundle Resources if the resource is being included.
App and Documents Folder
Get the documents folder from an array of [AnyObject]! which casts the first object to the NSURL type:
let docFolderURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL
println("DocumentFolderURL: \(docFolderURL)")
Then get the App folder, by stepping up to the parent folder and delete the last path component:
let appFolderURL = docFolderURL.URLByDeletingLastPathComponent
println("AppFolderURL: \(appFolderURL)")
Other directories may be accessed by using .URLByAppendingPathComponent(pathComponent: String?, isDirectory:Bool) etc.
Temporary Directory
var tempURL = NSURL.fileURLWithPath(NSTemporaryDirectory(), isDirectory: true).URLByDeletingLastPathComponent
Note that Apple now prefers the use of URL´s to access folders and files and new methods use them exclusively. To use the path in older methods just call: tempURL.path
I am working on OS X application. In the code, I would like to output a path of the current Mac OS App to a variable for future use. So later I could read the files in the same folder. Could anyone tell me the command/method in the Xcode ?
Thanks very much.
UPDATE
To be more clear, I am using xcode and create a cocoa-application.
My application is connected with applescript to control Mac software read files on the Mac. So I have to return the files' directory and name.
Actually I have no idea about what to do. So got stuck here.
To get the URL of your application, you can use:
[[NSBundle mainBundle] bundleURL]
See the NSBundle Class Reference for further information.
my 2 cents for swift 5,x:
let path = Bundle.main.bundlePath
print(path)
If You need a path to REAL exacutable: (i.e. you mast pass to shell or similar..)
let appName = AppName()
let exePath = path + "/Contents/MacOS/" + appName
print(exePath)
where AppName() is:
func AppName()->String{
let bund = Bundle.main
//print(bund)
if let displayName = bund.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String {
if displayName.count>0{
return displayName
}
}
if let name = bund.object(forInfoDictionaryKey: "CFBundleName") as? String {
return name
}
return "no AppName"
}