APNS仅显示一个待处理的通知

时间:2018-11-02 05:21:17

标签: ios swift apple-push-notifications apns-php unnotificationserviceextension

我已经为我的ios应用成功实现了推送通知服务。我已经生成了所需的证书,并且代码可以正常工作。当设备断开与互联网的连接并接收到一些通知(正在等待并且未显示)时,然后再将设备重新连接到互联网时,就会出现问题...仅其中一个待处理的 apns 显示推送通知。我将 php 用于后端,将NotificationServiceExtension用于附件等。

这是我的php代码

public static function sendAPNS($token,$data)
    {
      print_r($token);
      $apnsServer = 'ssl://gateway.push.apple.com:2195';
      $privateKeyPassword = 'password-here';
      /* Device token */
      $deviceToken = $token;
      $pushCertAndKeyPemFile = 'nameofthefile.pem';
      $stream = stream_context_create();
      stream_context_set_option($stream, 'ssl', 'passphrase', $privateKeyPassword);
      stream_context_set_option($stream, 'ssl', 'local_cert', $pushCertAndKeyPemFile);
      $connectionTimeout = 20;
      $connectionType = STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT;
      $connection = stream_socket_client($apnsServer, $errorNumber, $errorString, $connectionTimeout, $connectionType, $stream);




        /*Alert array eg. body, title etc */
      $alertArray = [];
      $alertArray["body"] = $data["body"];
      $alertArray["title"] =$data["title"];


      $messageBody['aps'] = array(
        'alert' => $alertArray,
        'sound' => 'default',
        'category'=> 'customUi',
        'mutable-content'=>1

      );
      /*User Info*/
      $messageBody["attachment-url"] = $data["url"];
      $messageBody["type_code"] = $data["type_code"];
      $messageBody["ref_id"] = $data["ref_id"];
      $messageBody["user_to"] =$data["user_to"];

      /*Could be here*/



      $payload = json_encode($messageBody);

       print_r($payload);
      $notification = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
      $wroteSuccessfully = fwrite($connection, $notification, strlen($notification));


      fclose($connection);
    }

我的服务扩展如下:-

class NotificationService: UNNotificationServiceExtension {

var contentHandler: ((UNNotificationContent) -> Void)?
var bestAttemptContent: UNMutableNotificationContent?

override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
    self.contentHandler = contentHandler
    bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)

    if let bestAttemptContent = bestAttemptContent {


        var defaultsUser: UserDefaults = UserDefaults(suiteName: "group.shared.com.plates215")!
        if let countNot = defaultsUser.value(forKey: "notUniversal")
        {
            var   IntcountNot = countNot as! Int
            IntcountNot = IntcountNot + 1
            var sum: NSNumber = NSNumber(value: IntcountNot)
            bestAttemptContent.badge = sum
            defaultsUser.set(IntcountNot, forKey: "notUniversal") 

        }

        if let photo = bestAttemptContent.userInfo["attachment-url"] as? String
        {
            updateReadNots(userID: (bestAttemptContent.userInfo["user_to"] as? String)!)
            let url = NSURL(string: photo);
            var err: NSError?
            var imageData :NSData = try! NSData(contentsOf: url! as URL)
            var bgImage = UIImage(data:imageData as Data)

            if let attachment = UNNotificationAttachment.create(identifier: "colo", image: bgImage!, options: nil)
            {
                bestAttemptContent.attachments = [attachment]
                contentHandler(bestAttemptContent)
            }


        }




    }

}


override func serviceExtensionTimeWillExpire() {
    // Called just before the extension will be terminated by the system.
    // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
    if let contentHandler = contentHandler, let bestAttemptContent =  bestAttemptContent {
        contentHandler(bestAttemptContent)
    }
}
func updateReadNots(userID: String)
{
    var url: String = "api-url"
    let session: URLSession = URLSession(configuration: URLSessionConfiguration.default)
    var urlDown = URL(string: url)
    let downloadTask = session.downloadTask(with: urlDown!) { (url, rsp, error) in


    }
    downloadTask.resume()


}

     }

    extension UNNotificationAttachment {

static func create(identifier: String, image: UIImage, options: [NSObject : AnyObject]?) ->  UNNotificationAttachment? {
    let fileManager = FileManager.default
    let tmpSubFolderName = ProcessInfo.processInfo.globallyUniqueString
    let tmpSubFolderURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(tmpSubFolderName, isDirectory: true)
    do {
        try fileManager.createDirectory(at: tmpSubFolderURL, withIntermediateDirectories: true, attributes: nil)
        let imageFileIdentifier = identifier+".png"
        let fileURL = tmpSubFolderURL.appendingPathComponent(imageFileIdentifier)
        guard let imageData = UIImagePNGRepresentation(image) else {
            return nil
        }
        try imageData.write(to: fileURL)
        let imageAttachment = try UNNotificationAttachment.init(identifier: imageFileIdentifier, url: fileURL, options: options)
        return imageAttachment
    } catch {
        print("error " + error.localizedDescription)
    }
    return nil
}
  }

解决方案
 根据@Li Sim的链接,这就是我所做的……每一次通知我  从我的服务器发送的邮件不仅包含最新的通知,还包含  每个未读的通知均以“ \ n”分隔。然后ios  通知会正确显示它们。跟踪已读和未读  通知,我的back_end中有一个read_status键  通知在收到后立即更新   NotificationContentExtension  (https://developer.apple.com/documentation/usernotifications/unnotificatio nserviceextension)。它用于修改内容并执行一些代码  每当收到apns推送时。希望这对以后的人有帮助   :)

1 个答案:

答案 0 :(得分:0)

这是Apple以前记录的行为。 链接到文档:https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/APNSOverview.html#//apple_ref/doc/uid/TP40008194-CH8-SW1

  

如果设备离线,则发送针对该设备的通知请求会导致先前的请求被丢弃。如果设备长时间保持离线状态,则其在APN中存储的所有通知都将被丢弃。

尽管我对此并不熟悉,(对此感到抱歉),但我发现一些对您的问题有用的帖子: How does whatsapp receive multiple notification when APNS stores only one in case device is offline?

希望您能从中学到一些东西。我可以想到的另一种方法是使用与脱机兼容的LocalNotifications,但您必须找出一种方法来跟踪用户未读取的通知。 (也许是某种状态)