0

firebase 클라우드 기능을 사용하여 사용자 푸시 알림을 보내고 있습니다. JS는 잘 이해하지 못하지만 알림 페이로드를 통해 앱 배지 번호를 자동으로 증가시키고 각 알림이 수신 될 때마다 1 씩 숫자를 늘릴 수 있기를 바랍니다. 이것은 내가 지금 가지고있는 것입니다. 나는 firebase에 대한 문서를 읽었으나 그들이 묘사하고있는 것을 이해하기에 충분한 JS 이해가 없다고 생각한다.수신 한 푸시 알림에 대한 앱 배지 번호를 늘리는 방법

exports.sendPushNotificationLikes = functions.database.ref('/friend-like-push-notifications/{userId}/{postId}/{likerId}').onWrite(event => { 
const userUid = event.params.userId; 
const postUid = event.params.postId; 
const likerUid = event.params.likerId; 
if (!event.data.val()) { 
    return; 
} 

// const likerProfile = admin.database().ref(`/users/${likerUid}/profile/`).once('value'); 

const getDeviceTokensPromise = admin.database().ref(`/users/${userUid}/fcmToken`).once('value'); 

// Get the follower profile. 
const getLikerProfilePromise = admin.auth().getUser(likerUid); 

return Promise.all([getDeviceTokensPromise, getLikerProfilePromise]).then(results => { 
    const tokensSnapshot = results[0]; 
    const user = results[1]; 

    if (!tokensSnapshot.hasChildren()) { 
     return console.log('There are no notification tokens to send to.'); 
    } 

    const payload = { 
     notification: { 
      title: 'New Like!', 
      body: '${user.username} liked your post!', 
      sound: 'default', 
      badge: += 1.toString() 
     } 
    }; 

    const tokens = Object.keys(tokensSnapshot.val()); 

    // Send notifications to all tokens. 
    return admin.messaging().sendToDevice(tokens, payload).then(response => { 
      // For each message check if there was an error. 
      const tokensToRemove = []; 
     response.results.forEach((result, index) => { 
      const error = result.error; 
     if (error) { 
      console.error('Failure sending notification to', tokens[index], error); 
      // Cleanup the tokens who are not registered anymore. 
      if (error.code === 'messaging/invalid-registration-token' || 
       error.code === 'messaging/registration-token-not-registered') { 
       tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove()); 
       } 
      } 
     }); 
     return Promise.all(tokensToRemove); 
    }); 
}); 

}); 형식 변환 가정의

badge: += 1.toString() 

주의 : 어떤 도움이 가정

답변

0

에 미리

감사는 문제의 라인입니다. "1"+ "1"을 추가하면 "2"가 아니라 "11"이됩니다. 다음과 같이 시도해보십시오.

badge: `${targetUser.notificationCount + 1}` 

이것은 notificationCount가 스키마의 키이고 문자열로 입력되었다고 가정합니다. . 당신은 또한 정수가 될 수있는 새로운 통지가 오면이 증가 할 수 있습니다 어딘가에 있도록 대상 사용자의 알림 수를 유지해야합니다 다음 문자열 보간 즉, 불필요 : 또한

badge: targetUser.notificationCount + 1 

, 인식 당신의 문자열 보간 여기에, 대신 작은 따옴표의 역 따옴표에 싸여 될 필요가 있다고 예 :

body: `${user.username} liked your post!` 

나는 상호 작용이 데이터베이스에 매핑되는 방법을 말할 수 없다. 이 방법을 사용하려면 대상 사용자의 알림 수를 유지하고 업데이트해야합니다. 나는이 추측하고있어

+0

임 확실하지 무슨 말인지 이해 따옴표, 즉 : " 아직 포장되지 않았습니까? 하지만 네, 이것은 사용자 이름 대신에 "undefined"를주었습니다. – Chris

+0

위의'''body'' 값에 대한 예제에서 작은 따옴표를 사용하고 있습니다. '''{{}''''는 보통 문자열로 취급됩니다. 문자열 보간이 작동하려면 백 탭 (Tab 키 위)을 사용해야합니다. ('vs ') IDE를 사용한다면,'''{{}'''안에있는 물건의 강조 표시 역시 변경되어야합니다. [MDN docs 템플릿 리터럴] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) – DILP

1

은 문제가 무엇인지입니다 :에 또한

const payload = { 
    notification: { 
     title: 'New Like!', 
     body: `${user.username} liked your post!`, 
     sound: 'default', 
     badge: Number(notificationCount++) // => notificationCount + 1 
    } 
}; 

:

const payload = { 
    notification: { 
     title: 'New Like!', 
     body: '${user.username} liked your post!', 
     sound: 'default', 
     badge: += 1.toString() 
    } 
}; 

다음 당신이 할 수있는 당신이 당신의 스키마에서 사용할 수있는 알림 카운트 속성이 notificationCount을 말 가정 이 body: '${user.username} liked your post!'이면 "user.username like your post!"으로 저장됩니다. 이것은 당신이 일을해야하는 것은 이것이다, 당신이 원하는 동작되지 않습니다 : "또한, 여기 당신의 문자열 보간 단일 대신 역 따옴표에 싸여 될 필요가 있다는 인식 :

body: `${user.username} liked your post!`