IOS client gets seven kn upload token

Source: Internet
Author: User
Tags sha1 encryption

First, the official reference document: 1. Upload policy http://developer.qiniu.com/article/developer/security/put-policy.html2. Upload voucher (i.e. Uptoken)/HTTP/ developer.qiniu.com/article/developer/security/upload-token.html3. Download Voucher http://developer.qiniu.com/article/ Developer/security/download-token.html4.token Generate online Demo http://jsfiddle.net/gh/get/extjs/4.2/icattlecoder/jsfiddle/ Tree/master/uptoken II: Generate TOKEN1. First, I opened up a public storage space in seven cattle named: Images the way to generate tokens is: The first step: Determine the top policy second step: Serialize the upload policy to JSON format

{"Scope": "Your Bucket", "deadline": valid time, default is one hours}

The third step: the BASE64 encoding of the URL security of the upload strategy after the JSON serialization, get encoded fourth step: Secretkey the encoding after the upload strategy HMAC-SHA1 encryption, and do URL security Base64 code, get Encoded_ Signed Fifth step: Connect AccessKey, encode_signed and encoded with ":" To get Uploadtoken:2. The code is as follows 1. header file:
#import " UploadManager.h " #import " HttpManager.h " #import <GTMBase64/GTMBase64.h>#import <CommonCrypto/CommonDigest.h>#import <CommonCrypto/CommonHMAC.h>
2. Get upload voucher (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]; CharDigeststr[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]; returnToken//got token.}

- (NSString *) Marshal:(NSString *)bucket key:(NSString *) key

{

time_t deadline;

time (&deadline);// return current system times

@property (nonatomic , assign) int expires; How to define with you ...

Deadline + = (_expires > 0) _expires:3600;//+3600 seconds, that is, the default token is saved for 1 hours.

NSNumber *deadlinenumber = [NSNumber numberwithlonglong:deadline];

Nsmutabledictionary *dic = [nsmutabledictionary dictionary];

Images is my public space name (bucket), AAA is the file key,

By seven cows description of "Upload policy": <bucket>:<key>, which means that only users are allowed to upload files of the specified key. In this format the file is allowed to "modify" by default, and if a resource with the same name already exists, it will be overwritten. If you only want to upload a file of the specified key and do not allow modification, you can set the following Insertonly property value to 1.

So if the parameter only to users, the next upload key or AAA file will prompt the existence of the same name file, cannot upload.

Pass Images:aaa words, can overwrite the update, but the measured delay is longer, I upload the same name new file up, downloaded or old files.

NSString *value = [NSString stringwithformat:@ "%@:%@", bucket, key];

[dic setobject:value forkey:@ "Scope"];// based on

[dic setobject:deadlinenumber forkey:@ "Deadline"];

NSString *json = [dic mj_jsonstring];

return JSON;

}

Three: Upload

Upload token, upload so easy.

 for(Uploadtask *taskinch_tasks) {        if(Task.fileurl! = nil)Continue;        Dispatch_group_enter (_group); Dispatch_async (_queue,^{qnuploadoption* option = [[Qnuploadoption alloc] initwithprogresshandler:^ (NSString *key,floatpercent)                            {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: Seven kn return data:%@", 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:-1userinfo:@{}];                      [Task Updateerror:error];                  Dispatch_group_leave (_group);    }} Option:option]; Dispatch_group_notify (_group, Dispatch_get_main_queue (),^{_completionhandler (_tasks);    }); 
Four. Easy to download

Download voucher document According to seven KN
The download uses the Get method
Get URL generation method look at the document on the line, divided into private space and public space two.

-(void) download{NSString*path =@"Check the documentation yourself and fill in the URL of the file you need to download"; Nsurlrequest*request =[nsurlrequest Requestwithurl:[nsurl Urlwithstring:path] CachePolicy:1timeOutInterval:15.0f]; [Nsurlconnection sendasynchronousrequest:request queue:[nsoperationqueue Mainqueue] CompletionHandler:^ (Nsurlresponse * _nullable response, NSData * _nullable data, Nserror *_nullable Connectionerror) {NSLog (@"response =%@", response); //It's good to get the JSON file parsing.         IDresult = [Nsjsonserialization jsonobjectwithdata:data options:0Error:null]; NSLog (@"%@", result); }];}

IOS client gets seven kn upload token

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.