Problem creating and writing a subdirectory in Swift 5
Remove the check if the file already exists, if !fileManager.fileExists(atPath: myAppDirectoryURL.path)
since the createDirectory
call will not generate an error if the directory already exist when you have withIntermediateDirectories
set tot true.
You used some properties that wasn't part of the question so here is my test version of your function for completeness
func saveToDirectory(_ fileName: String, text: String) {
let fileManager = FileManager.default
do {
let directoryURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
let myAppDirectoryURL = directoryURL.appendingPathComponent("MySubDirectory")
try fileManager.createDirectory(at: myAppDirectoryURL, withIntermediateDirectories: true, attributes: nil)
let documentURL = myAppDirectoryURL.appendingPathComponent (fileName)
try text.write(to: documentURL, atomically: true, encoding: .utf8)
} catch {
print(error)
}
}
(Swift) How to make subfolders in one folder
Your code should be like below,
extension FileManager.SearchPathDirectory {
func createSubFolder(named: String, withIntermediateDirectories: Bool = true) -> 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
}
}
}
I have just set withIntermediateDirectories's default value to true
.
createIntermediates
: If true, this method creates any nonexistent parent directories as part of creating the directory in url. If false, this method fails if any of the intermediate parent directories does not exist.
How to make subfolder inside a folder
The main issue is that you cannot create a directory passing a file path including the file name (/../AET/1.jpg
). You need to specify a folder path without the file name.
Generally it's highly recommended to use the URL related API.
This example uses the URL related API, more descriptive variable names and the API of Data
to write the image data to disk.
let chkString : String? = "AET"
let fileManager = FileManager.default
do {
let documentDirectoryURL = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let imagesFolderURL = documentDirectoryURL.appendingPathComponent("images/\(chkString!)")
let imageURL = imagesFolderURL.appendingPathComponent("1.jpg")
let image = imagePic// UIImage(named: "apple.jpg")
if !fileManager.fileExists(atPath: imagesFolderURL.path){
try fileManager.createDirectory(at: imagesFolderURL, withIntermediateDirectories: true, attributes: nil)
} else {
print("Already dictionary created.")
}
let imageData = UIImageJPEGRepresentation(image, 0.5)
try imageData!.write(to: imageURL)
print("imagePath =", imageURL.path)
} catch {
print(error)
}
No such file or directory Error when creating directory
Here's the way to get the documents directory:
- (NSString *)documentsDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
return (paths.count)? paths[0] : nil;
}
Then, to build the path to your file:
- (NSURL *)thumbnailDirectoryWithName:(NSString *)theName {
NSString *namePath = [[self documentsDirectory] stringByAppendingPathComponent:theName];
NSString *thumbnailsPath = [namePath stringByAppendingPathComponent:@"Thumbnails"];
NSURL *thumbnailsURL = [NSURL fileURLWithPath:thumbnailsPath];
NSError *error;
if ([[NSFileManager defaultManager] fileExistsAtPath:thumbnailsPath] == NO) {
[[NSFileManager defaultManager] createDirectoryAtURL:thumbnailsURL withIntermediateDirectories:YES attributes:nil error:&error];
if (error) {
NSLog(@"[Thumbnail Directory] %@", [error description]);
return nil;
}
}
return thumbnailsURL;
}
Get nil when looking for file in subdirectory of main bundle
The solution is to use
Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "games/game1")
I don't know why, but it doesn't work if we get a path, then construct an URL from it.
Note: You must
- Copy items if needed
- Create folder references (not "Create groups")
- Add to targets
Problem with get path to a subfolder in main bundle in AVPlayer
First of all you are responsible for creating the directory structure of the bundle so don't mess it up.
Secondly use the URL related API.
For example put all mp4 files in a subdirectory named videos
. It's crucial that you create a real blue folder rather than a group (yellow) folder.
This would reduce your code to
var videoArray = [URL]()
override func viewDidLoad() {
super.viewDidLoad()
videoTableView.delegate = self
videoTableView.dataSource = self
videoView.addSubview(videoVC.view)
videoVC.view.frame = videoView.frame
videoVC.showsPlaybackControls = false
videoArray = Bundle.main.urls(forResourcesWithExtension: "mp4", subdirectory: "videos")!
playTopVideo(value: 0)
}
func playTopVideo(value: Int) {
let videoURL = videoArray[value]
videoVC.player = AVPlayer(url: videoURL)
videoVC.player?.play()
}
Move file from mainfolder to subfolder failed
Cocoa error 4
here means that you are trying to move a file that does not exist or this could also mean that the target directory does not exists.
Related Topics
Error While Using Property 'Cgrectgetwidth', It Says It Was Replaced with 'Cgrect.Width'
How to Set Cadisplaylink in Swift with Weak Reference Between Target and Cadisplaylink Instance
Swift Spritekit 3D Touch and Touches Moved
Codable Decode Property with Multiple Object Types Based on Another Value
Update Firebase Multi-Location with Error: Path Is an Ancestor of Path. Swift
"Unexpectedly Found Nil While Unwrapping an Optional Value" When Retriveing Pffile from Parse.Com
Swift Function Compiler Error 'Missing Return'
Equivalent of Skaction Scaletox for a Given Duration in Unity
Why Do We Need to Specify Init Method
Swift Switch Char{ Case "\U{E2}:
How to Run the Simulator the Operation Couldn't Be Completed. (Launchserviceserror Error 0.)
Swift Check If Value Is of Type Array (Of Any Type)
Auth.Auth().Currentuser.Reload() Doesn't Refresh Currentuser.Isemailverified
What Does the Underscore in a Function Declaration Do
Accessing Actor Properties Synchronously from Task-Less Context