我需要用户的设备token作为一个十六进制字符串来发送推送通知。我曾经使用deviceToken "description "来实现这个功能,但是在iOS13中,这个功能已经失效了。我在Objective-C和Swift中找到了几种解决方案。
但问题是 deviceToken.bytes
返回一个 Pointer
在RubyMotion中。并调用 bytes[index]
与用Objective-C做相比,会有不同的结果。我尝试了很多不同的方法,但似乎都无法成功。RubyMotion的文档中关于Pointers的内容也是非常赤裸裸的,所以这并没有什么帮助。我在SO上找到了以下关于指针的内容。
它说,我必须做 bytes + index
而不是 bytes[index]
. 我目前有以下代码。
def application(application, didRegisterForRemoteNotificationsWithDeviceToken: device_token)
string = token_to_string(device_token)
end
def token_to_string(device_token)
data_length = device_token.length
if data_length == 0
nil
else
data_buffer = device_token.bytes
token = NSMutableString.stringWithCapacity(data_length * 2)
index = 0
begin
buffer = data_buffer + index
token.appendFormat('%02.2hhx', buffer)
index += 1
end while index < data_length
token.copy
end
end
它没有给出任何错误,但生成的设备标记似乎并不正确。如果有任何建议,我将非常感激
我一直在尝试想一个纯RubyMotion的解决方案,但我对'指针'的理解不够,无法让它工作。所以我采用了不同的方式:扩展NSData类。
1)在你的项目中创建vendorNSData+Hex文件夹。
2)在文件夹里面创建NSData+Hex.h文件,把这个放在里面。
#import <Foundation/Foundation.h>
@interface NSData (Hex)
@property (nonatomic, copy, readonly) NSString *hexString;
@end
3)现在在同一个文件夹里面创建NSData+Hex.m,并把这个放在文件里面。
#import "NSData+Hex.h"
@implementation NSData (Hex)
- (NSString *) hexString
{
NSUInteger len = self.length;
if (len == 0) {
return nil;
}
const unsigned char *buffer = self.bytes;
NSMutableString *hexString = [NSMutableString stringWithCapacity:(len * 2)];
for (int i = 0; i < len; ++i) {
[hexString appendFormat:@"%02x", buffer[i]];
}
return [hexString copy];
}
@end
4) 把这个加入到你的Rakefile中:
app.vendor_project('vendor/NSData+Hex', :static)
5) 现在你可以简单地调用 deviceToken.hexString
内 def application(application, didRegisterForRemoteNotificationsWithDeviceToken: deviceToken)
.
如果有人能想到一个纯粹的RubyMotion解决方案,请随时回答。目前,它至少还能用:)
嗨,我使用以下方法将NSData转换为NSString,然后可以在ruby中进行操作。
class NSData
def to_s
NSString.alloc.initWithBytes(bytes, length: length, encoding: NSUTF8StringEncoding)
end
end