PCH files:
Ali cloud / * * * / # import < AliyunOSSiOS/OSSService. H > / / header file # define Ali_EndPoint_URL @ "http://oss-cn-shanghai.aliyuncs.com" //URL #define Ali_AccessKeyId @"abcdefg12345abcd" //AccessKeyId #define Ali_AccessKeySecret @"abcdefg12345abcdefg12345ab" //secretKeyId #define Ali_SecurityToken @"" //securityToken #define Ali_bucketName #define Ali_objectKey @"" #define User_Def [NSUserDefaults standardUserDefaults] //NSUserdefaultCopy the code

Example: Picture storage processing

[1]. Picture upload:

// Select the image, And upload [BDImagePicker showImagePickerFromViewController: self allowsEditing: YES finishAction: ^ (UIImage * image) {if (image) [SVProgressHUD showWithStatus:@" upload..."]; NSData * iconData = NSString *endpoint = Ali_EndPoint_URL;// Alicloud URL // Recommend the use of mobile end initialization OSSClient STS way. More authentication mode section. Please refer to the back of the access control id < OSSCredentialProvider > the credential = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:Ali_AccessKeyId secretKeyId:Ali_AccessKeySecret securityToken:Ali_SecurityToken]; OSSClientConfiguration * conf = [OSSClientConfiguration New]; conf.maxretryCount = 3; // Number of retries after network requests fail The conf. TimeoutIntervalForRequest = 30; / / network request timeout conf. TimeoutIntervalForResource = 24 * 60 * 60; / / to allow resource transmission for the longest time OSSClient * client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential ClientConfiguration :conf]; OSSPutObjectRequest * PUT = [OSSPutObjectRequest new];// Put mode put.bucketName = NSDateFormatter * format = [[NSDateFormatter alloc] init]; [format setDateFormat:@"yyyyMMddHHmmsss"]; NSString * timeStr = [format stringFromDate:[NSDate date] ]; NSString * mobileStr = [User_Def objectForKey:USER_MobileNumber]?[User_Def objectForKey:USER_MobileNumber]:@""; NSString * objKeyStr = [NSString stringWithFormat:@"%@-%@.png",mobileStr,timeStr]; put.objectKey = objKeyStr; UploadingData = iconData; // uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) { //NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, TotalBytesExpectedToSend); Percentage [SVProgressHUD showProgress:(float)totalByteSent/(float)totalBytesExpectedToSend];}; OSSTask * putTask = [client putObject:put]; [putTask continueWithBlock:^id(OSSTask *task) { NSLog(@"%@",task); if (!task.error) { NSLog(@"upload "); [User_Def setObject:objKeyStr forKey:ICON_Avatar]; [SVProgressHUD showSuccessWithStatus:@" // main thread: Dispatch_async (dispatch_get_main_queue(), ^{_iconimgv. image = image;});} else {NSLog(@"upload object failed, error: % @ ", Task.error); [SVProgressHUD showErrorWithStatus:@" Image upload failed "];} return nil;}]; [putTask waitUntilFinished]; }];Copy the code

[2]. Obtain cloud server storage address:

NSString * publicURL = nil; NSString *endpoint = Ali_EndPoint_URL; // It is recommended to initialize OSSClient in STS mode on the mobile terminal. For more authentication modes, see the access Control section later. id<OSSCredentialProvider> credential = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:Ali_AccessKeyId secretKeyId:Ali_AccessKeySecret securityToken:Ali_SecurityToken]; OSSClientConfiguration * conf = [OSSClientConfiguration new]; conf.maxRetryCount = 3; / / network request exception encountered after the failure of retries conf. TimeoutIntervalForRequest = 30; / / network request timeout conf. TimeoutIntervalForResource = 24 * 60 * 60; / / allow the longest OSSClient resources transmission * client = [[OSSClient alloc] initWithEndpoint: the endpoint credentialProvider: the credential clientConfiguration:conf]; OSSPutObjectRequest * get = [OSSPutObjectRequest new]; // Get get.bucketName = Ali_bucketName; // path NSString * objKeyStr = [NSString stringWithFormat:@"%@/avatar",[NSData data]]; //get.objectKey = @"<objectKey>"; // Get. ObjectKey = @"18308080808-201706281539328.png"; OSSTask * task = [client putObject:get]; task = [client presignPublicURLWithBucketName:Ali_bucketName withObjectKey:get.objectKey]; if (! task.error) { publicURL = task.result; } else {NSLog(@"sign URL error: %@", task.error); }Copy the code

Access to the ali cloud storage address: http://cuteKids-img.oss-cn-shanghai.aliyuncs.com/18308080808-201706281539328.png

Then you can define a URL macro (fixed) : #define GetAliDataHeaderUrl @”http://cuteKids-img.oss-cn-shanghai.aliyuncs.com/”

[3]. Address: <3-1>. Rongyun chat interface, profile picture configuration

After the network request succeeds, set the profile picture address of Rongyun as userinfo. portraitUri = publicURL.

/ / melt cloud: If ([responseObject[@"Code"] integerValue] == 0) {// Network request succeeded for (NSDictionary * dict in) ResponseObject [@"DataList"]) {RCUserInfo * userInfo = [[RCUserInfo alloc] init]; userInfo.userId = dict[@"userId"]; //1. User id userinfo.name = dict[@"userName"]; //2. Username NSString * picUrlStr; / / head address if dict [@ "icon"]) {/ / ali cloud picture URL picUrlStr = [nsstrings stringWithFormat: @ "% @ % @", GetAliDataHeaderUrl, dict / @ "icon" ]; } else {/ / web sites (the default) images picUrlStr = @ "http://img.qq1234.org/uploads/allimg/140520/3_140520152454_6.jpg"; } userInfo.portraitUri = picUrlStr; //3. Avatar address // Rong Yun Unified configuration //RCUserInfo * userInfo = [[RCUserInfo alloc] initWithUserId:dict[@"userId"] name:dict[@"userName"] portrait:picUrlStr]; [[RCIM sharedRCIM] setCurrentUserInfo:userInfo]; } dispatch_async(dispatch_get_main_queue(), ^{ [weakSelf.conversationMessageCollectionView reloadData]; }); } #define GetAliDataHeaderUrl @"http://cuteKids-img.oss-cn-shanghai.aliyuncs.com/"Copy the code

<3-2>. General image usage: SDWebImage loading

NSString * picUrlStr = [NSString stringWithFormat:@"%@%@",GetAliDataHeaderUrl,model.createrAvatar];
[_iconImgV sd_setImageWithURL:[NSURL URLWithString:picUrlStr] placeholderImage:[UIImage imageNamed:@"userIcon"]]
Copy the code

Server data Management

Basic configuration:

NSString *endpoint = Ali_EndPoint_URL; // It is recommended to initialize OSSClient in STS mode on the mobile terminal. For more authentication modes, see the access Control section later. id<OSSCredentialProvider> credential = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:Ali_AccessKeyId secretKeyId:Ali_AccessKeySecret securityToken:Ali_SecurityToken]; OSSClientConfiguration * conf = [OSSClientConfiguration new]; conf.maxRetryCount = 3; / / network request exception encountered after the failure of retries conf. TimeoutIntervalForRequest = 30; / / network request timeout conf. TimeoutIntervalForResource = 24 * 60 * 60; / / allow the longest OSSClient resources transmission * client = [[OSSClient alloc] initWithEndpoint: the endpoint credentialProvider: the credential clientConfiguration:conf];Copy the code

[1]. View all objects:

OSSGetBucketRequest * getBucket = [OSSGetBucketRequest new]; getBucket.bucketName = Ali_bucketName; This parameter is optional. For details, see https://docs.aliyun.com/#/pub/oss/api-reference/bucket&GetBucket // getbucket.marker = @""; // getBucket.prefix = @""; // getBucket.delimiter = @""; OSSTask * getBucketTask = [client getBucket:getBucket]; [getBucketTask continueWithBlock:^id(OSSTask *task) { if (!task.error) { OSSGetBucketResult * result = task.result; NSLog(@"get bucket success!"); for (NSDictionary * objectInfo in result.contents) { NSLog(@"list object: %@", objectInfo); } } else { NSLog(@"get bucket failed, error: %@", task.error); } return nil; }];Copy the code

[2]. Check whether the file exists:

NSString * objKeyStr = @"18308080808-201706281539328.png"; NSError * error = nil; BOOL isExist = [client doesObjectExistInBucket:Ali_bucketName objectKey:objKeyStr error:&error]; if (! error) { if(isExist) { NSLog(@"File exists."); } else { NSLog(@"File not exists."); } } else { NSLog(@"Error!" ); }Copy the code

[3]. Delete the Object

NSString * deleteObjKeyStr = @"18308080808-201706281539328.png"; OSSDeleteObjectRequest * delete = [OSSDeleteObjectRequest new]; delete.bucketName = Ali_bucketName; delete.objectKey = deleteObjKeyStr; OSSTask * deleteTask = [client deleteObject:delete]; [deleteTask continueWithBlock:^id(OSSTask *task) {if (! Task.error) {MBProgressHUD *hud = [MBProgressHUD ShowHUDAddedTo :self.view animated:YES]; hud. Mode = MBProgressHUDModeText; hud.  hud.offset = CGPointMake(0, 0. F); hud. RemoveFromSuperViewOnHide = YES; [hud hideAnimated: YES afterDelay: 1.5 f];} return nil;}]; // [deleteTask waitUntilFinished];Copy the code

In fact, data management step, processing small files (small pictures, small documents) is not necessary; But handling large files (music, video) is still necessary!

My personal advice: deal with it! (Don’t stop dealing with it just because someone tells you not to!) This is more or less the quality of a programmer and the embodiment of logical rigor! 😂 😂 😂 😂 😂 😂 😂 😂

(2017.09.29)

goyohol’s essay