【问题标题】:Passing notification data from App Delegate to View Controller with NSNotificationCenter using Swift 3 and Obj C使用 Swift 3 和 Obj C 使用 NSNotificationCenter 将通知数据从 App Delegate 传递到 View Controller
【发布时间】:2017-09-02 17:28:21
【问题描述】:

我在我的 AppDelegate 中成功地从远程通知负载 userInfo 接收数据。现在我正在尝试从 Storyboard 推送到视图控制器,将数据传递给它,并使用 NSNotificationCenter 更新变量但收到错误:

Fatal error: unexpectedly found nil while unwrapping an Optional values

在viewDidLoad。谢谢参观!

(ObjC) AppDelegate.m

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
         withCompletionHandler:(void (^)())completionHandler
{
    NSDictionary *userInfo = response.notification.request.content.userInfo;
    NSDictionary *roomKey = [[[userInfo objectForKey:@"custom"] objectForKey:@"a"] objectForKey:@"roomKey"];
    NSLog(@"%@", roomKey);
    // Successfully prints correct roomKey, now need to pass to view controller and update variable. 

    [[NSNotificationCenter defaultCenter] postNotificationName:@"pushToFollowers" object:nil userInfo:roomKey];

    self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"main" bundle:nil];
    UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:@"audience"];
    self.window.rootViewController = viewController;

    // line below is involved in optional crash
    [self.window makeKeyAndVisible];
}

(斯威夫特 3)VC:

import UIKit
import SocketIO
import IHKeyboardAvoiding

@objc class AudienceViewController: UIViewController {

    @IBOutlet weak var previewView: UIView!
    @IBOutlet weak var statusLabel: UILabel!

    var room: Room!

    var player: IJKFFMoviePlayerController!
    let socket = SocketIOClient(socketURL: URL(string: Config.serverUrl)!, config: [.log(true), .forcePolling(true)])

    var overlayController: LiveOverlayViewController!

    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(self.notificationArrived(_:)), name: NSNotification.Name(rawValue: "pushToFollowers"), object: nil)
        // Optional error occurs on next line
        let urlString = Config.rtmpPlayUrl + room.key
        player = IJKFFMoviePlayerController(contentURLString: urlString, with: IJKFFOptions.byDefault())
        player.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        player.view.frame = previewView.bounds
        previewView.addSubview(player.view)
        player.prepareToPlay()
        socket.on("connect") {[weak self] data, ack in
            self?.joinRoom()
        }
    }

    // function isn't firing
    @objc func notificationArrived(_ notification: NSNotification) {
        print(notification.userInfo!)
        if let custom = notification.userInfo?["custom"] as? [String: Any] {
            if let a = custom["a"] as? NSDictionary {
                if let roomKey = a["roomKey"] as? String {
                    print(roomKey)
                    room.key = (roomKey) as String
                }
            }
        }
    }
}

【问题讨论】:

    标签: ios objective-c swift


    【解决方案1】:

    您在视图控制器调用viewDidLoad() 并成为观察者之前发布通知方式。这就是notificationArrived(_:) 方法不触发的原因。 但实际上发生崩溃是因为您在尝试使用之前没有初始化room 属性。

    因此,当它尝试访问room.key 时,不仅没有设置键值,room 也没有启动。

    您可以做的是创建一个 Room 实例,并在您从情节提要实例化它之后将其传递给 AudienceViewController 属性,然后在控制器的视图加载后然后使用它.

    AppDelegate.m

    UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:@"audience"];
    Room *room = ... ; // create a room
    room.key = roomKey;
    viewController.room = room;
    

    AudienceViewController

    @objc class AudienceViewController: UIViewController {
    
        ...
    
        @objc var room: Room!
    
        ...
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // if you are not planning on reusing this view controller for other rooms
            // then there's no reason for it to become an observer 
            let urlString = Config.rtmpPlayUrl + room.key
            ...
        }
    
        // notificationArrived(_:) is not needed anymore
    }
    

    【讨论】:

    • 感谢@lësha-turkowski 的帮助!实施您的解决方案需要一些时间,因为我正在学习 iOS,并且必须解决另一个问题才能使其正常工作。在我的 model.swift 文件中,我必须重写一个 swift Struct,以便它对目标 c 可见。如果对其他人有帮助,请使用以下代码:
    • struct Room { var key: String var title: String init(dict: [String: AnyObject]) { title = dict["title"] as! String key = dict["key"] as! String } func toDict() -> [String: AnyObject] { return [ "title": title as AnyObject, "key": key as AnyObject ] } } 转换为 -->
    • @objc public class Room: NSObject { var key: String = "" var title: String = "" convenience init(dict: [String: AnyObject]) { self.init() title = dict["title"] as! String key = dict["key"] as! String } func toDict() -> [String: AnyObject] { return [ "title": title as AnyObject, "key": key as AnyObject ] } }
    猜你喜欢
    • 1970-01-01
    • 2023-01-24
    • 2019-06-15
    • 1970-01-01
    • 2020-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多