11

I am trying to make a universal framework, for iOS by following steps specified in this URL: Universal-framework-iOS

I have a viewController class within, that framework which internally loads a .xib file.

Below is a part of code which shows, how I am initializing that viewController and showing related view:

/*** Part of implementation of SomeViewController class, which is outside the framework ***/

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.viewControllerWithinFramework = [[ViewControllerWithinFramework alloc] initWithTitle:@"My custom view"];
}
- (IBAction)showSomeView:(id)sender {
    [self.viewControllerWithinFramework showRelatedView];
} 

/*** Part of implementation of ViewControllerWithinFramework class, which is inside the framework ***/

- (id)initWithTitle:(NSString *)aTitle
{
   self = [super initWithNibName:@"ViewControllerWithinFramework" bundle:nil]; // ViewControllerWithinFramework.xib is within the framework

   if (self)
   {
       _viewControllerTitle = aTitle;
   }

   return self;
}

While creating the framework, I included all .xib files, including ViewControllerWithinFramework.xib within its Copy Bundle Resources build phase.

Now my problem is when I try to integrate that framework within other project, it crashes with below stack trace:

Sample[3616:a0b] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle </Users/miraaj/Library/Application Support/iPhone Simulator/7.0/Applications/78CB9BC5-0FCE-40FC-8BCB-721EBA031296/Sample.app> (loaded)' with name 'ViewControllerWithinFramework''
*** First throw call stack:
(
    0   CoreFoundation                      0x017365e4 __exceptionPreprocess + 180
    1   libobjc.A.dylib                     0x014b98b6 objc_exception_throw + 44
    2   CoreFoundation                      0x017363bb +[NSException raise:format:] + 139
    3   UIKit                               0x004cc65c -[UINib instantiateWithOwner:options:] + 951
    4   UIKit                               0x0033ec95 -[UIViewController _loadViewFromNibNamed:bundle:] + 280
    5   UIKit                               0x0033f43d -[UIViewController loadView] + 302
    6   UIKit                               0x0033f73e -[UIViewController loadViewIfRequired] + 78
    7   UIKit                               0x0033fc44 -[UIViewController view] + 35

Any ideas, how could I resolve this problem?

Note: It works fine if there is no any xib within the framework.

Avi
  • 21,182
  • 26
  • 82
  • 121
Devarshi
  • 16,440
  • 13
  • 72
  • 125
  • Can you please confirm that the nib is included in the ipa bundle? Locate your simulator directory where the ipa is installed, Show Package Contents, and see if your nib is indeed there. – TomSwift Mar 23 '14 at 16:02

8 Answers8

4

If you're using Universal-framework-iOS all resources (including Nibs and images), will be copied inside a separate bundle (folder) such as MyApp.app/Myframework.bundle/MyNib.nib.

You need to specify this bundle by passing a NSBundle object instead of nil. Your can get your bundle object as follows:

NSString *path = [[NSBundle mainBundle] pathForResource:@"Myframework" ofType:@"bundle"];
NSBundle *resourcesBundle = [NSBundle bundleWithPath:path];

As for images you can just prepend Myframework.bundle/ to their names:

[UIImage imageNamed:@"Myframework.bundle/MyImage"

This also works in Interface Builder.

Finally your users to install/update a framework is a pain, specially with resources, so better try to use CocoaPods.

Rivera
  • 10,792
  • 3
  • 58
  • 102
  • Hi I have a static library which has a bundle of resources.I want to access the images from xcassets but not able to.Can you suggest any workaround? – user1010819 Dec 23 '14 at 08:20
2

Unfortunately because iOS does not have an exposed concept of dynamic fragment loading some of NSBundle's most useful functionality is a little hard to get to. What you want to do is register the framework bundle with NSBundle, and from then on you can find the bundle by it's identifier - and the system should be able to correctly find nibs, etc. within that bundle. Remember, a framework is just a kind of bundle.

To make NSBundle "see" your bundle and it's meta information (from it's Info.plist), you have to get it to attempt to load the bundle. It will log an error because there will be no CFPlugin class assigned as a principal class, but it will work.

So for example:

NSArray *bundz = [[NSBundle bundleForClass:[self class]] URLsForResourcesWithExtension:@"framework" subdirectory:nil];
for (NSURL *bundleURL in bundz){
    // This should force it to attempt to load. Don't worry if it says it can't find a class.
    NSBundle *child = [NSBundle bundleWithURL:bundleURL];
    [child load];
}

Once that is done, you can find your framework bundle using bundleWithIdentifier:, where the identifier is the CFBundleIdentifier in your framework's Info.plist. If you need to use UINib directly to load your view controller nib directly at that point, it should be easy to locate the bundle using bundleWithIdentifier: and give that value to nibWithNibName:bundle: .

quellish
  • 21,123
  • 4
  • 76
  • 83
  • I believe this is actually more than what's necessary to solve just the OP's issue. Since the code getting the nib is part of the framework, it's possible to just use ```[NSBundle bundleForClass:[self class]``` to get the framework's bundle instance and use that in `initWithNibName:bundle:`. – Jay Whitsitt Aug 26 '17 at 02:37
2

As an another option you can directly put your xib file into your framework project and can get your nib with calling

Swift 3 and Swift 4

let bundleIdentifier = "YOUR_FRAMEWORK_BUNDLE_ID"
let bundle = Bundle(identifier: bundleIdentifier)
let view = bundle?.loadNibNamed("YOUR_XIB_FILE_NAME", owner: nil, options: nil)?.first as! UIView

Objective-C

NSString *bundleIdentifier = @"YOUR_FRAMEWORK_BUNDLE_ID";
NSBundle *bundle = [NSBundle bundleWithIdentifier:bundleIdentifier];
UIView *view =  [bundle loadNibNamed:@"YOUR_XIB_FILE_NAME" owner:nil options:nil];
abdullahselek
  • 7,893
  • 3
  • 50
  • 40
2

The simplest way is to use [NSBundle bundleForClass:[self class]] to get the NSBundle instance of your framework. This won't enable the ability to get the framework's NSBundle instance by its Bundle ID but that isn't usually necessary.

The issue with your code is the initWithNibName:@"Name" bundle:nil gets a file named Name.xib in the given bundle. Since bundle is nil, it looks in the host app's bundle, not your framework.

The corrected code for the OP's issue is this:

/*** Part of implementation of ViewControllerWithinFramework class, which is inside the framework ***/

- (id)initWithTitle:(NSString *)aTitle
{
   NSBundle *bundle = [NSBundle bundleForClass:[self class]];
   self = [super initWithNibName:@"ViewControllerWithinFramework" bundle:bundle];

   // ... 

   return self;
}

The only thing changed is giving the correct bundle instance.

Jay Whitsitt
  • 937
  • 9
  • 27
1

Frameworks that come with XIBs usually come with bundles too - so you probably should not pass nil in the framework part.

Right click the framework -> Show in finder Open it up and see what's the bundle name in the resources folder (For example - Facebook uses FBUserSettingsViewResources.bundle) and use it.

In general - static libraries do not include xib or resource files. Frameworks is basically a wrapper to a static library, headers and some resources (usually inside a bundle)

Liviu R
  • 679
  • 8
  • 16
  • And 3rd party frameworks are not natively supported for iOS development, so you still have to add the resources and set the correct headers path yourself. – Rivera May 12 '14 at 00:41
1

You need to specify the bundle to search inside for the nib. Otherwise, it just (shallowly) searches your application's resources directory.

- (id)initWithTitle:(NSString *)aTitle
{
    // replace 'framework' with 'bundle' for a static resources bundle 
    NSURL *frameworkURL = [[NSBundle mainBundle] URLForResource:@"myFrameworkName" withExtension:@"framework"];
    NSBundle *framework = [NSBundle bundleWithURL:frameworkURL];

    self = [super initWithNibName:@"ViewControllerWithinFramework" bundle:framework];
    if (self)
    {
       _viewControllerTitle = aTitle;
    }

    return self;
}
Chris Devereux
  • 5,453
  • 1
  • 26
  • 32
1

I'm going to answer this the way I achieved the results you intended, but it may not be the best approach, improvements are more than welcome! I did it on a Cocoa Touch Framework subproject, but it should be easy to adapt to a Cocoa Touch Static Library, if it doesn't work already. This will be more like a tutorial than an answer, to be honest, but anyway...

First things first. Quick overview of my solution: you'll have two projects on the same workspace. One is the framework, the other one is the app itself. You'll create the xib/storyboard on the framework, and use it either on the framework or the app (although the latter doesn't make much sense to me).

The framework project will contain a build run script that will copy all it's resources (images, xibs, storyboards) to a bundle, and that bundle will be part of the app project. Also, the framework project will be a dependency of your app project. This way, whenever you compile your app, the build run script should run automatically and update the resources bundle before packaging your app.

It sure is NOT a quick & easy thing to set up, but that's why I'm answering your question. This way I'll be able to come back here myself and remember how I achieved the same goal. You never know when Alzheimer's gonna hit you :)

Anyway, let's get to work.

  1. Create/open your app's project. I'll be referring to this as AppProject.

  2. Create a framework/library project and add it as subproject to the AppProject, or just drag your current framework project to the AppProject. What matters here is that the framework project is a subproject of AppProject. I'll be referring to the framework project as MyFramework.

  3. Configure whatever you need for your specific projects. I guess it's a standard thing to use linker flags -ObjC and -all_load, at least. This isn't really useful for the purpose of this mini-tutorial, but the project should at least be compiling. Your workspace should be looking something like this:

    workspace

  4. Open the AppProject folder and create a new directory called MyBundle.bundle.

  5. Drag the MyBundle.bundle to the AppProject (this is important: you are NOT supposed to drag it to the library project!). You probably want to un-check the Copy items if needed and select/check the targets where this bundle will be copied to when compiling your app.

  6. Leave MyBundle.bundle alone for now.

  7. Go to MyFramework's Build Settings and add a new Run script phase.

  8. This step might be optional, but it worked like this for me, so I'm including it. Drag the just-created Run script right above the Compile sources phase.

  9. Edit the Run script phase, changing it's shell to /bin/sh if it's not that already. Set the script to the following (comments should explain the script):

Run script

#!/bin/bash
echo "Building assets bundle."

# Bundle name (without the ".bundle" part). I separated this because I have different app targets, each one with a different bundle.
BUNDLE_NAME='MyBundle'
CURRENT_PATH=`pwd`

# This should generate the full path to your bundle. Might need to be adapted if the bundle
# directory you created was in another directory.
BUNDLE_PATH="$CURRENT_PATH/$BUNDLE_NAME.bundle"

# Check if the bundle exists, and removes it completely if it does.
if [ -d "$BUNDLE_PATH" ]; then
    rm -rf "$BUNDLE_PATH"
fi

# Re-creates the same bundle (I know this is weird. But at least I am SURE the bundle will
# be clean for the next steps)
mkdir "$BUNDLE_PATH"

# Copy all .jpg files to the bundle
find ./ -name *.jpg -type f -print0 | xargs -0 -J% cp % "$BUNDLE_PATH"

# Copy all .png files to the bundle
find ./ -name *.png -type f -print0 | xargs -0 -J% cp % "$BUNDLE_PATH"

# Copy all .xib files to the bundle.
find ./ -name *.xib -type f -print0 | xargs -0 -J% cp % "$BUNDLE_PATH"

# Copy all .storyboard files to the bundle.
find ./ -name *.storyboard -type f -print0 | xargs -0 -J% cp % "$BUNDLE_PATH"

# This is the golden thing. iOS code will not load .xib or storyboard files, you need to compile
# them for that. That's what these loop do: they get each .xib / .storyboard file and compiles them using Xcode's
# ibtool CLI.

for f in "$BUNDLE_PATH/"*.xib ;
do
    # $f now holds the complete path and filename a .xib file
    XIB_NAME="$f";
                        
    # Replace the ".xib" at the end of $f by ".nib"
    NIB_NAME="${f%.xib}.nib";
    
    # Execute the ibtool to compile the xib file
    ibtool --compile "$NIB_NAME" "$XIB_NAME"
                        
    # Since the xib file is now useless for us, remove it.
    rm -f "$f"
done

for f in "$BUNDLE_PATH/"*.storyboard ;
do
    # $f now holds the complete path and filename a .storyboard file
    STORYBOARD_NAME="$f";

    # Replace the ".storyboard" at the end of $f by ".storyboardc" (could've just added the final "c", but I like
    # to keep both loops equal)
    COMPILED_NAME="${f%.storyboard}.storyboardc";

    # Execute the ibtool to compile the storyboard file
    ibtool --compile "$COMPILED_NAME" "$STORYBOARD_NAME"

    # Since the .storyboard file is now useless for us, remove it.
    rm -f "$f"
done
  1. Your workspace/settings should be looking something like this now:

settings

  1. Go to AppProject Build phases, and add your framework to the Link Binary with Libraries section. Also add the framework as the Target dependencies section.

dependencies

  1. Everything seems to be set up. Create a xib or storyboard file on the framework project, and create the view (or view controller) just the way you usually do. Nothing special here. You can even set custom classes for your components and everything (as long as the custom class is inside the framework project, and not in the app project).

Before compiling the app project

before_compiling

After compiling the app project

after_compiling

  1. On your code, wherever you need to load your NIB/Xib, use one of the following codes. If you managed to follow so far, I don't even need to tell you you'll need to adapt these codes to whatever you wanna do with the xib/Storyboard, so... Enjoy :)

Registering cell xib for a UITableView:

NSString* bundlePath = [[NSBundle mainBundle] pathForResource:@"MyBundle" ofType:@"bundle"];
NSBundle* bundle = [NSBundle bundleWithPath:bundlePath];
UINib* nib = [UINib nibWithNibName:@"TestView" bundle:bundle];
[tableView registerNib:nib forCellReuseIdentifier:@"my_cell"];

Pushing a UIViewController to the navigation controller:

NSString* bundlePath = [[NSBundle mainBundle] pathForResource:@"MyBundle" ofType:@"bundle"];
NSBundle* bundle = [NSBundle bundleWithPath:bundlePath];
UIViewController* vc = [[UIViewController alloc] initWithNibName:@"BundleViewController" bundle:bundle]; // You can use your own classes instead of the default UIViewController
[navigationController pushViewController:vc animated:YES];

Presenting modally a UIStoryboard from it's initial UIViewController:

NSString* bundlePath = [[NSBundle mainBundle] pathForResource:@"MyBundle" ofType:@"bundle"];
NSBundle* bundle = [NSBundle bundleWithPath:bundlePath];
UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"BundleStoryboard" bundle:bundle];
UIViewController* vc = [storyboard instantiateInitialViewController];
vc.modalPresentationStyle = UIModalPresentationFormSheet;
vc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentViewController:vc animated:YES completion:^{}];

If it doesn't work for you (or whoever is visiting this question/answer), please let me know and I'll try to help.

Community
  • 1
  • 1
B.R.W.
  • 1,566
  • 9
  • 15
0

Try this in main.m

#import "ViewControllerWithinFramework.h"  //import this

int main(int argc, char *argv[])
{
    @autoreleasepool 
{
    [ViewControllerWithinFramework class]; //call class function
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
}

I hope this will work for you.

svrushal
  • 1,612
  • 14
  • 25
  • Have you tried my answer? If yes does it solved you issue or not. Or U got any other solution. if so please post the answer. – svrushal Mar 28 '14 at 05:33