2014-09-22 2 views
-1

В настоящее время я пытаюсь загрузить файл plist с URL-адреса. Я не уверен, что способ, которым у меня установлен мой код, вызывает его сбой или если я что-то делаю неправильно.Загрузка plist из URL вместо файла

файл .m

#import "deptTableViewController.h" 

@interface deptTableViewController() 

@property (nonatomic, copy) NSDictionary *names; 

@property (nonatomic, copy) NSArray *keys; 

@property (nonatomic, strong) NSMutableArray *filterednames; 

@property (nonatomic, strong) UISearchDisplayController *searchController; 

@end 


@implementation deptTableViewController 

@synthesize names, keys, filterednames, searchController, searchNames; 

- (id)initWithStyle:(UITableViewStyle)style 
{ 
    self = [super initWithStyle:style]; 

    if (self) { 

     // Custom initialization 
    } 

    return self; 
} 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    UITableView *tableview = (id) [self.view viewWithTag:1]; 
    [tableview registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"]; 
    filterednames = [[NSMutableArray alloc]init]; 
    searchController = [[UISearchDisplayController alloc]init]; 
    searchController.searchResultsDataSource = self; 

    // This will get the plist into data format 
    NSData *dataReturn = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://morphinggamers.ca/staff.plist"]]; 
    NSString *path = [[NSBundle mainBundle]pathForResource:@"staff" ofType:@"plist"]; 
    names = [NSDictionary dictionaryWithContentsOfFile:path]; 

    keys = [[names allKeys]sortedArrayUsingSelector:@selector(compare:)]; 

    keys = [NSKeyedUnarchiver unarchiveObjectWithData:dataReturn]; 
} 

#pragma mark - Table view data source 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    if (tableView.tag == 1) { 

     return [keys count]; 
    } 
    else{ 

     return 1; 
    } 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ 

    if (tableView.tag == 1) { 

     NSString *key = keys[section]; 
     NSArray *keyValues = names[key]; 
     return [keyValues count]; 
    } 
    else { 

     return [filterednames count]; 
    } 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; 

    // Configure the cell... 
    if (tableView.tag == 1) { 

     names = keys[indexPath.row]; 

     NSString *teacherNames = names[@"teacherNames"]; 

     cell.textLabel.text = teacherNames; 
    } 
    else{ 
     cell.textLabel.text = filterednames [indexPath.row]; 
    } 
    return cell; 
} 

-(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{ 

    if (tableView.tag == 1) { 

     return keys[section]; 
    } 
    else{ 

     return nil; 
    } 

} 

#pragma mark - Search Display And Delegate Methods 

-(void)searchDisplayController:(UISearchDisplayController *)controller didLoadSearchResultsTableView:(UITableView *)tableView { 

    [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"]; 
} 

-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{ 

    [filterednames removeAllObjects]; 

    if (searchString.length > 0) { 

     NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains [search] %@", self.searchNames.text]; 

     for (NSString *key in keys) { 

      NSArray *matches = [names[key]filteredArrayUsingPredicate:predicate]; 

      [filterednames addObjectsFromArray:matches]; 

     } 
    } 
    return YES; 
} 

@end 
+0

Какая ошибка вы получаете? Что еще вы пытались решить проблему? – RyanR

+0

Я получаю (нить 1: сигнал SIGABRT). Я не очень много пробовал. Я не уверен, что так я закодировал вид таблицы, чтобы загрузить различные разделы, вызывающие его. – macguy3

+0

Ваш интервал * действительно * нуждается в помощи. Отправлено редактирование. В общем, пожалуйста, сделайте свой вопрос легко читаемым, чтобы людям не приходилось прокручивать 3 страницы пробелов. – rebello95

ответ

1

Вы можете использовать только initwithcontentsofurl с использованием локальных файлов (файлы на устройстве уже) Этот URL-адрес находится на сервере, так что вам нужно использовать сетевой запрос для извлечения данных из сервер.

NSURLRequest *request = [NSURLRequest requestWithURL:@"http://morphinggamers.ca/staff.plist"]; 
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { 
    NSDictionary *names = [NSPropertyListSerialization propertyListFromData:data mutabilityOption:0 format:0 errorDescription:nil]; 

    keys = [[names allKeys]sortedArrayUsingSelector:@selector(compare:)]; 

    keys = [NSKeyedUnarchiver unarchiveObjectWithData:dataReturn]; 
    //might want to reload the tableview 
    [self.tableview reloadData] 
}]; 
+0

Итак, я добавил его, и я возвращаюсь с ошибками и предупреждениями. Тема 1: EXC_BAD_ACCESS (код = 1, адрес = 0x7c8) – macguy3

+0

Есть еще некоторые проблемы с кодом, но мне показалось, что загрузка plist была основным недоразумением (хотя я могу понять, почему вы так думаете. NSURL используется как для локальных, так и для удаленных URL-адресов). Большая часть остатков - это просто правильный код шаблона для таблицы. – devgeek

+0

Я не знаю, почему я так думал. По какой-то причине я не собирался вместе. И какие еще проблемы вы видите? – macguy3

Смежные вопросы