загрузка файлов NSBundle на iOS - PullRequest
26 голосов
/ 01 июня 2011

Я хотел бы создать проект с очень гибким графическим интерфейсом пользователя ( skinnable ).Чтобы сделать это возможным, я бы хотел загрузить NSBundle с внешнего ресурса, например с веб-сайта.Пакет должен содержать перья, которые соответствуют некоторым свойствам и методам в основном проекте (IBOutlets & IBActions)

Кажется, Apple ограничила возможность использовать NSBundle таким способом.Есть ли способ, которым я могу сделать эту работу?Если это невозможно обычным способом, какой рекомендуемый альтернативный подход?

Ответы [ 2 ]

34 голосов
/ 03 июня 2011

Как и было обещано, вот краткое объяснение того, как я это сделал.

В моем AppDelegate я проверяю, есть ли на сервере новый пакет (упакованный в zip-файл).Если он существует, я загружаю пакет.Пакет содержит перья, необходимые для графического интерфейса с поддержкой скинов, и другие связанные данные (например, графические файлы).Код выглядит примерно так:

TestAppDelegate.m

- (void)downloadBundle 
{      
   NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/~wsc/template.bundle.zip"];
   NSURLRequest *request = [NSURLRequest requestWithURL:url];
   NSURLResponse *response = nil;
   NSError *error = nil;
   NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
   NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
   NSLog(@"%d", [httpResponse statusCode]);

   if ([httpResponse statusCode] == 404) // bundle will be deleted and the default interface will be used ...
   {
      NSString *path = [documentsDirectory stringByAppendingPathComponent:@"template.bundle"];
      [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
      return;
   }
   else if (error) 
   {
      NSLog(@"%@", error);
   }

   BOOL didWriteData = [data writeToFile:zipFile atomically:YES];
   if (didWriteData) 
   {
      BOOL success = [SSZipArchive unzipFileAtPath:zipFile toDestination:documentsDirectory];
      if (!success) 
      {
         NSLog(@"failed to unzip file.");
      }
   }
}

Обратите внимание, что я использую класс SSZipArchive, предложенный neoneye .Для эффективной загрузки всего пакета необходимо упаковать пакет в какой-то контейнер, поскольку пакет - это просто структура каталогов и файлов в соответствии с соглашениями Apple.

Одним из моих классов является ViewController, в котором есть метка и кнопка.как IBOutlets.Самый важный код в ViewController выглядит следующим образом:

TestViewController.h

@interface TestViewController : UIViewController {
   UIButton *button;
   UILabel *label;
}

@property (nonatomic, retain) IBOutlet UIButton *button;
@property (nonatomic, retain) IBOutlet UILabel *label;

- (IBAction)buttonTouched:(id)sender;

@end

TestViewController.m

@implementation TestViewController
@synthesize button, label;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

// the -init method is overridden to use nib file from bundle, if bundle exists ...
- (id)init 
{
   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
   NSString *documentsDirectory = [paths objectAtIndex:0];
   NSString *file = [documentsDirectory stringByAppendingPathComponent:@"template.bundle"];
   NSBundle *bundle = [NSBundle bundleWithPath:file];
   if (!bundle)
   {
      NSLog(@"no bundle found, falling back to default gui ...");
      return [self initWithNibName:nil bundle:nil];
   }

   NSString *nibName = NSStringFromClass([self class]);
   return [self initWithNibName:nibName bundle:bundle];
}

- (void)dealloc
{
   [button release];
   [label release];
   [view release];

   [super dealloc];
}

#pragma mark - View lifecycle

- (void)loadView
{
   if (self.nibName && self.nibBundle) 
   {
      // connect outlets to proxy objects ...
      NSDictionary *objects = [NSDictionary dictionaryWithObjectsAndKeys:
          self.label, @"label", 
          self.button, @"button", 
          nil];
      NSDictionary *proxies = [NSDictionary dictionaryWithObject:objects forKey:UINibExternalObjects];
      NSArray *nibs = [self.nibBundle loadNibNamed:self.nibName owner:self options:proxies]; // connection happens here ...

      NSLog(@"nibs found with name %@: %d", self.nibName, [nibs count]);
      return;
   }

   // show default gui if no nib was found ...

   CGRect frame = [UIScreen mainScreen].applicationFrame;
   self.view = [[[UIView alloc] initWithFrame:frame] autorelease];
   [self.view setBackgroundColor:[UIColor lightGrayColor]];

   self.button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
   [self.button setFrame:CGRectMake(0.0f, 0.0f, 60.0f, 30.0f)];
   [self.button setCenter:CGPointMake(160.0f, 100.0f)];
   [self.button addTarget:self action:@selector(buttonTouched:) forControlEvents:UIControlEventTouchUpInside];
   [self.view addSubview:self.button];

   self.label = [[[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 300.0f, 30.0f)] autorelease];
   [self.label setCenter:CGPointMake(160.0f, 50.0f)];
   [self.label setTextAlignment:UITextAlignmentCenter];
   [self.view addSubview:self.label];
}

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

   // for my purposes I'll add the localized string from the mainBundle here for the standard controls, 
   // this will override the text set in the nibs, since the nibs are loaded and displayed at this point ...
   [self.button setTitle:NSLocalizedString(@"TestButton", nil) forState:UIControlStateNormal];
   [self.label setText:NSLocalizedString(@"TestLabel", nil)];

}

- (void)viewDidUnload
{
   [super viewDidUnload];
   self.button = nil;
   self.label = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark -

- (IBAction)buttonTouched:(id)sender 
{
   [[[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"DialogTitle", nil) 
                                message:NSLocalizedString(@"ButtonTouchedText", nil) 
                               delegate:nil 
                      cancelButtonTitle:@"OK" 
                      otherButtonTitles:nil] 
     autorelease] show];
}

@end

Фактическое перо определено в отдельном связанном проекте (проект Cocoa NSBundle с некоторыми параметрами, измененными, чтобы он работал на устройствах iOS).Владелец файла - TestViewController, так что я могу получить доступ ко всем выходам и действиям и установить соответствующие подключения.Обратите внимание, что в TestViewController не определено свойство view (UIView *), поскольку суперкласс уже имеет свойство view .Убедитесь, что представление подключено в Интерфейсном Разработчике.Также обратите внимание, что для удобства использования в nib-файле используется то же имя, что и в самом классе.

Не удалось найти много информации в Интернете о том, как это сделать, поэтому я надеюсь, что это будет полезно для многих людей, имеющих схожие цели.

12 голосов
/ 01 июня 2011

не проверено.

Вы можете распространять все содержимое в zip-файле, распаковать его, используя SSZipArchive .

NSBundle* bundle = [NSBundle bundleWithPath:absolutePathToNibFile].

UIViewController* vc = [[[MyViewController alloc] initWithNibName:@"mycustomnib" bundle:bundle] autorelease];
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...