React-native IOS приложение перестает работать при запуске, когда я перехожу с main.m на appdegelegate.swift - PullRequest
0 голосов
/ 16 февраля 2020

Я пытаюсь преобразовать appdelegate.h .m и main.m (файлы объективных c) в swift, создав appdelegate.swift (и, конечно, удалив эти файлы), но когда я делаю это, приложение выдает черный экран при запуске

вот код main.m

#import <UIKit/UIKit.h>

#import "AppDelegate.m"

int main(int argc, char * argv[]) {
@autoreleasepool {
 return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
 }
}

и appdelegate.m

#import "AppDelegate.h"

#import <React/RCTBridge.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
@import Firebase;

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary 
*)launchOptions
  {
 RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
 RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
                                               moduleName:@"doctor_react_app"
                                        initialProperties:nil];

 rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];

  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
 rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
 [self.window makeKeyAndVisible];
 [FIRApp configure];
 return YES;
 }

- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG
 return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" 
 fallbackResource:nil];
#else
 return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
}

@end

и вот код, который я пытаюсь использовать в appdelegate .swift

import UIKit
import PushKit
import Firebase
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?

 private func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        //Enable all notification type. VoIP Notifications don't present a UI but we will use this to show local nofications later
        let notificationSettings = UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil)

        //register the notification settings
        application.registerUserNotificationSettings(notificationSettings)

        //output what state the app is in. This will be used to see when the app is started in the background
        NSLog("app launched with state \(application.applicationState)")
        FirebaseApp.configure()
        return true
}

func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {

  //register for voip notifications
let voipRegistry = PKPushRegistry(queue: DispatchQueue.main)
voipRegistry.desiredPushTypes = Set([PKPushType.voIP])
  voipRegistry.delegate = self;


 }



  }
 extension AppDelegate: PKPushRegistryDelegate {

  func pushRegistry(_ registry: PKPushRegistry,
                    didUpdate pushCredentials: PKPushCredentials,
                    for type: PKPushType) {
    //print out the VoIP token. We will use this to test the notification.
    NSLog("voip token: \(pushCredentials.token)")
  }

  func pushRegistry(_ registry: PKPushRegistry,
                             didReceiveIncomingPushWith payload: PKPushPayload,
                             for type: PKPushType,
                             completion: @escaping () -> Void){
    let payloadDict = payload.dictionaryPayload["aps"] as? Dictionary<String, String>
    let message = payloadDict?["alert"]

    //present a local notifcation to visually see when we are recieving a VoIP Notification
    if UIApplication.shared.applicationState == UIApplication.State.background {

      let localNotification = UILocalNotification();
      localNotification.alertBody = message
      localNotification.applicationIconBadgeNumber = 1;
      localNotification.soundName = UILocalNotificationDefaultSoundName;

      UIApplication.shared.presentLocalNotificationNow(localNotification);
    }

    else {

      DispatchQueue.main.async(execute: { () -> Void in

        let alert = UIAlertController(title: "My Alert", message: "This is an alert.", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Default action"), style: .default, handler: { _ in
        NSLog("The \"OK\" alert occured.")
        }))

 //            alert.show()
      })
    }

    NSLog("incoming voip notfication: \(payload.dictionaryPayload)")
  }
  func pushRegistry(_ registry: PKPushRegistry,
                             didInvalidatePushTokenFor type: PKPushType) {

    NSLog("token invalidated")
  }
 }

1 Ответ

0 голосов
/ 16 февраля 2020

Здесь можно попробовать 2 вещи: -

1: установить Root -View-Controller в didFinishLaunchingWithOptions

2: в iOS 13 Apple представила новый класс называется SceneDelegate, поэтому все вещи, связанные с окном, вы должны реализовать здесь и сейчас SceneDelegate класс расширяет UIResponder, поэтому просто установите root view controller в этой функции SceneDelegate class: -

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    //set root vc here
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...