2016-07-28 57 views
2

我試圖檢測我的反應原生應用是否由用戶點擊推送通知橫幅(有關主題,請參閱this excellent SO answer)啓動。如何使用react-native的PushNotificationIOS.getInitialNotification

我已經實現了Mark描述的模式,並且發現PushNotificationIOS.getInitialNotification提供的「通知」對象真的很奇怪,至少在沒有檢索通知的情況下。檢測到這種情況一直是PITA,我實際上很困惑。

從我所知道的,PushNotificationIOS.getInitialNotification返回一個承諾;這個承諾應該在null或實際的通知對象 - null當沒有通知等待用戶時解決。這是我試圖檢測和支持的場景。

這就是爲什麼檢測是如此痛苦;以下測試全部在沒有通知的情況下運行:

// tell me about the object 
JSON.stringify(notification); 
//=> {} 

// what keys does it have? 
Object.keys(notification); 
//=> [ '_data', '_badgeCount', '_sound', '_alert' ] 

因此,它被串化爲空,但它有四個鍵? ķ...

// tell me about the data, then 
JSON.stringify(notification._data); 
//=> undefined 
// wtf? 

這些怪異的事實阻撓我都瞭解,我這裏有一個實際的通知作出反應,對情況的郵箱是空箱之間的辨別能力。基於這些事實,我以爲我可以測試我想要的成員,但即使是最仔細的探測產生誤報的100%的時間:

PushNotificationIOS.getInitialNotification() 
.then((notification) => { 

    // usually there is no notification; don't act in those scenarios 
    if(!notification || notification === null || !notification.hasOwnProperty('_data')) { 
     return; 
    } 

    // is a real notification; grab the data and act. 

    let payload = notification._data.appName; // TODO: use correct accessor method, probably note.data() -- which doesn't exist 
    Store.dispatch(Actions.receivePushNotification(payload, true /* true = app was awaked by note */)) 
}); 

我每次運行此代碼,它未能觸發因爲undefined is not an object (evaluating 'notification._data.appName')逃生艙口蓋和let payload

有人可以解釋這裏發生了什麼嗎? PushNotificationIOS.getInitialNotification已損壞或已棄用?如何在JS中可以有一個評估爲未定義的鍵?我如何檢測這種情況?

經驗豐富的javascripter,在這裏很困惑。謝謝你的幫助。

BTW:使用反應母語v0.29.0

回答

2

notificationan instance ofPushNotification,而不是一個簡單的對象,這就是爲什麼它stringifies到一個空的對象,因爲沒有自定義的toString是爲它實施。

這聽起來像是一個錯誤(應該報告,如果不是已經),當沒有通知可用時創建該對象。

總之,要解決此問題,您的支票實際上應該是:

if(!notification || !notification.getData()) { 
     return; 
} 

更新:問題已被固定在0.31 - 看Github issue瞭解更多詳情。

+0

感謝您的解釋!我很好奇你如何知道'PushNotification'沒有'toString'。 – Tom