菜鸟教程小白 发表于 2022-12-12 16:11:49

ios - NSNotificationCenter 和 didReceiveRemoteNotification


                                            <p><p>我在使用 NSNotificationCenter 和 didReceiveRemoteNotification 时遇到了一些问题。当我收到来自 APNS 的新通知时,我想打开我的 ViewController。内部通知我有 objectId - 这是关键。
我尝试将 ViewController 打开到 didReceiveRemoteNotification 但它不起作用((</p>

<p>AppDelegate.m</p>

<pre><code> - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{   
    [
postNotificationName:kDidReceiveRemoteNotification
object:userInfo];
}
</code></pre>

<p>NewsDetailViewController.m</p>

<pre><code>- (void)viewDidLoad {
;
[
addObserver:self
selector:@selector(didReceiveRemoteNotification:)
name:kDidReceiveRemoteNotification
object:nil];
}

- (void)didReceiveRemoteNotification:(NSNotification *)notification
{
NSLog(@&#34;%s %@&#34;,__func__,);
}
</code></pre>

<p>常量.h</p>

<pre><code>#define kDidReceiveRemoteNotification @&#34;UIApplicationDidReceiveRemoteNotification&#34;
</code></pre>

<p>ViewController 未加载。我不知道该怎么办。</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>您附加的示例代码的当前流程是:</p>

<ol>
<li>收到推送通知时,向 NSNotificationCenter 发布通知(与推送通知完全不同且无关的东西)。</li>
<li>当另一个 View 被加载时(有人需要在收到推送通知之前加载这个 View ),订阅这个 NSNotificationCenter 通知。</li>
<li>发布通知后,将其打印到日志中。</li>
</ol>

<p>我很难从您的问题中理解这一点,但是如果您因收到推送通知而尝试启动的 ViewController 是 NewsDetailViewController,那么您的代码不会这样做。您的代码所做的是打印要记录的通知(假设其他人确保在收到推送通知之前已加载 NewsDetailViewController)。</p>

<p>为了在收到推送通知时加载 NewsDetailViewController,您不需要将通知发布到 NSNotification</p>

<pre><code>- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{   
    NewsDetailViewController *newsVC = [ initWithNibName:@&#34;NewsDetailViewController&#34; bundle:nil];
    ;
}
</code></pre>

<p>或任何其他更适合您的加载逻辑。但是在您发布的当前代码中,接收推送通知和加载 ViewController 之间没有任何联系。</p>

<p>我希望这会有所帮助。祝你好运!</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - NSNotificationCenter 和 didReceiveRemoteNotification,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/32260282/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/32260282/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - NSNotificationCenter 和 didReceiveRemoteNotification