将设备令牌发送到服务器

发布于 2024-12-05 06:05:07 字数 1708 浏览 1 评论 0原文

我已经阅读了很多这方面的教程,我只是想知道这是否是正确的方法,

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
    NSLog(@"My token is: %@", deviceToken);

    NSString* newToken = [deviceToken description];

    newToken = [newToken stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    newToken = [newToken stringByReplacingOccurrencesOfString:@" " withString:@""]; 


    NSString *urlString = [NSString stringWithFormat:@"http://myhost.com./filecreate.php?token=%@",newToken];

    NSURL *url = [[NSURL alloc] initWithString:urlString];

    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];

    NSData *urlData;
    NSURLResponse *response;
    urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:nil];

}

任何建议都非常受欢迎。

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{

    const char* data = [deviceToken bytes];
    NSMutableString* token = [NSMutableString string];

    for (int i = 0; i < [deviceToken length]; i++) {
        [token appendFormat:@"%02.2hhX", data[i]];
    }


    NSString *urlString = [NSString stringWithFormat:@"http://myhost.com/filecreate.php?token=%@",token];

    NSURL *url = [[NSURL alloc] initWithString:urlString];

    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];   
    NSData *urlData;
    NSURLResponse *response;
    urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:nil];

}

我的应用程序可以使用这两种代码,但是正确的方法是什么?

I have read a lot of tutorials for this and i just wanted ti know if this is right way to do this

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
    NSLog(@"My token is: %@", deviceToken);

    NSString* newToken = [deviceToken description];

    newToken = [newToken stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    newToken = [newToken stringByReplacingOccurrencesOfString:@" " withString:@""]; 


    NSString *urlString = [NSString stringWithFormat:@"http://myhost.com./filecreate.php?token=%@",newToken];

    NSURL *url = [[NSURL alloc] initWithString:urlString];

    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];

    NSData *urlData;
    NSURLResponse *response;
    urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:nil];

}

any advices are more then welcomed.

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{

    const char* data = [deviceToken bytes];
    NSMutableString* token = [NSMutableString string];

    for (int i = 0; i < [deviceToken length]; i++) {
        [token appendFormat:@"%02.2hhX", data[i]];
    }


    NSString *urlString = [NSString stringWithFormat:@"http://myhost.com/filecreate.php?token=%@",token];

    NSURL *url = [[NSURL alloc] initWithString:urlString];

    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];   
    NSData *urlData;
    NSURLResponse *response;
    urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:nil];

}

My application works with both codes, but what's the right way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

辞别 2024-12-12 06:05:07

正如mja在评论中所说,最好添加错误恢复机制(如果请求失败,您将丢失令牌)并使用异步请求(在后台发送令牌)

在您的AppDelegate.m中:

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
    NSString * token = [NSString stringWithFormat:@"%@", deviceToken];
    //Format token as you need:
    token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    token = [token stringByReplacingOccurrencesOfString:@">" withString:@""];
    token = [token stringByReplacingOccurrencesOfString:@"<" withString:@""];

    [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"apnsToken"]; //save token to resend it if request fails
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"apnsTokenSentSuccessfully"]; // set flag for request status
    [DataUpdater sendUserToken]; //send token
}

发送令牌创建新类(或使用现有类之一):
DataUpdater.h

#import <Foundation/Foundation.h>

@interface DataUpdater : NSObject     
+ (void)sendUserToken;
@end

DataUpdater.m

#import "DataUpdater.h"

@implementation DataUpdater

+ (void)sendUserToken {
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"apnsTokenSentSuccessfully"]) {
        NSLog(@"apnsTokenSentSuccessfully already");
        return;
    }

    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://myhost.com/filecreate.php?token=%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"apnsToken"]]]; //set here your URL

    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];

    [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
     {
         if (error == nil) {
             [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"apnsTokenSentSuccessfully"];
             NSLog(@"Token is being sent successfully");
             //you can check server response here if you need
         }
     }];
}

@end

然后您可以在互联网连接出现时、或定期或在 < b>-(void)viewDidLoad 或 -(void)viewWillAppear 方法

我的建议:

1)我使用 AFNetworking 发送异步请求并检查服务器 JSON 响应

2) 有时最好使用 Parse 等服务来处理推送通知

As mja said in comments, it's better to add error recovery mechanism (if the request fails you will lose your token) and use asynchronous request (send token in background)

In your AppDelegate.m:

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
    NSString * token = [NSString stringWithFormat:@"%@", deviceToken];
    //Format token as you need:
    token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    token = [token stringByReplacingOccurrencesOfString:@">" withString:@""];
    token = [token stringByReplacingOccurrencesOfString:@"<" withString:@""];

    [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"apnsToken"]; //save token to resend it if request fails
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"apnsTokenSentSuccessfully"]; // set flag for request status
    [DataUpdater sendUserToken]; //send token
}

To send token create new class (or use one of existing):
DataUpdater.h

#import <Foundation/Foundation.h>

@interface DataUpdater : NSObject     
+ (void)sendUserToken;
@end

DataUpdater.m

#import "DataUpdater.h"

@implementation DataUpdater

+ (void)sendUserToken {
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"apnsTokenSentSuccessfully"]) {
        NSLog(@"apnsTokenSentSuccessfully already");
        return;
    }

    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://myhost.com/filecreate.php?token=%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"apnsToken"]]]; //set here your URL

    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];

    [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
     {
         if (error == nil) {
             [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"apnsTokenSentSuccessfully"];
             NSLog(@"Token is being sent successfully");
             //you can check server response here if you need
         }
     }];
}

@end

Then you can call [DataUpdater sendUserToken]; in your controllers when internet connection appears, or periodically, or in -(void)viewDidLoad or -(void)viewWillAppear methods

My advises:

1) I use AFNetworking to send async request and check server JSON response

2) Some times it's better to use services such as Parse to work with push notifications

你怎么这么可爱啊 2024-12-12 06:05:07

在 didFinishLaunchingWithOptions 方法中

[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
     (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];

完成上述代码行后,添加以下方法

#pragma mark -
#pragma mark Push Notifications
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSString  *token_string = [[[[deviceToken description]    stringByReplacingOccurrencesOfString:@"<"withString:@""]
                            stringByReplacingOccurrencesOfString:@">" withString:@""]
                           stringByReplacingOccurrencesOfString: @" " withString: @""];
NSString* strURL = [NSString stringWithFormat:@"http://www.sample.com?device_token=%@&type=IOS",token_string];
strURL=[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@",strURL);
NSData *fileData = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
NSLog(@"content---%@", fileData);
}

In didFinishLaunchingWithOptions method

[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
     (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];

After doing above lines of code ,add the method below

#pragma mark -
#pragma mark Push Notifications
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSString  *token_string = [[[[deviceToken description]    stringByReplacingOccurrencesOfString:@"<"withString:@""]
                            stringByReplacingOccurrencesOfString:@">" withString:@""]
                           stringByReplacingOccurrencesOfString: @" " withString: @""];
NSString* strURL = [NSString stringWithFormat:@"http://www.sample.com?device_token=%@&type=IOS",token_string];
strURL=[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@",strURL);
NSData *fileData = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
NSLog(@"content---%@", fileData);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文