How to use Objective C to send device token for pu

2019-03-08 22:18发布

问题:

Ideally, I would like to send an HTTP Request using POST to the Push Notification Server that contains the device token as well as some user-defined settings. From there I can set up a php script on the server to deal with the incoming data and input it into an sql table. If this is the only way to do it, how would I go about initiating and HTTP Request from Objective C?

回答1:

You'll first need to convert the device token to a hex string with a function like this:

- (NSString*)stringWithDeviceToken:(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]];
  }

  return [[token copy] autorelease];
}

Then you'll need to make a request to your server:

NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"http://example.com/script.php?token=%@", DEVICE_TOKEN]];
NSMutableURLRequest* request = [[[NSMutableRequest alloc] initWithURL:url] autorelease];
NSURLConnection* connection = [NSURLConnection connectionWithRequest:request delegate: self];


回答2:

another way:

NSString * tokenAsString = [[[deviceToken description] 
stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]] 
stringByReplacingOccurrencesOfString:@" " withString:@""];