I have a file that is in my Documents/Inbox and is shown in my Print log:
File:
file:///private/var/mobile/Containers/Data/Application/5388031B-48B5-48D6-8299-B3FEDC1D7F45/Documents/Inbox/Pizza-6.pdf
I looked here and saw a way to delete files, but I want to move them out of the Inbox folder to another folder I want to create. How would I do this? I can't find anything for iOS and Swift 2. Thank you.
Here is what I ended up doing:
// MOVING AND SAVING INCOMING PDF TO FILE MANAGER FROM INBOX
let filemgr = NSFileManager.defaultManager()
let docsDirURL = try! filemgr.URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
// 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)")
}
// Then check if the Recipes directory exists. If not, create it
let recipesURL = docsDirURL.URLByAppendingPathComponent("Recipes")
if !filemgr.fileExistsAtPath(docsDirURL.path!) {
do {
try filemgr.createDirectoryAtURL(recipesURL, withIntermediateDirectories: true, attributes: nil)
print("Directory created at: \(recipesURL)")
} catch let error as NSError {
NSLog("Unable to create directory \(error.debugDescription)")
return
}
}
// Move file from Inbox to Recipes Folder
let incomingFileName = incomingFileTransfer.lastPathComponent!
let startingURL = incomingFileTransfer
let savePDFURL = recipesURL.URLByAppendingPathComponent(incomingFileName)
if !filemgr.fileExistsAtPath(savePDFURL.path!) {
do {
try filemgr.moveItemAtURL(startingURL, toURL: savePDFURL)
} catch let error as NSError {
NSLog("Unable to move file \(error.debugDescription)")
}
}
Related
Using the new shiny WKWebView and sandbox on os/x, require some intervening reset or clear as subsequent calls to load a file URL will be ignored; this is somewhat related to an earlier question on WKWebView loadFileURL works only once -
ios there, here on os/X I do
if loadURL.isFileURL {
webView.loadFileURL(loadURL, allowingReadAccessTo: loadURL)
}
else
{
webView.load(URLRequest(url: loadURL))
}
I've tried to pass loadURL.deletingLastPathComponent() as the second arg but then all breaks - no file URLs get loaded, nor does using the user's home path, or the entire root 'file:///', nor the 'temporary' exception re: absolute file paths. Finally, trying an intervening topLoading() has no affect.
The only solution (yuck) to get a subsequent file URL loaded is to first load a non file URL!
It seems within a sandbox environment this has unintended consequences?
Well, this works but ugly - webView subclass function, as you cannot reuse a webView when a file url was previously loaded. This workaround will instantiate a new window/doc tossing the old - unless as a user preference they want to keep the old window (newWindows flag is true):
func loadNext(url: URL) {
let doc = self.window?.windowController?.document as! Document
let newWindows = UserSettings.createNewWindows.value
var fileURL = url
if !url.isFileURL {
if newWindows {
do
{
let next = try NSDocumentController.shared().openUntitledDocumentAndDisplay(true) as! Document
let oldWindow = self.window
let newWindow = next.windowControllers.first?.window
(newWindow?.contentView?.subviews.first as! MyWebView).load(URLRequest(url: url))
newWindow?.offsetFromWindow(oldWindow!)
}
catch let error {
NSApp.presentError(error)
Swift.print("Yoink, unable to create new url doc for (\(url))")
return
}
}
else
{
self.load(URLRequest(url: url))
}
}
if let origURL = (fileURL as NSURL).resolvedFinderAlias() {
fileURL = origURL
}
if appDelegate.isSandboxed() && !appDelegate.storeBookmark(url: fileURL) {
Swift.print("Yoink, unable to sandbox \(fileURL))")
return
}
if !(self.url?.isFileURL)! && !newWindows {
self.loadFileURL(fileURL, allowingReadAccessTo: fileURL)
doc.update(to: fileURL, ofType: fileURL.pathExtension)
return
}
// We need or want a new window; if need, remove the old afterward
do {
let next = try NSDocumentController.shared().openUntitledDocumentAndDisplay(true) as! Document
let oldWindow = doc.windowControllers.first?.window
let newWindow = next.windowControllers.first?.window
(newWindow?.contentView?.subviews.first as! MyWebView).loadFileURL(fileURL, allowingReadAccessTo: fileURL)
if newWindows {
newWindow?.offsetFromWindow(oldWindow!)
}
else
{
newWindow?.overlayWindow(oldWindow!)
oldWindow?.orderOut(self)
}
next.update(to: fileURL, ofType: fileURL.pathExtension)
}
catch let error
{
NSApp.presentError(error)
Swift.print("Yoink, unable to new doc (\(fileURL))")
}
}
I am using AVFoundation to capture screen recording and write it to a path. My app is sandboxed.
func captureVideo() { // Capture Method Code
let documentsDirectory = FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask).first!
let dataPath = documentsDirectory.appendingPathComponent("System")
do {
try FileManager.default.createDirectory(atPath: dataPath.path, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
print("Error creating directory: \(error.localizedDescription)")
}
session.sessionPreset = AVCaptureSessionPresetMedium
if session.canAddInput(input) {
session.addInput(input)
}
if session.canAddOutput(movieCaptureOutPut) {
session.addOutput(movieCaptureOutPut)
}
session.startRunning()
let outputUrl = URL(fileURLWithPath: dataPath.absoluteString)
movieCaptureOutPut.startRecording(toOutputFileURL: outputUrl, recordingDelegate: self)
let _ = Timer.scheduledTimer(timeInterval: TimeInterval(5), target: self, selector: #selector(self.finishRecord), userInfo: nil, repeats: false)
}
But I am getting error:
FigMovieFormatFileWriter::PostProcessMovie: WriteMovie() errored!!! -67452
I have checked write permission, as I can create 'System' folder.
Any idea how this error can be resolved?
The outputUrl should be a video URL, you can change it to something like this:
let outputUrl = URL(fileURLWithPath: dataPath.absoluteString)
.appendingPathComponent("test")
.appendingPathExtension("mov")
You can check the method's API page.
Here`s my code:
let fileName = "someFileName"
func saveDataToFile(urlStr:String){
let url = NSURL(string: urlStr)
var data:NSData!
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let directory = paths[0]
let filePath = directory.stringByAppendingPathComponent(self.fileName)
print(filePath)//prints /Users/.../Library/Developer/CoreSimulator/Devices/1013B940-6FAB-406B-96FD-1774C670A91E/data/Containers/Data/Application/2F7139D6-C137-48BF-96F6-7579821B17B7/Documents/fileName
let fileManager = NSFileManager.defaultManager()
data = NSData(contentsOfURL: url!)
print(data) // prints a lot of data
if data != nil{
fileManager.createFileAtPath(filePath, contents: data, attributes: nil)
}
}
Now I want to read this data:
func readDataFromFile(){
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let directory = paths[0]
let filePath = directory.stringByAppendingPathComponent(self.fileName)
print(filePath) // prints the same path
let fileManager = NSFileManager.defaultManager()
if fileManager.fileExistsAtPath(filePath){
data = fileManager.contentsAtPath(filePath)
}else{
print("*****BAD*****") // always prints this which means that file wasn`t created
}
}
What`s wrong with the first func? What is the right way to save file to DocumentDirectory?
OK, in this case the answer was following:
First need to create directory (aka folder) and only after that create file inside that directory.
Added to code this:
let fullDirPath = directory.stringByAppendingPathComponent(folderName)
let filePath = fullDirPath.stringByAppendingPathComponent(fileName)
do{
try fileManager.createDirectoryAtPath(fullDirPath, withIntermediateDirectories: false, attributes: nil)
}catch let error as NSError{
print(error.localizedDescription)
}
And as I said after this you create your file:
fileManager.createFileAtPath(filePath, contents: data, attributes: nil)
Thanks to Eric.D
Hope someone will find this useful.
I'm trying to download a file off the internet and place it in the application name directory under the Application Support directory and I keep getting a
Assertion failed: ([path isAbsolutePath]), function -[NSURLDownload setDestination:allowOverwrite:], file /SourceCache/CFNetwork/CFNetwork-720.5.7/Foundation/NSURLDownload.mm, line 370.
Here's the code that I wrote:
var imageRequest = NSURLRequest(URL: self.source)
var imageDownload = NSURLDownload(request: imageRequest, delegate:self)
var error: NSError? = NSError()
/* does path exist */
let directoryPath = self.destination.stringByDeletingLastPathComponent
let fileMgr = NSFileManager();
fileMgr.createDirectoryAtPath(directoryPath, withIntermediateDirectories: true, attributes: nil, error: &error)
imageDownload.setDestination(self.destination, allowOverwrite: true);
When I step through the code everything looks correct. self.source is
(https:/remoteDomain.com/img/downloadimage.jpg)
a NSURL
self.destination is the full path in my system (file:/Users/ryan/Library/Application%20Support/AppName/downloadimage.jpg)
Any Ideas?
To answer the question to your specific topic:
The error message says that your path is invalid. The right way to create the path for your image is the following:
let fileManager = NSFileManager.defaultManager()
var folder = "~/Library/Application Support/[APPNAME]/someFolder" as NSString
folder = folder.stringByExpandingTildeInPath
if fileManager.fileExistsAtPath(folder as String) == false {
do {
try fileManager.createDirectoryAtPath(folder as String, withIntermediateDirectories: true, attributes: nil)
}
catch {
//Deal with the error
}
}
BUT
#jtbandes is right. You should use NSURLSessionDownloadTask to download your files.
It is part of the Foundation.framework, which is available on OS X, iOS and watchOS.
The reason to use it is that Apple keeps updating this Api to meet the latest standards. For example, you don't need to worry about IPv4 or IPv6 etc. This avoids crashes and weird behavior in your app.
This is how you use it (Swift):
var imageRequest = NSURLRequest(URL: self.source)
let session = NSURLSession.sharedSession()
let downloadTask = session.downloadTaskWithRequest(imageRequest) { (url: NSURL?, response: NSURLResponse?, error: NSError?) -> Void in
//Work with data
}
downloadTask.resume()
Note that url is the path to the downloaded image.
I'm new to swift and I'm not sure how to make a new folder from a string path (or from some kind of File/ NSFile object)
This is on OS X with Cocoa.
My understanding is that you are trying to create a directory programmatically using swift. The code given below does the same.
var err: NSErrorPointer = nil
let manager = NSFileManager.defaultManager()
manager.createDirectoryAtPath("/Users/abc/Desktop/swiftDir", withIntermediateDirectories: true, attributes: nil, error: err)
Xcode 8 • Swift 3
extension FileManager.SearchPathDirectory {
func createSubFolder(named: String, withIntermediateDirectories: Bool = false) -> Bool {
guard let url = FileManager.default.urls(for: self, in: .userDomainMask).first else { return false }
do {
try FileManager.default.createDirectory(at: url.appendingPathComponent(named), withIntermediateDirectories: withIntermediateDirectories, attributes: nil)
return true
} catch {
print(error)
return false
}
}
}
Usage:
if FileManager.SearchPathDirectory.desktopDirectory.createSubFolder(named: "untitled folder") {
print("folder successfully created")
}
SearchPathDirectory
In Swift 2.0 you must use the new style for error handling:
let path: String = "/Users/abc/Desktop/swiftDir"
let fileManager = NSFileManager.defaultManager()
do
{
try fileManager.createDirectoryAtPath(path, withIntermediateDirectories: true, attributes: nil)
}
catch let error as NSError
{
print("Error while creating a folder.")
}