首页 > 解决方案 > 如何在后台禁用 Cordova webview?(仅限 iOS)

问题描述

我正在开发一个 iOS Cordova 应用程序,该应用程序在后台启动以处理位置事件。这工作正常,但我注意到当应用程序在后台启动时,webview 被初始化并且我的整个应用程序被渲染。我有处理后台启动的所有逻辑,所以我可以(希望)避免渲染 UI 和运行 Javascript 端。

我想我可以通过将MainViewController创建包装在一个if语句中来禁用 webview,但这似乎不起作用(我知道 webview 正在运行,因为它正在发送 HTTP 请求)。

这是我的AppDelegate.m

#import "AppDelegate.h"
#import "MainViewController.h"
#import "AppName-Swift.h"

@implementation AppDelegate {
  LocationSyncManager* locationSyncManager;
}

- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
    bool isLocationLaunch = launchOptions[@"location"] == nil ? false : launchOptions[@"location"];
    NSString* serverAddress = @"http://192.168.1.61:9090/api/notes/nearby";
    locationSyncManager = [LocationSyncManager create: serverAddress isLocationLaunch: isLocationLaunch];

    // Don't render the webview if the app is launched in the background by a location event
    if(!isLocationLaunch) {
      self.viewController = [[MainViewController alloc] init];
    }
    return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

@end

标签: iosobjective-ccordova

解决方案


想通了问题:

isLocationLaunch总是false因为我检查位置启动标志错误。

此外,为了防止 Cordova 渲染/运行 javascript,我必须避免super didFinishLaunchingWithOptions在位置启动期间被调用。

这有效:

#import "AppDelegate.h"
#import "MainViewController.h"
#import "AppName-Swift.h"

@implementation AppDelegate {
  LocationSyncManager* locationSyncManager;
}

- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{

    bool isLocationLaunch = [launchOptions objectForKey:UIApplicationLaunchOptionsLocationKey];

    NSString* serverAddress = @"http://192.168.1.61:9090/api/notes/nearby";
    locationSyncManager = [LocationSyncManager create: serverAddress isLocationLaunch: isLocationLaunch];

    if(!isLocationLaunch) {
      self.viewController = [[MainViewController alloc] init];
      return [super application:application didFinishLaunchingWithOptions:launchOptions];
    }
    return nil;
}

@end

推荐阅读