Aliyun
PCH文件:
/** 阿里云 */
#import <AliyunOSSiOS/OSSService.h> //頭文件
#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 @"cuteKids-img" //文件夾(路徑)
#define Ali_objectKey @""
#define User_Def [NSUserDefaults standardUserDefaults] //NSUserdefault
示例:圖片存儲處理
[1].圖片上傳:
//選擇圖片,并上傳
[BDImagePicker showImagePickerFromViewController:self allowsEditing:YES finishAction:^(UIImage *image) {
if (image) { //圖片已經(jīng)挑選好
//上傳圖片
[SVProgressHUD showWithStatus:@"圖片上傳中..."];
NSData * iconData = UIImagePNGRepresentation(image);//圖片轉(zhuǎn)為NSData類型
NSString *endpoint = Ali_EndPoint_URL;//阿里云URL
// 移動端建議使用STS方式初始化OSSClient睛榄。更多鑒權(quán)模式請參考后面的訪問控制章節(jié)颓帝。
id<OSSCredentialProvider> credential = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:Ali_AccessKeyId secretKeyId:Ali_AccessKeySecret securityToken:Ali_SecurityToken];
OSSClientConfiguration * conf = [OSSClientConfiguration new];
conf.maxRetryCount = 3; // 網(wǎng)絡(luò)請求遇到異常失敗后的重試次數(shù)
conf.timeoutIntervalForRequest = 30; // 網(wǎng)絡(luò)請求的超時時間
conf.timeoutIntervalForResource = 24 * 60 * 60; // 允許資源傳輸?shù)淖铋L時間
OSSClient * client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential clientConfiguration:conf];
OSSPutObjectRequest * put = [OSSPutObjectRequest new];//PUT方式
put.bucketName = Ali_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; //圖片存儲名:“手機號-日期.png”
put.uploadingData = iconData; //直接上傳NSData
put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
//NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
//顯示進度:百分比
[SVProgressHUD showProgress:(float)totalByteSent/(float)totalBytesExpectedToSend];
};
OSSTask * putTask = [client putObject:put];
[putTask continueWithBlock:^id(OSSTask *task) {
NSLog(@"%@",task);
if (!task.error) {
NSLog(@"upload object success!");
[User_Def setObject:objKeyStr forKey:ICON_Avatar];
[SVProgressHUD showSuccessWithStatus:@"圖片上傳成功"];
//主線程:更換當(dāng)前圖片
dispatch_async(dispatch_get_main_queue(), ^{
_iconImgV.image = image;
});
} else {
NSLog(@"upload object failed, error: %@" , task.error);
[SVProgressHUD showErrorWithStatus:@"圖片上傳失敗"];
}
return nil;
}];
//[putTask waitUntilFinished];//可以等待任務(wù)完成
}
}];
//獲取URL
NSString * publicURL = nil;
NSString *endpoint = Ali_EndPoint_URL;
// 移動端建議使用STS方式初始化OSSClient黔帕。更多鑒權(quán)模式請參考后面的訪問控制章節(jié)突委。
id<OSSCredentialProvider> credential = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:Ali_AccessKeyId secretKeyId:Ali_AccessKeySecret securityToken:Ali_SecurityToken];
OSSClientConfiguration * conf = [OSSClientConfiguration new];
conf.maxRetryCount = 3; // 網(wǎng)絡(luò)請求遇到異常失敗后的重試次數(shù)
conf.timeoutIntervalForRequest = 30; // 網(wǎng)絡(luò)請求的超時時間
conf.timeoutIntervalForResource = 24 * 60 * 60; // 允許資源傳輸?shù)淖铋L時間
OSSClient * client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential clientConfiguration:conf];
OSSPutObjectRequest * get = [OSSPutObjectRequest new];//get方式
get.bucketName = Ali_bucketName;//路徑
NSString * objKeyStr = [NSString stringWithFormat:@"%@/avatar",[NSData data] ];
//get.objectKey = @"<objectKey>";//填寫文件的路徑
get.objectKey = @"18308080808-201706281539328.png";//圖片存儲名:“手機號-日期.png”
OSSTask * task = [client putObject:get];
task = [client presignPublicURLWithBucketName:Ali_bucketName
withObjectKey:get.objectKey];
if (!task.error) {
publicURL = task.result;//獲取到的URL
} else {
NSLog(@"sign url error: %@", task.error);
}
獲取到的阿里云存儲地址:http://cuteKids-img.oss-cn-shanghai.aliyuncs.com/18308080808-201706281539328.png
之后就可以定義一個URL的宏(固定):
#define GetAliDataHeaderUrl @"http://cuteKids-img.oss-cn-shanghai.aliyuncs.com/" //外網(wǎng)(圖片)
網(wǎng)絡(luò)請求成功后滞详,配置 融云頭像地址:userInfo.portraitUri = publicURL;
//融云:個人信息配置
if ([responseObject[@"Code"] integerValue] == 0) { //網(wǎng)絡(luò)請求成功
for (NSDictionary * dict in responseObject[@"DataList"]) {
//設(shè)置用戶個人信息
RCUserInfo * userInfo = [[RCUserInfo alloc] init];
userInfo.userId = dict[@"userId"]; //1.用戶id
userInfo.name = dict[@"userName"]; //2.用戶名
NSString * picUrlStr; //頭像地址
if (dict[@"icon"]) {
//阿里云圖片URL
picUrlStr = [NSString stringWithFormat:@"%@%@",GetAliDataHeaderUrl,dict[@"icon"] ];
} else { //網(wǎng)絡(luò)占位(默認)圖片
picUrlStr = @"http://img.qq1234.org/uploads/allimg/140520/3_140520152454_6.jpg";
}
userInfo.portraitUri = picUrlStr; //3.頭像地址
//融云【方式二】:統(tǒng)一配置
//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];
});
}
//頭像存儲URL:
//#define GetAliDataHeaderUrl @"http://cuteKids-img.oss-cn-shanghai.aliyuncs.com/" //外網(wǎng)(圖片)
NSString * picUrlStr = [NSString stringWithFormat:@"%@%@",GetAliDataHeaderUrl,model.createrAvatar];
[_iconImgV sd_setImageWithURL:[NSURL URLWithString:picUrlStr] placeholderImage:[UIImage imageNamed:@"userIcon"]]
服務(wù)器 數(shù)據(jù)管理
基礎(chǔ)配置:
NSString *endpoint = Ali_EndPoint_URL;
// 移動端建議使用STS方式初始化OSSClient暂筝。更多鑒權(quán)模式請參考后面的訪問控制章節(jié)澄惊。
id<OSSCredentialProvider> credential = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:Ali_AccessKeyId secretKeyId:Ali_AccessKeySecret securityToken:Ali_SecurityToken];
OSSClientConfiguration * conf = [OSSClientConfiguration new];
conf.maxRetryCount = 3; // 網(wǎng)絡(luò)請求遇到異常失敗后的重試次數(shù)
conf.timeoutIntervalForRequest = 30; // 網(wǎng)絡(luò)請求的超時時間
conf.timeoutIntervalForResource = 24 * 60 * 60; // 允許資源傳輸?shù)淖铋L時間
OSSClient * client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential clientConfiguration:conf];
//查看所有Object
OSSGetBucketRequest * getBucket = [OSSGetBucketRequest new];
getBucket.bucketName = Ali_bucketName;
// 可選參數(shù)唆途,具體含義參考: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;
}];
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!");
}
NSString * deleteObjKeyStr = @"18308080808-201706281539328.png";
//刪除Object
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.label.text = @"刪除成功!";
hud.margin = 10.f;
hud.offset = CGPointMake(0, 0.f);
hud.removeFromSuperViewOnHide = YES;
[hud hideAnimated:YES afterDelay:1.5f];
}
return nil;
}];
// [deleteTask waitUntilFinished];
其實數(shù)據(jù)管理這一步缤削,處理小文件(小圖片窘哈,小文檔)是不太需要的;但處理大文件(音樂亭敢、視頻)還是必要的滚婉!
我個人建議:處理!(不要因為別人跟你說不用處理帅刀,就不去處理让腹!)
這多多少少是一個程序員的素質(zhì)和邏輯縝密性的體現(xiàn)!????????????????