聊聊iOS做融云时重要的一步,获取token。token应该从服务端拿这样你的appSecret就不容易暴露。但有时开发需要也要自己先获取一个token也是可以的。请求方式有很多随你便喽,C哥(“我”自称)用的是AFN,记着安融云文档上来是POST请求,需要自己提供一些参数,有的参数是从融云控制平台得到的比如appkey,下面是我的代码
- (void)getIMToken {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSString *urlstr =@"https://api.cn.rong.io/user/getToken.json";
NSDictionary *dic =@{@"userId":@"你想要的账号,字母或数字都行",
@"name":@"随便起一个名字吧",
@"portraitUri":@"http://pic6.huitu.com/res/20130116/84481_20130116142820494200_1.jpg,前面的是我随便找的图片你可以替换"
};
//这几句是按融云的提示写的
NSString * timestamp = [[NSString alloc] initWithFormat:@"%ld",(NSInteger)[NSDate timeIntervalSinceReferenceDate]];
NSString * nonce = [NSString stringWithFormat:@"%d",arc4random()];
NSString * appkey = @"你的appkey,从你的控制台得到";
NSString *SignatureWillMD5 = [NSString stringWithFormat:@"%@%@%@",appkey,nonce,timestamp];//这个要加密
NSString *Signature = [self MD5String:ppp]; //C哥是做了MD5加密
//以下拼接请求内容
[manager.requestSerializer setValue:appkey forHTTPHeaderField:@"App-Key"];
[manager.requestSerializer setValue:nonce forHTTPHeaderField:@"Nonce"];
[manager.requestSerializer setValue:timestamp forHTTPHeaderField:@"Timestamp"];
[manager.requestSerializer setValue:Signature forHTTPHeaderField:@"Signature"];
[manager.requestSerializer setValue:@"6KQHFraKVNpR" forHTTPHeaderField:@"appSecret"];
[manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
//开始请求
[manager POST:urlstr parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
//这里你就能得到token啦~
NSLog(@"%@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
}
//MD5加密,要导入#import <CommonCrypto/CommonDigest.h>。
- (NSString *)MD5String:(NSString *)str {
const char *cStr = [str UTF8String];
unsigned char result[16];
CC_MD5(cStr, (CC_LONG)strlen(cStr), result); // This is the md5 call
NSString * md5Str = [NSString stringWithFormat:
@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
result[0], result[1], result[2], result[3],
result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11],
result[12], result[13], result[14], result[15]
];
CGLog(@"%@",md5Str);
return md5Str;
}