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
Bundle.main.path(forResource... always returns nil when looking for xml file
Try this code:
if let filePath = Bundle.main.url(forResource: "config.xml", withExtension: nil, subdirectory: "/Resources") {
/// Do something with the filePath
}
Getting a subdirectory from mainBundle in xcode
The yellow folder icon for your "Objects" folder indicates that you created a folder group instead of a folder reference (those have blue folder icons) when you dragged your image folder onto the Xcode project.
Xcode copies files in a folder group into the root directory of your app bundle during the "Copy Bundle Resources" build phase.
If you want a subdirectory named "Objects" in your app bundle, you have to choose "Create folder references for any added folder" after dragging "Objects" into your Xcode window.
You projects sidebar should display the "Objects" folder as follows:
To get a list of all .pngs from that copied folder, you can use the following code:
NSURL* resourceURL = [[NSBundle mainBundle] resourceURL];
resourceURL = [resourceURL URLByAppendingPathComponent:@"Objects"];
NSError* error = nil;
NSArray* resourceURLContents = [[NSFileManager defaultManager] contentsOfDirectoryAtURL:resourceURL includingPropertiesForKeys:nil options:0 error:&error];
resourceURLContents = [resourceURLContents filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(NSURL* evaluatedObject, NSDictionary *bindings) {
return [[evaluatedObject pathExtension] isEqualToString:@"png"];
}]];
NSLog(@"Contents:%@", resourceURLContents);
How to get path to a subfolder in main bundle?
In Swift-3 make URL
, and call appendingPathComponent
:
let resourcePath = Bundle.main.resourcePath
let subdir = URL(fileURLWithPath:resourcePath!).appendingPathComponent("sub").path
or simply
let subdir = Bundle.main.resourceURL!.appendingPathComponent("sub").path
(thanks, Martin R!)
See this Q&A on information on stringByAppendingPathComponent
method in Swift.
Can't find resource from Bundle
- Click the target of project.
- Select the item of Build Phase.
- under
Copy Bundle Resources
check if your file is listed or not. If not
listed add with the plus button.
How do I get all resource paths in my bundle recursively in iOS?
I got this working using the code posted by @rekle as a starting point. The trick is to use NSDirectoryEnumerator, which will do this recursively. Here's the function I wrote in case anyone needs it.
- (NSArray *)recursivePathsForResourcesOfType:(NSString *)type inDirectory:(NSString *)directoryPath{
NSMutableArray *filePaths = [[NSMutableArray alloc] init];
// Enumerators are recursive
NSDirectoryEnumerator *enumerator = [[[NSFileManager defaultManager] enumeratorAtPath:directoryPath] retain];
NSString *filePath;
while ((filePath = [enumerator nextObject]) != nil){
// If we have the right type of file, add it to the list
// Make sure to prepend the directory path
if([[filePath pathExtension] isEqualToString:type]){
[filePaths addObject:[directoryPath stringByAppendingPathComponent:filePath]];
}
}
[enumerator release];
return [filePaths autorelease];
}
Swift, using NSURL
func recursivePathsForResources(type type: String) -> [NSURL] {
// Enumerators are recursive
let enumerator = NSFileManager.defaultManager().enumeratorAtPath(bundlePath)
var filePaths = [NSURL]()
while let filePath = enumerator?.nextObject() as? String {
if NSURL(fileURLWithPath: filePath).pathExtension == type {
filePaths.append(bundleURL.URLByAppendingPathComponent(filePath))
}
}
return filePaths
}
Related Topics
Parse.Com Pfgeopoint.Geopointforcurrentlocationinbackground Not Doing Anything
JSONencoder Won't Allow Type Encoded to Primitive Value
How to Combine Two Nsdictionary in Swift
Scenekit Shape Between 4 Points
How to Prompt for Accessibility Features in a MACos App (From the Appdelegate)
Expression Pattern of Type 'String' Cannot Match Values of Type 'Nsstoryboardsegue.Identifier
Swift Throws Python Errors from Terminal
Swiftui List View Not Updating After Core Data Entity Updated in Another View
How to Create and Access Share App Group Document Directory
Usage of Withmemoryrebound with Apples Swift 3 Beta 6
Saving Swifty JSON Array to User Defaults
Count the Number of Lines in a Swift String
Http Request Swift Providing Parameters
Guard Let Error: Initializer for Conditional Binding Must Have Optional Type Not 'String'
Swift - Encode and Decode a Dictionary [String:Any] into Plist
Swift iOS 9: Section Header Change Position After Reload Data