iOS 客戶端獲取七牛上傳token
一、官方參考文檔:
1.上傳策略http://developer.qiniu.com/article/developer/security/put-policy.html
2.上傳憑證(即uptoken)http://developer.qiniu.com/article/developer/security/upload-token.html
3.下載憑證http://developer.qiniu.com/article/developer/security/download-token.html
4.token生成在線演示http://jsfiddle.net/gh/get/extjs/4.2/icattlecoder/jsfiddle/tree/master/uptoken
二:生成token
1.首先,我在七牛開辟了一個公共的存儲空間名為:images
生成token的方法是:
第一步:確定上策略
第二步:將上傳策略序列化為json格式
{"scope":"你的bucket","deadline":有效時間,默認是一個小時}
第三步:對json序列化後的上傳策略進行URL安全的Base64編碼,得到encoded
第四步:用SecretKey對編碼後的上傳策略進行HMAC-SHA1加密,並且做URL安全的Base64編碼,得到encoded_signed
第五步:將 AccessKey、encode_signed 和 encoded 用 “:” 連接起來,得到UploadToken:
2.代碼如下
1.頭文件:
#import "UploadManager.h" #import "HttpManager.h" #import <GTMBase64/GTMBase64.h> #import <CommonCrypto/CommonDigest.h> #import <CommonCrypto/CommonHMAC.h>
2.獲取上傳憑證(token)
- (NSString *)makeToken:(NSString *)accessKey secretKey:(NSString *)secretKey bucket:(NSString *)bucket key:(NSString *)key {const char *secretKeyStr = [secretKey UTF8String]; NSString *policy = [self marshal: bucket key:key]; NSData *policyData = [policy dataUsingEncoding:NSUTF8StringEncoding]; NSString *encodedPolicy = [GTMBase64 stringByWebSafeEncodingData:policyData padded:TRUE]; const char *encodedPolicyStr = [encodedPolicy cStringUsingEncoding:NSUTF8StringEncoding]; char digestStr[CC_SHA1_DIGEST_LENGTH]; bzero(digestStr, 0); CCHmac(kCCHmacAlgSHA1, secretKeyStr, strlen(secretKeyStr), encodedPolicyStr, strlen(encodedPolicyStr), digestStr); NSString *encodedDigest = [GTMBase64 stringByWebSafeEncodingBytes:digestStr length:CC_SHA1_DIGEST_LENGTH padded:TRUE]; NSString *token = [NSString stringWithFormat:@"%@:%@:%@", accessKey, encodedDigest, encodedPolicy]; return token;//得到了token }
- (NSString *)marshal:(NSString *)bucket key:(NSString *)key
{
time_t deadline;
time(&deadline);//返回當前系統時間
[email protected] (nonatomic , assign) int expires; 怎麽定義隨你...
deadline += (_expires > 0) ? _expires : 3600; // +3600秒,即默認token保存1小時.
NSNumber *deadlineNumber = [NSNumber numberWithLongLong:deadline];
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
//images是我開辟的公共空間名(即bucket),aaa是文件的key,
//按七牛“上傳策略”的描述: <bucket>:<key>,表示只允許用戶上傳指定key的文件。在這種格式下文件默認允許“修改”,若已存在同名資源則會被覆蓋。如果只希望上傳指定key的文件,並且不允許修改,那麽可以將下面的 insertOnly 屬性值設為 1。
//所以如果參數只傳users的話,下次上傳key還是aaa的文件會提示存在同名文件,不能上傳。
//傳images:aaa的話,可以覆蓋更新,但實測延遲較長,我上傳同名新文件上去,下載下來的還是老文件。
NSString *value = [NSString stringWithFormat:@"%@:%@", bucket, key];
[dic setObject:value forKey:@"scope"];//根據
[dic setObject:deadlineNumber forKey:@"deadline"];
NSString *json = [dic mj_JSONString];
return json;
}
三:上傳
有了上傳token,上傳so easy.
for (UploadTask *task in _tasks) { if (task.fileURL != nil) continue; dispatch_group_enter(_group); dispatch_async(_queue, ^{ QNUploadOption * option = [[QNUploadOption alloc] initWithProgressHandler:^(NSString *key, float percent) { progress(key,percent); }]; QNUploadManager *upManager = [[QNUploadManager alloc] init]; [upManager putData:task.data key:key token:_upimagetoken complete: ^(QNResponseInfo *info, NSString *key, NSDictionary *resp) { NSLog(@"uploadWithKey:七牛返回數據: %@", info); if (kQNInvalidToken == info.statusCode) { _upimagetoken = nil; } NSString *respKey = resp[@"key"]; //_keyStr = respKey; if (respKey) { NSString* fileUrl = [_img_host stringByAppendingString:respKey]; [task updateFileURL:fileUrl fileKey:respKey]; dispatch_group_leave(_group); }else{ NSError *error = [NSError errorWithDomain:@"com.fdzx" code:-1 userInfo:@{}]; [task updateError:error]; dispatch_group_leave(_group); } } option:option]; dispatch_group_notify(_group, dispatch_get_main_queue(), ^{ _completionHandler(_tasks); });
四.下載更easy
根據七牛的下載憑證文檔
下載均使用GET方法
get的URL生成方法看一下文檔就行,分私有空間和公共空間兩種。
-(void)download { NSString *path = @"自己查看一下文檔,這裏填你需要下載的文件的url"; NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:path] cachePolicy:1 timeoutInterval:15.0f]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { NSLog(@"response = %@",response); //得到了JSON文件 解析就好了。 id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL]; NSLog(@"%@", result); }]; }
iOS 客戶端獲取七牛上傳token