通过 AWS SNS 发送和接收推送通知
Sending and receiving push notifications via AWS 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)
}
一切似乎都运行良好,我在控制台上收到 "Subscribed successfully"、"Confirmed subscription" 和 "Message sent" 日志,但从未调用 application:didReceiveRemoteNotificationuserInfo:
。我做错了什么?
我发现我遗漏了一些要点。这是一段完美运行的代码。
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)")
}
}
我一直在尝试创建一个应用程序,以便通过 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)
}
一切似乎都运行良好,我在控制台上收到 "Subscribed successfully"、"Confirmed subscription" 和 "Message sent" 日志,但从未调用 application:didReceiveRemoteNotificationuserInfo:
。我做错了什么?
我发现我遗漏了一些要点。这是一段完美运行的代码。
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)")
}
}