У меня есть приложение iOS с расширением watchOS, оба из которых встроены в Objective-C. Приложение должно отправить по массиву при загрузке (viewDidLoad
) или появится (viewDidAppear:(BOOL)animated
). Когда приложение загружается, ничего не происходит, но если я каким-то образом добавлю файл в приложение (либо через встроенный сумматор, либо импортируя его с моего рабочего стола или AirDrop), приложение часов обновится. Нажатие кнопки обновления не делает работу приложения. Однако, как только я добавляю файл, он прекрасно обновляется и прекрасно обновляется. Я не знаю, почему это происходит, но вот какой-то код, который я использовал. Я вырезал несколько менее полезный код.Информация, не отправляющая Apple Watch на viewDidLoad
В viewDidLoad
:
- (void)viewDidLoad
{
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *appFolderPath = [path objectAtIndex:0];
NSString *inboxAppFolderPath = [appFolderPath stringByAppendingString:@"/Inbox"]; //changes the directory address to make it for the inbox
//move all files from inbox to documents root
//get to inbox directory
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSArray *inboxContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[NSString stringWithFormat:inboxAppFolderPath,documentsDirectory] error:nil];
//move all the files over
for (int i = 0; i != [inboxContents count]; i++)
{
NSString *oldPath = [NSString stringWithFormat:@"%@/%@", inboxAppFolderPath, [inboxContents objectAtIndex:i]];
//NSLog(oldPath);
NSString *newPath = [NSString stringWithFormat:@"%@/%@", appFolderPath, [inboxContents objectAtIndex:i]];
//NSLog(newPath);
NSError* error;
[[NSFileManager defaultManager] moveItemAtPath:oldPath toPath:newPath error:&error];
NSLog(@"error: %@", error.localizedDescription);
}
//end of moving all files
//Turn every file inside the directory into an array
//add directory in case it doesn't already exist
if (![[NSFileManager defaultManager] fileExistsAtPath: inboxAppFolderPath])
{
[[NSFileManager defaultManager] createDirectoryAtPath: inboxAppFolderPath withIntermediateDirectories:NO attributes:nil error:nil];
NSLog(@"directory created");
}
//a bunch of NSPredicates go here to filter out the array
[self sendStuffToWatch];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self connectToWatch];
}
В -(void)connectToWatch
есть
-(void)connectToWatch
{
//set up WatchConnectivity session
if([WCSession isSupported])
{
self.watchSession = [WCSession defaultSession];
self.watchSession.delegate = self;
[self.watchSession activateSession];
if([WCSession defaultSession].paired){
NSLog(@"Watch session active");
}
else
{
NSLog(@"WATCH NOT CONNECTED");
}
}
}
В -(void)sendStuffToWatch
-(void)sendStuffToWatch
{
if(self.watchSession)
{
NSError *error;
NSDictionary *applicationDict = @{@"array":recipes};
[self.watchSession updateApplicationContext:applicationDict error:&error];
NSLog(@"sent info to watch");
}
}
В -(void)viewDidAppear:(BOOL)animated
, есть только этот
-(void)viewDidAppear:(BOOL)animated
{
[self sendStuffToWatch];
}
Код для кнопки Обновить
-(IBAction)Refresh:(id)sender
{
[recipeTable reloadData];
[self sendStuffToWatch];
[self viewDidLoad];
}
Кроме того, если вы хотите принудительно загружать 'view' и вызывать' viewDidLoad', вы можете вызвать 'loadViewIfNeeded'. – EmilioPelaez
К сожалению, это не сработало, но для вызова '' viewDidLoad'' в кнопке обновления, где мне нужно перезагрузить все, нужно взять/все/из '' viewDidLoad'' и вставить все это в свои собственные методы? – JustMe
Да (все, кроме вызова супер). Поскольку он не работает, вы должны иметь возможность использовать отладчик, выполнять свой код и следить за тем, чтобы ошибки не возникали. Поскольку он не работает изначально, но работает, когда вы добавляете файл, тогда что-то не настроено или не готово при первом запуске. Вы только должны выяснить, какая часть вызывает проблему. –