通过AWS SNS发送和接收推送通知

时间:2015-07-10 07:04:02

标签: ios swift amazon-web-services push-notification amazon-sns

我一直在尝试创建一个应用程序,以便通过AWS SNS发送和接收推送通知。我是API的新手,无法找到可靠的教程。以下是我为了发送和接收通知而提出的功能:

func subscribe(deviceTokenString : String)
{
    let credentialsProvider : AWSStaticCredentialsProvider = AWSStaticCredentialsProvider(accessKey: AWSAccessKey, secretKey: AWSSecretKey)
    let defaultServiceConfiguration : AWSServiceConfiguration = AWSServiceConfiguration(region: DefaultServiceRegionType, credentialsProvider: credentialsProvider)
    AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = defaultServiceConfiguration

    let sns = AWSSNS.defaultSNS()

    let subscribeInput = AWSSNSSubscribeInput()

    subscribeInput.topicArn = SNSTopicARN

    sns.subscribe(subscribeInput).continueWithBlock
    {
        (task) -> AnyObject! in
        if task.error != nil
        {
            print("Subscribed successfully")
            let confirmSubscription = AWSSNSConfirmSubscriptionInput()
            confirmSubscription.topicArn = SNSTopicARN
            confirmSubscription.token = deviceTokenString
            sns.confirmSubscription(confirmSubscription).continueWithBlock
            {
                (task) -> AnyObject! in
                if task.error != nil
                {
                    print("Confirmed subscription")
                    self.sendMessage()
                }
                else
                {
                    print("Subscription confirmation failed with error: \(task.error)")
                }
                return nil
            }
        }
        else
        {
            print("Error while subscribing: \(task.error)")
        }
        return nil
    }

}

func sendMessage()
{
    let sns = AWSSNS.defaultSNS()
    let request = AWSSNSPublishInput()
    request.messageStructure = "json"

    let dict = ["default": "Hello World!", "APNS_SANDBOX": "{\"aps\":{\"alert\": \"HELLO WORLD!\",\"sound\":\"default\", \"badge\":\"1\"} }"]

    do
    {
        let jsonData = try NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions.PrettyPrinted)
        request.message = NSString(data: jsonData, encoding: NSUTF8StringEncoding) as! String
        request.topicArn = SNSTopicARN
        sns.publish(request).continueWithBlock
        {
            (task) -> AnyObject! in
            if task.error != nil
            {
                print("Error sending mesage: \(task.error)")
            }
            else
            {
                print("Success sending message")
            }
            return nil
        }
    }
    catch
    {
        print("Error on json serialization: \(error)")
    }

}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData)
{
    let deviceTokenString = "\(deviceToken)"
        .stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString:"<>"))
        .stringByReplacingOccurrencesOfString(" ", withString: "")
    print("deviceTokenString: \(deviceTokenString)")
    subscribe(deviceTokenString)
}

一切似乎都运行良好,我在控制台上获得了“已成功订阅”,“已确认订阅”和“已发送消息”日志,但application:didReceiveRemoteNotificationuserInfo:永远不会被调用。我做错了什么?

1 个答案:

答案 0 :(得分:5)

我发现我错过了一些观点。这段代码完美无缺。

func subscribe(token : String, completionHandler : ((NSError?) -> ())? = nil)
{
    let credentialsProvider : AWSStaticCredentialsProvider = AWSStaticCredentialsProvider(accessKey: AWSAccessKeySend, secretKey: AWSSecretKeySend)
    let defaultServiceConfiguration : AWSServiceConfiguration = AWSServiceConfiguration(region: DefaultServiceRegionType, credentialsProvider: credentialsProvider)

    AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = defaultServiceConfiguration

    let sns = AWSSNS.defaultSNS()
    let createPlatformEndpointInput = AWSSNSCreatePlatformEndpointInput()
    createPlatformEndpointInput.token = token
    createPlatformEndpointInput.platformApplicationArn = SNSPlatformApplicationArn

    sns.createPlatformEndpoint(createPlatformEndpointInput).continueWithBlock
    {
        (task) -> AnyObject! in
        if task.error != nil
        {
            print("Error creating platform endpoint: \(task.error)")
            completionHandler?(task.error)
            return nil
        }
        let result = task.result as! AWSSNSCreateEndpointResponse
        let subscribeInput = AWSSNSSubscribeInput()
        subscribeInput.topicArn = SNSTopicARN
        subscribeInput.endpoint = result.endpointArn
        print("Endpoint arn: \(result.endpointArn)")
        subscribeInput.protocols = "application"
        sns.subscribe(subscribeInput).continueWithBlock
        {
            (task) -> AnyObject! in
            if task.error != nil
            {
                completionHandler?(task.error)
                print("Error subscribing: \(task.error)")
                return nil
            }
            print("Subscribed succesfully")
            let subscriptionConfirmInput = AWSSNSConfirmSubscriptionInput()
            subscriptionConfirmInput.token = token
            subscriptionConfirmInput.topicArn = SNSTopicARN
            sns.confirmSubscription(subscriptionConfirmInput).continueWithBlock
            {
                (task) -> AnyObject! in
                if task.error != nil
                {
                    print("Confirmed subscription")
                }
                completionHandler?(task.error)
                return nil
            }
            return nil
        }
        return nil
    }
}

func sendMessage(message : String, type : String = "alert", sound : String = "default", badges : Int = 1, completionHandler : ((NSError?) -> ())? = nil)
{
    let credentialsProvider : AWSStaticCredentialsProvider = AWSStaticCredentialsProvider(accessKey: AWSAccessKeySend, secretKey: AWSSecretKeySend)
    let defaultServiceConfiguration : AWSServiceConfiguration = AWSServiceConfiguration(region: DefaultServiceRegionType, credentialsProvider: credentialsProvider)
    AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = defaultServiceConfiguration


    let sns = AWSSNS.defaultSNS()
    let request = AWSSNSPublishInput()
    request.messageStructure = "json"

    let dict = ["default": message, "APNS_SANDBOX": "{\"aps\":{\"\(type)\": \"\(message)\",\"sound\":\"\(sound)\", \"badge\":\"\(badges)\"} }"]

    do
    {
        let jsonData = try NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions.PrettyPrinted)
        request.message = NSString(data: jsonData, encoding: NSUTF8StringEncoding) as! String
        request.topicArn = SNSTopicARN

        sns.publish(request).continueWithBlock
        {
            (task) -> AnyObject! in
            if task.error != nil
            {
                print("Error sending mesage: \(task.error)")
            }
            else
            {
                print("Success sending message")
            }
            completionHandler?(task.error)
            return nil
        }
    }
    catch
    {
        print("Error on json serialization: \(error)")
    }

}