gpt4 book ai didi

ios 使用 GCM 设备向设备发送推送通知

转载 作者:行者123 更新时间:2023-11-29 10:28:46 24 4
gpt4 key购买 nike

我希望能够在设备之间发送主题推送通知。如果我从服务器发送通知,我已经能够收到通知,但最后我不希望服务器与我的应用程序交互。

我写了一个发送通知的方法,如下所示:

-(void)sendNotif {
NSDictionary *message = @{
@"notification" : @"{ \"text\" : \"test\", \"title\" : \"test\"}",
@"to" : @"/topics/test"
};
// kSenderID is the senderID you want to send the message to
NSString *kSenderID = @"X";
NSString *to = [NSString stringWithFormat:@"%@@gcm.googleapis.com", kSenderID];
DLOG(@"dict %@, to : %@",message, to);
[[GCMService sharedInstance] sendMessage:message to:to withId:@"id1"];
}

但是好像什么都没有发送。

所以我有两个问题:如何编写我的方法?如何实现回调方法?

最佳答案

我找到的解决方案是创建自己的 HTTPRequest,就像在 google 示例中一样:

-(void)sendNotif {
NSString *sendUrl = @"https://android.googleapis.com/gcm/send";
NSString *subscriptionTopic = @"/topics/test";
NSString *title = notifTitle.text;
NSString *body = notifBody.text;
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:sendUrl ]];
req.HTTPMethod = @"POST";
[req setValue:@"application/json" forHTTPHeaderField: @"Content-Type"];
[req setValue:@"key=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" forHTTPHeaderField: @"Authorization"];
NSDictionary *message = [self getMessageTo:subscriptionTopic withTitle:title withBody:body];
NSError *jsonError;
NSMutableString *jsonString;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:message options:NSJSONWritingPrettyPrinted error:&jsonError];
if (! jsonData) {
NSLog(@"Got an error: %@", jsonError);
} else {
jsonString = [[NSMutableString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
DLOG(@"json string%@", jsonString);
req.HTTPBody = jsonData;
[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if (error != nil) {
DLOG(@"truc error %@",error);
} else {
DLOG(@"Success! Response from the GCM server:");
DLOG(@"%@",response);
}
}];
}

-(NSDictionary *) getMessageTo:(NSString *) to withTitle:(NSString *) title withBody:(NSString *) body{
// [START notification_format]
NSDictionary *message = @{
@"notification" : @{@"title" : title,@"text" : body},
@"to" : to
};
return message;
// [END notification_format]
}

关于ios 使用 GCM 设备向设备发送推送通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30780422/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com