2014-11-12 4 views
4

Я работаю над расширением общего доступа, чтобы просто захватить ссылку, выбрать несколько имен, чтобы поделиться им, и поделиться. Уровень данных еще не добавлен, только пользовательский интерфейс отображает некоторые имена в представлении таблицы (используя пользовательскую ячейку), и я вынимаю общий URL из контекста расширения. Весь код в VC приведен ниже. Все виды настроены в Раскадке. Два UIButtons, Two UILabels, One TableView и UIView, чтобы держать все это, поэтому я могу легко обойти углы.Slow iOS Share Extension

enter image description here

Проблема у меня в том, что _linkLabel что я использую дисплей URL, визуально не обновлять почти 10 секунд! Что в мире. Что я здесь делаю, это вызывает это?

Я выхожу из URL-адреса в обратном вызове от hasItemConformingToTypeIdentifier, и это происходит, как только расширение появляется, но не обновляет метку ?? !! Помогает. Пожалуйста.

#import "ShareViewController.h" 
#import "UserCell.h" 

@interface ShareViewController() 

@end 

@implementation ShareViewController 

- (void)viewDidLoad{ 
    self.view.alpha = 0; 
    _friends = [@[@"Ronnie",@"Bobby",@"Ricky",@"Mike"] mutableCopy]; 
    _containerView.layer.cornerRadius = 6.f; 
    _selectedIndexPaths = [[NSMutableArray alloc] init]; 
} 

- (void)viewWillAppear:(BOOL)animated 
{ 
    [super viewWillAppear:animated]; 
    [UIView animateWithDuration:0.5 animations:^{ 
     self.view.alpha = 1; 
    }]; 
} 

- (void)viewDidAppear:(BOOL)animated{ 
    //pull the URL out 
    NSExtensionItem *item = self.extensionContext.inputItems[0]; 
    NSItemProvider *provider = item.attachments[0]; 
    if ([provider hasItemConformingToTypeIdentifier:@"public.url"]) { 
     [provider loadItemForTypeIdentifier:@"public.url" options:nil completionHandler:^(id<NSSecureCoding> item, NSError *error) { 
      NSURL *url = (NSURL*)item; 
      _linkLabel.text = url.absoluteString; 
      NSLog(@"Link: %@", url.absoluteString); 
     }]; 
    } 
    else{ 
     NSLog(@"No Link"); 
    } 
} 

#pragma mark - UITableView Delegate Methods 
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ 
    UserCell *cell = (UserCell*)[tableView cellForRowAtIndexPath:indexPath]; 
    if([_selectedIndexPaths containsObject:indexPath]){ 
     [_selectedIndexPaths removeObject:indexPath]; 
     cell.selected = NO; 
    } 
    else{ 
     cell.selected = YES; 
     [_selectedIndexPaths addObject:indexPath]; 
    } 
    NSLog(@"Share to %i friends", (int)[_selectedIndexPaths count]); 
} 

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ 
    //Later, calc height based on text in comment 
    return 44; 
} 
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ 
    return [_friends count]; 
} 
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 
    static NSString *CellIdentifier = @"UserCell"; 
    UserCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if(cell == nil){ 
     cell = [[UserCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    } 
    cell.selected = ([_selectedIndexPaths containsObject:indexPath]) ? YES : NO; 
    cell.nameLabel.text = [_friends objectAtIndex:indexPath.row]; 
    return cell; 
} 

- (IBAction)dismiss { 
    [UIView animateWithDuration:0.34 animations:^{ 
     self.view.alpha = 0; 
    } completion:^(BOOL finished) { 
     [self.extensionContext completeRequestReturningItems:nil completionHandler:nil]; 
    }]; 
} 

@end 

ответ

7

Задержки в обновлениях элементов пользовательского интерфейса являются классическим признаком попытки обновления пользовательского интерфейса из-за пределов главной очереди. Это то, что происходит здесь. У вас есть это:

[provider loadItemForTypeIdentifier:@"public.url" options:nil completionHandler:^(id<NSSecureCoding> item, NSError *error) { 
    NSURL *url = (NSURL*)item; 
    _linkLabel.text = url.absoluteString; 
    NSLog(@"Link: %@", url.absoluteString); 
}]; 

Кроме того NSItemProvider не гарантирует, что обработчик завершения будет называться по одной и той же очереди, что вы начали. Вы почти гарантированно находитесь в другой очереди, так что вы получаете эту странную задержку. Вам необходимо отправить обратно в основную очередь, чтобы произвести обновление:

[provider loadItemForTypeIdentifier:@"public.url" options:nil completionHandler:^(id<NSSecureCoding> item, NSError *error) { 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     NSURL *url = (NSURL*)item; 
     _linkLabel.text = url.absoluteString; 
     NSLog(@"Link: %@", url.absoluteString); 
    }); 
}]; 
+0

Это сделало это :) Отличный ответ Tom – d2burke

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