Coder Social home page Coder Social logo

aliyun-oss-ios-sdk's Introduction

Alibaba Cloud OSS SDK for iOS

Introduction

This document mainly describes how to install and use the OSS iOS SDK. This document assumes that you have already activated the Alibaba Cloud OSS service and created an AccessKeyID and an AccessKeySecret. In the document, ID refers to the AccessKeyID and KEY indicates the AccessKeySecret. If you have not yet activated or do not know about the OSS service, log on to the OSS Product Homepage for more help.

Environment requirements

  • iOS 8.0 or above.
  • You must have registered an Alibaba Cloud account with the OSS activated.

Installation

Introduce framework directly

The OSS iOS SDK framework needs to be introduced.

You can use this AliyunOSSSDK.xcworkspace,and select scheme which named AliyunOSSSDK OSX to directly generate a framework in MacOS :

# Clone the project
$ git clone [email protected]:aliyun/aliyun-oss-ios-sdk.git

# Enter the directory
$ cd aliyun-oss-ios-sdk

# Run the packaging script
$ sh ./buildiOSFramework.sh

# Enter the generated packaging directory  where the AliyunOSSiOS.framework will be generated
$ cd Products && ls

In Xcode, drag the OSS iOS SDK framework and drop it to your target, and select Copy items if needed in the pop-up box.

Pod dependency

If your project manages dependencies using a Pod, add the following dependency to the Podfile. In this case, you do not need to import the OSS iOS SDK framework.

pod 'AliyunOSSiOS'

CocoaPods is an outstanding dependency manager. Recommended official reference documents: CocoaPods Installation and Usage Tutorial.

You can directly introduce the OSS iOS SDK framework or the Pod dependency, either way works.

Introduce the header file to the project

#import <AliyunOSSiOS/AliyunOSSiOS.h>

Note: After you introduce the OSS iOS SDK framework, add -ObjC to Other Linker Flags of Build Settings in your project. If the -force_load option has been configured for your project, add -force_load <framework path>/AliyunOSSiOS.

Compatible with IPv6-Only networks

The OSS mobile SDK has introduced the HTTPDNS for domain name resolution to solve the problem of domain resolution hijacking in a wireless network and directly uses IP addresses for requests to the server. In the IPv6-Only network, compatibility issues may occur. The app has officially issued the review requirements for apps, requiring apps to be IPv6-only network compatible. To this end, the SDK starts to be compatible from V2.5.0. In the new version, apart from -ObjC settings, two system libraries should be introduced:

libresolv.tbd
SystemConfiguration.framework
CoreTelephony.framework

The ATS policy of Apple

At the WWDC 2016, Apple announced that starting January 1, 2017, all the apps in Apple App Store must enable App Transport Security (ATS). That is to say, all newly submitted apps are not allowed to use NSAllowsArbitraryLoads to bypass the ATS limitation by default. We'd better ensure that all network requests of the app are HTTPS-encrypted. Otherwise the app may have troubles to pass the review.

This SDK provides the support in V2.6.0 and above. Specifically, the SDK will not issue any non-HTTPS requests. At the same time, the SDK supports endpoint with the https:// prefix. You only need to set the correct HTTPS endpoint to ensure that all network requests comply with the requirements.

Note:

  • Use a URL with the https:// prefix for setting the endpoint.
  • Ensure that the app will not send non-HTTPS requests when implementing signing and getting STSToken callbacks.

Descriptions of OSSTask

You will get an OSSTask immediately for all operations that call APIs:

OSSTask * task = [client getObject:get];

You can configure a continuation for the task to achieve asynchronous callback. For example,

[task continueWithBlock: ^(OSSTask *task) {
	// do something
	...

	return nil;
}];

You can also wait till the task is finished (synchronous wait). For example,

[task waitUntilFinished];

...

Quick start

The basic object upload and download processes are demonstrated below. For details, you can refer to the following directories of this project:

test: Click to view details;

or

demo: click to view details.

Step-1. Initialize the OSSClient

We recommend STS authentication mode to initialize the OSSClient on mobile. For details about authentication, refer to the Access Control section in the complete official documentation provided in the following link.

Notice:if your app's buckets only at one data center,we recommend you to keep the lifecycle of OSSClient's instance consistent with your app.the code below demonstrate the usage

@interface AppDelegate ()

@property (nonatomic, strong) OSSClient *client;

@end

/**
 * the url to fetch sts info,for detail please refer to https://help.aliyun.com/document_detail/31920.html
 */
#define OSS_STS_URL                 @"oss_sts_url"


/**
 * the endpoint for OSS used in app, for detail please refer to https://help.aliyun.com/document_detail/31837.html
 */
#define OSS_ENDPOINT                @"your bucket's endpoint"

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    // initialize OSSClient
    [self setupOSSClient];
    
    return YES;
}

- (void)setupOSSClient {

    // initialize credential provider,which auto fetch and update sts info from sts url.
    OSSAuthCredentialProvider *credentialProvider = [[OSSAuthCredentialProvider alloc] initWithAuthServerUrl:OSS_STS_URL];
    
    // set config for oss client networking
    OSSClientConfiguration *cfg = [[OSSClientConfiguration alloc] init];
    
    _client = [[OSSClient alloc] initWithEndpoint:OSS_ENDPOINT credentialProvider:credentialProvider clientConfiguration:cfg];
}

Step-2. Upload a file

Suppose that you have a bucket in the OSS console. An OSSTask will be returned after each SDK operation. You can configure a continuation for the task to achieve asynchronous callback. You can also use the waitUntilFinished to block other requests and wait until the task is finished.

OSSPutObjectRequest * put = [OSSPutObjectRequest new];

put.bucketName = @"<bucketName>";
put.objectKey = @"<objectKey>";

put.uploadingData = <NSData *>; // Directly upload NSData

put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
	NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
};

OSSTask * putTask = [client putObject:put];

[putTask continueWithBlock:^id(OSSTask *task) {
	if (!task.error) {
		NSLog(@"upload object success!");
	} else {
		NSLog(@"upload object failed, error: %@" , task.error);
	}
	return nil;
}];

// Wait until the task is finished
// [putTask waitUntilFinished];

Step-3. Download a specified object

The following code downloads a specified object as NSData:

OSSGetObjectRequest * request = [OSSGetObjectRequest new];
request.bucketName = @"<bucketName>";
request.objectKey = @"<objectKey>";

request.downloadProgress = ^(int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
	NSLog(@"%lld, %lld, %lld", bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
};

OSSTask * getTask = [client getObject:request];

[getTask continueWithBlock:^id(OSSTask *task) {
	if (!task.error) {
		NSLog(@"download object success!");
		OSSGetObjectResult * getResult = task.result;
		NSLog(@"download result: %@", getResult.downloadedData);
	} else {
		NSLog(@"download object failed, error: %@" ,task.error);
	}
	return nil;
}];

// Use a blocking call to wait until the task is finished
// [task waitUntilFinished];

Complete documentation

The SDK provides advanced upload, download, resumable upload/download, object management and bucket management features. For details, see the complete official documentation: click to view details.

API documentation

Click to view details.

F&Q

1.how to support armv7s?

​arm is backward compatible, armv7 library is also suitable for app that needs to support armv7s. If you still need to optimize armv7s, you could set up as shown below.

list1

License

  • Apache License 2.0.

Contact us

aliyun-oss-ios-sdk's People

Contributors

1019272778 avatar baiyubin2020 avatar binghaiwang avatar duan007a avatar huiguangjun avatar qixu001 avatar readmecritic avatar sdlcdhc avatar sducodemonkey avatar strox avatar wanghui9309 avatar wlll129 avatar wushuai1415 avatar xuyecan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

aliyun-oss-ios-sdk's Issues

resumableUploadFile完成回调错误

以下在resumableUploadFile的回调是错的, 有的task可能被取消了,

 if (task.error) {
    onComplete(NO, task.error);
} else {
    onComplete(YES, nil);
}

不能仅仅通过task.error去判断是否上传成功, 正确的判断应该是:

completed = YES; cancelled = NO; faulted = NO

麻烦你们修复一下. 谢谢.

这个Bug我已经在你们的demo工程中提了.

在对私有Bucket签名时会一直阻塞主线程

NSString * constrainURL = nil;
OSSTask * task = [client presignConstrainURLWithBucketName:bucketName withObjectKey:objectKey withExpirationInterval: 30 * 60];
if (!task.error) {
    constrainURL = task.result;
} else {
    NSLog(@"error: %@", task.error);
}
return constrainURL;

在通过如上代码进行私有Bucket加签时,程序主线程会被阻塞,并且打印了如下log:
Warning: A long-running operation is being executed on the main thread.
Break on warnBlockingOperationOnMainThread() to debug.

请问这是什么原因造成的?该怎么解决?

批量上传的问题 批量上传

同时上传两张图片,一张以put.uploadingData的方式上传,一张以put.uploadingFileURL的方式上传,只会成功一张,而且有一个上传,不会触发成功和失败的回调

Https

你们昨天修改了关于适配https的东西,但现在cocoapods上面还不是最新版吧。

OSSClient多实例上传会死锁

使用resumableUploadFile 创建一个client上传文件, 取消上传并且释放这个client. 再次上传并且创建一个client. 报以下的warning,

A background URLSession with identifier com.aliyun.oss.backgroundsession already exists!

并且一直死锁在:

            BFTask * uploadPartTask = [self uploadPart:uploadPart];
        [uploadPartTask waitUntilFinished];

如果你们的client要设计成单例的, 要在文档中说明.

IOS 2.0.2 上传文件问题?

上传文件 回调中 没有 文件在云端的 URL 嘛??

需要自己进行拼接对吗?

但是我看到 开启log日志后,你们打印出好多次文件云端的URL

你们的OSS 在设计上就是要用户 在上传成功的 回调中 自己拼接URL
而不是你们返回 这个URL ,对吗?

NSOperation 多次快速调用[request cancel] 无法取消

实现一个NSOperation, 在Operation里面上传文件, 运行一个CFRunLoopRun() (使用RunLoop等待上传完成, 同时接收外面的暂停事件). 如果此时接收到外部的取消事件, 则立即调用 [request cancel] 和CFRunLoopStop(CFRunLoopGetCurrent()) 结束这个NSOperation. 如果外部希望重新开始上传, 则创建一个新的OPeration上传同一个文件. 如此切换, 前面1,2次能成功, 后面不能成功, 发现一直在上传. 我必须等待continueWithBlock事件之后再结束RunLooper才不会发生这样的情况. 虽然我找到绕过的方法了, 但是希望你们解决一下.

你们可以实现这样的一个Demo试一下:
一个按钮: 一个暂停状态, 一个继续状态, 继续时把operation添加进运行. 暂停时调用cancel和stopRunLoop.
一个OperationQueue, 同时只有一个Opeation运行, 上传同一个文件, 使用putObject方法.

这个按钮去监听任务上传的状态, 如果正在上传, 显示暂停, 停止上传, 显示继续.

然后一直点, 迅速点,多次点这个按钮, 如果cancel时同时stop了RunLoop, 就会无法停止上传文件. 要等你们的取消的结束的Block回调再Stop runloop, 才能正常运作.

如果不能解决这个Bug, 希望其他人开发时能看到这个坑,我的工程里面是必现的.

用OSSFederationCredentialProvider获取token时报错;

OSSCredentialProvider credentialProvider = new OSSFederationCredentialProvider() {
@OverRide
public OSSFederationToken getFederationToken() {
return getToken();
}
};

Can't get a federation token
Encounter local execpiton: java.io.IOException: Can't get a federation token
Can't get a federation token

bitcode bundle could not be generated

bitcode bundle could not be generated because '/ios/AliyunOSSiOS.framework/AliyunOSSiOS(OSSTaskCompletionSource.o)' was built without full bitcode. All object files and libraries for bitcode must be generated from Xcode Archive or Install build for architecture arm64 我按照网上提供的在Other C Flags 添加-fembed-bitcode 也没能解决

OSSGetFederationTokenBlock无限调用直到崩溃,不知道哪里写错,请帮忙看一下(iOS8和iOS9下有问题,iOS7下没有崩)

现在用的是最新版的SDK 9月22日更新的版本
电脑系统10.11 Xcode 7.0
在使用STS授权模式的情况下,调用
BFTask *putTask = [_client putObject:putObjectRequest];
[putTask continueWithBlock:^id(BFTask *task) {
DebugLog(@"\n--------------------Task Completed------------------");
return nil;
}];
之后,OSS SDK会无限制调用OSSGetFederationTokenBlock来获取token,最后崩溃。
初始化client的代码如下,按照官方demo来的:
screen shot 2015-09-30 at 11 49 54 pm

  • (void)initClient {
    // 获取签名方法
    // @weakify(self);
    id credentialProvider = [[OSSFederationCredentialProvider alloc] initWithFederationTokenGetter:^OSSFederationToken *{
    // @strongify(self);
    BFTaskCompletionSource *tcs = [BFTaskCompletionSource taskCompletionSource];

    ICFetchOSSAccessKeyRequest *fetchOSSTokenRequest = [ICFetchOSSAccessKeyRequest request];
    [fetchOSSTokenRequest startWithCompletionBlockWithSuccess:^(ICBaseRequest *request) {
        DebugLog(@"\n阿里云上传token: %@", request.decryptedResponseString);
        JSONModelError *error = nil;
        CQOSSAccessInfoModel *model = [[CQOSSAccessInfoModel alloc] initWithString:request.decryptedResponseString usingEncoding:NSUTF8StringEncoding error:&error];
        if (!error && model && [model operationSuccess]) {
            self.lastUpdateTimeStamp = [ICUtility currentTimeStamp];
    
            [tcs setResult:model];
        }else {
            [tcs setError:error];
        }
    }
                                                       failure:^(ICBaseRequest *request) {
                                                           [tcs setError:[NSError errorWithDomain:@"com.icangqu.cangqu" code:100 userInfo:@{@"reason": @"request fail"}]];
                                                       }];
    [tcs.task waitUntilFinished];
    
    if (tcs.task.error) {
        DebugLog(@"\nempty federation token");
        return nil;
    }else {
    
        CQOSSAccessInfoModel *model = (CQOSSAccessInfoModel *)tcs.task.result;
    
        OSSFederationToken *federationToken = [[OSSFederationToken alloc] init];
    
        federationToken.tAccessKey = model.accessKeyId;
        federationToken.tSecretKey = model.accessKeySecret;
        federationToken.tToken = model.securityToken;
        federationToken.expirationTimeInMilliSecond = model.expirationDate.longLongValue;
    
        DebugLog(@"\nsuccess get federationtoken");
    
        return federationToken;
    }
    

    }];

    OSSClientConfiguration *conf = [[OSSClientConfiguration alloc] init];
    conf.maxRetryCount = 3;
    conf.enableBackgroundTransmitService = NO;
    conf.timeoutIntervalForRequest = 15;
    conf.timeoutIntervalForResource = 24 * 60 * 60;

    self.ossClient = [[OSSClient alloc] initWithEndpoint:kOSSDefaultBucketHostId
    credentialProvider:credentialProvider
    clientConfiguration:conf];

}

上传成功时, 取消任务, 无法再继续上传文件, 需要重新上传

使用resumableUploadFile函数 上传文件. 然后一直狂切换暂停和继续上传, 在上传成功后, uploadId应该是被删除了, 但是回调的值如下:
2015-10-23 17:03:35.514 KeyShare[12205:481048] 阿里云断点续传上传文件进度 1.000000
2015-10-23 17:03:35.515 KeyShare[12205:481048] 阿里云断点续传结束上传文件 task<BFTask: 0x7fbbf4026ae0; completed = YES; cancelled = YES; faulted = NO; result:(null)>, uploadId:33648A455FC34103ADF55430AF084C19

可以看到其实这时已经是上传成功了, 但是用户点击了暂停上传, 导致返回的是canceled, 但是下次用这个uploadId, 是无法查询到上传的分块的(已经上传成功了). 所以又会重新上传.

看一下这个怎么解决.

STS Token鉴权什么时候可以开始用?

AK/SK鉴权效率非常低下, 我测试MultipartUploadRequest上传时(resumableUploadFile这个函数), 发现每一次progress回调, 都会向服务器请求一次签名. 这样效率非常低, 而且我们服务器压力也非常大. 能不能优化SDK.

目前STS Token这种方式还用不了是吧?

OSS上传图片时怎么使用Background Transfer Service?

这是我目前的设置
初始化client:

    OSSClientConfiguration *conf = [OSSClientConfiguration new];
    conf.enableBackgroundTransmitService = YES;

    _backgroundTransferClient = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential clientConfiguration:conf];

设置回调:

    - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler
    {

        [[[EZOAliyunOSSManager sharedInstance] backgroundTransferClient] setBackgroundSessionCompletionHandler:completionHandler];
        NSLog(@"completionHandler called");

    }

开始上传:

    OSSClient *client = [[EZOAliyunOSSManager sharedInstance] backgroundTransferClient];
    BFTask * putTask = [client putObject:put];

但我上传后发现你们的OSSNetworking.m中的URLSessionDidFinishEventsForBackgroundURLSession始终没有被调用,麻烦解答一下,多谢

无网络删除图片Block无法回调

开始上传照片时断开网络连接进入飞行模式,- (OSSTask *)continueWithBlock:(OSSContinuationBlock)block 方法block永久不会回调,页面上的loading弹窗无法消失。

打包framework时错误

Build settings from command line:
SDKROOT = iphoneos10.2
SYMROOT = ./build

xcodebuild: error: The project named "AliyunOSSiOS" does not contain a scheme named "AliyunOSSiOS". The "-list" option can be used to find the names of the schemes in the project.
Build settings from command line:
SDKROOT = iphonesimulator10.2
SYMROOT = ./build

xcodebuild: error: The project named "AliyunOSSiOS" does not contain a scheme named "AliyunOSSiOS". The "-list" option can be used to find the names of the schemes in the project.
cp: ./build/Release-iphoneos/AliyunOSSiOS.framework: No such file or directory
fatal error: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/lipo: can't open input file: ./build/Release-iphoneos/AliyunOSSiOS.framework/AliyunOSSiOS (No such file or directory)
rm: ./build: No such file or directory

OSSCustomSignerCredentialProvider 自签模式的疑问

OSS开发者你好,我现在在客户端将相关参数(请求方法、文件路径、MD5)提交给业务服务器,服务器会生成并返回对应的时间以及相应的 Signature,但是目前的 SDK 自签模式似乎没有提供接口修改请求的时间?请问是否有计划提供这种接口?
如果不提供这种接口,用户的手机时间不正确会导致无法使用 OSS 服务啊。

使用cocoasPod也装不了

Unable to satisfy the following requirements:

  • AliyunOSSiOS (~> 2.6.0) required by Podfile

None of your spec sources contain a spec satisfying the dependency: AliyunOSSiOS (~> 2.6.0).

You have either:

  • out-of-date source repos which you can update with pod repo update.
  • mistyped the name or version.
  • not added the source repo that hosts the Podspec to your Podfile.

Note: as of CocoaPods 1.0, pod repo update does not happen on pod install by default.

uploadId 应该由外部来管理

目前uploadId是由resumableUploadFile这个函数通过UserDefault来管理的. 看似没什么问题, 其实导致了两个严重的问题:

  1. 外部无法控制应该继续上传还是重新上传. 虽然有判断文件的修改时间, 但是文件的修改时间这个属性是可以修改的. 这导致了一个隐性的Bug.
  2. 如果一个文件上传了一部分, 被删除了, 导致了userDefault的泄露.

经过我的测试, 我测试了1000多个上传, 后面发现, userDefault里面有大量的recordKey, 虽然只占用了用户少量的空间, 但是积少成多, 而且永久不可删除.

虽然我没有给出更好的设计方法. 我目前的实现是这样的. 可能还有更好的设计方法, 希望你们改进.

   /**
 *  @param resumableUploadId 如果传入nil, 不会继续上传, 如果传入与上次未成功相同的值, 将会继续           上次未完成的上传
 */
 - (OSSTaskHandler *)uploadFileResumable:(NSString *)filePath
                        resumableId:(NSString *)resumableUploadId
                    withContentType:(NSString *)contentType
                     withObjectMeta:(NSDictionary *)meta
                       toBucketName:(NSString *)bucketName
                        toObjectKey:(NSString *)objectKey
                        onCompleted:(void(^)(BFTask *task,NSString *resumableUploadId))onCompleted
                         onProgress:(void(^)(float progress))onProgress;

我将Framework拖进我的工程,发现有这个问题。

Undefined symbols for architecture arm64:
"_res_9_getservers", referenced from:
-[OSSIPv6Adapter getDNSServersIpStack] in AliyunOSSiOS(OSSIPv6Adapter.o)
"_res_9_ninit", referenced from:
-[OSSIPv6Adapter getDNSServersIpStack] in AliyunOSSiOS(OSSIPv6Adapter.o)
"_res_9_ndestroy", referenced from:
-[OSSIPv6Adapter getDNSServersIpStack] in AliyunOSSiOS(OSSIPv6Adapter.o)
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

同一 client 进行多次不同的 HEAD 请求,会遗失部分调用回调

0.如题,根据文档方法,使用 HEAD 方法判断文件是否存在: https://help.aliyun.com/document_detail/32064.html?spm=5176.doc32061.6.354.ST0hpM

1.client 生成方法

+ (OSSClient *)clientWithEndPoint:(NSString *)endPoint {
    static NSMutableDictionary<NSString *, OSSClient *> *clients;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        clients = [NSMutableDictionary new];
    });
    OSSClient *client = clients[endPoint];
    if (client == nil) {
        OSSClientConfiguration *conf = [OSSClientConfiguration new];
        conf.maxRetryCount = 2;
        conf.timeoutIntervalForRequest = 30;
        conf.timeoutIntervalForResource = 24 * 60 * 60;

        client = [[OSSClient alloc] initWithEndpoint:endPoint credentialProvider:self.stsCredential clientConfiguration:conf];
        [clients setObject:client forKey:endPoint];
    }

    return client;
}

2.访问控制的方式是 FederationToken

static id<OSSCredentialProvider> stsCredential;
static dispatch_semaphore_t stsRequestSemaphore;
+ (id<OSSCredentialProvider>)stsCredential {
    if (stsCredential == nil) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            stsRequestSemaphore = dispatch_semaphore_create(0);
            stsCredential = [[OSSFederationCredentialProvider alloc] initWithFederationTokenGetter:^OSSFederationToken *{
                WBAlicloudTokenRequestModel *requestModel = [WBAlicloudTokenRequestModel new];
                DKDataManager *dataManager = [DKDataManager new];
                OSSFederationToken *resultToken = [OSSFederationToken new];
                [dataManager requestWithRequestModel:requestModel completedBlock:^(DKResponseModel *responseModel, NSError *error) {
                    if (error == nil) {
                        WBAlicloudTokenResponseModel *response = (WBAlicloudTokenResponseModel *)responseModel;
                        resultToken.tAccessKey = response.AccessKeyId;
                        resultToken.tSecretKey = response.AccessKeySecret;
                        resultToken.tToken = response.SecurityToken;
                        resultToken.expirationTimeInGMTFormat = response.Expiration;
                    }
                    dispatch_semaphore_signal(stsRequestSemaphore);
                }];
                dispatch_semaphore_wait(stsRequestSemaphore, DISPATCH_TIME_FOREVER);
                return resultToken;
            }];
        });
    }

    return stsCredential;
}

3.连续做 20 次 HEAD 方法

NSLog(@"FLAG 1");
[headTask continueWithBlock:^id(OSSTask *task) {
    NSLog(@"FLAG 2");
    NSLog(@"%@", task.error);
    return nil;
}];

会发现 FLAG 1 打印次数有很大概率比 FLAG 2 多。

4.OSS_IOS_SDK_VERSION 2.5.1

不太明白是不是自己的操作哪里有问题。

resumableUploadFile recordKey的Bug

原代码:

   [NSString stringWithFormat:@"%@-%@-%@-%@", bucketName, objectKey, filePath, lastModified];

其中filePath这一句是有Bug的. filePath在iOS里面是有沙盒机制的,前面的路径每次运行都是随机的, 不能去记录一个完整的路径, 会有Bug.

如:

/Users/gzc/Library/Developer/CoreSimulator/Devices/FA0B0EC6-9366-4905-B9C1-E80DAF59EBC4/data/Containers/Data/Application/9C6F610E-D902-4450-AB8E-CA69C3F1A61A/Documents/jaxusData/userData/5617a1218a2f2d2c0c054925/publishAsset/image/66E6027E-ABDE-431B-A3FF-15251502CF3E-2015-10-22

上面的路径中, 只有/Documents/jaxusData/userData/5617a1218a2f2d2c0c054925/publishAsset/image/66E6027E-ABDE-431B-A3FF-15251502CF3E-2015-10-22这个是固定的.

而其变化的是:/9C6F610E-D902-4450-AB8E-CA69C3F1A61A这一段.

以上为模拟器的测试结果, 每次运行都会变化.

真机应该是类似的.

请你们处理一下

resumableUploadFile 上传小文件取消后无法再次恢复

小文件, 只有一个分块, 如果取消了, 之后重试时, 一直是错误的. 原因如下:

小文件重试时, 查询到的OSSListPartsResult格式并不是普通的格式
Printing description of result->_parts:
{
ETag = ""0654ECA0DA09B0B95BC32B73072B002D"";
LastModified = "2015-10-22T06:31:39.000Z";
PartNumber = 1;
Size = 166328;
}

此时调用以下代码会一直失败 , 因为这个Dic的key全对应不上, 所以之后一直无法再成功了.

             [result.parts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                NSDictionary * dict = obj;
                uploadedLength += [[dict objectForKey:OSSSizeXMLTOKEN] longLongValue];
            }];

望解决. 谢谢.

README.md 的 endpoint 有误

少了 @""

现为:

NSString *endpoint = "http://oss-cn-hangzhou.aliyuncs.com";

应为:

NSString *endpoint = @"http://oss-cn-hangzhou.aliyuncs.com";

升级swift3.0之后,一上传就报错

如题,具体报错内容为:
`#pragma mark - Execution

  • (void)execute:(void(^)())block {
    self.block(block);
    }

@end`
相关文件:OSSExecutor.m
控制台输出:(lldb)

Warning: A long-running operation is being executed on the main thread. Break on warnBlockingOperationOnMainThread() to debug.

  1. 根据demo、测试用例和文档上的方法运行waitUntilFinished都会长期阻塞主线程
    Warning: A long-running operation is being executed on the main thread. Break on warnBlockingOperationOnMainThread() to debug.
        OSSTask * initTask = [client multipartUploadInit:init];
        [initTask waitUntilFinished];
  1. 我想问一下,要实现断点续传,是不是只按照文档这部分,是没办法实现的,还需要通过分片上传,这部分代码只是用在分片上传暂停之后,继续续传
__block NSString * uploadId = nil;
OSSInitMultipartUploadRequest * init = [OSSInitMultipartUploadRequest new];
init.bucketName = <bucketName>;
init.objectKey = <objectKey>;
// 以下可选字段的含义参考:https://docs.aliyun.com/#/pub/oss/api-reference/multipart-upload&InitiateMultipartUpload
// append.contentType = @"";
// append.contentMd5 = @"";
// append.contentEncoding = @"";
// append.contentDisposition = @"";
// init.objectMeta = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"value1", @"x-oss-meta-name1", nil];
// 先获取到用来标识整个上传事件的UploadId
OSSTask * task = [client multipartUploadInit:init];
[[task continueWithBlock:^id(OSSTask *task) {
    if (!task.error) {
        OSSInitMultipartUploadResult * result = task.result;
        uploadId = result.uploadId;
    } else {
        NSLog(@"init uploadid failed, error: %@", task.error);
    }
    return nil;
}] waitUntilFinished];
// 获得UploadId进行上传,如果任务失败并且可以续传,利用同一个UploadId可以上传同一文件到同一个OSS上的存储对象
OSSResumableUploadRequest * resumableUpload = [OSSResumableUploadRequest new];
resumableUpload.bucketName = <bucketName>;
resumableUpload.objectKey = <objectKey>;
resumableUpload.uploadId = uploadId;
resumableUpload.partSize = 1024 * 1024;
resumableUpload.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
    NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
};
resumableUpload.uploadingFileURL = [NSURL fileURLWithPath:<your file path>];
OSSTask * resumeTask = [client resumableUpload:resumableUpload];
[resumeTask continueWithBlock:^id(OSSTask *task) {
    if (task.error) {
        NSLog(@"error: %@", task.error);
        if ([task.error.domain isEqualToString:OSSClientErrorDomain] && task.error.code == OSSClientErrorCodeCannotResumeUpload) {
            // 该任务无法续传,需要获取新的uploadId重新上传
        }
    } else {
        NSLog(@"Upload file success");
    }
    return nil;
}];
// [resumeTask waitUntilFinished];
// [resumableUpload cancel];

能回答一下吗,谢谢

使用自实现的方法获取FederationToken时,无法初始化OSSClient成功

我的初始化代码如下:

id<OSSCredentialProvider> credential = [[OSSFederationCredentialProvider alloc] initWithFederationTokenGetter:^OSSFederationToken * {
        NSURL * url = [NSURL URLWithString:AliyunOSSSTSSetUpURL];
        NSURLRequest * request = [NSURLRequest requestWithURL:url];
        OSSTaskCompletionSource * tcs = [OSSTaskCompletionSource taskCompletionSource];
        NSURLSession * session = [NSURLSession sharedSession];
        NSURLSessionTask * sessionTask = [session dataTaskWithRequest:request
                                                    completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                        if (error) {
                                                            [tcs setError:error];
                                                            return;
                                                        }
                                                        [tcs setResult:data];
                                                    }];
        [sessionTask resume];
        [tcs.task waitUntilFinished];
        if (tcs.task.error) {
            NSLog(@"get token error: %@", tcs.task.error);
            return nil;
        } else {
            NSDictionary * object = [NSJSONSerialization JSONObjectWithData:tcs.task.result
                                                                    options:kNilOptions
                                                                      error:nil];
            OSSFederationToken * token = [OSSFederationToken new];
            token.tAccessKey = [object objectForKey:@"accessKeyId"];
            token.tSecretKey = [object objectForKey:@"accessKeySecret"];
            token.tToken = [object objectForKey:@"securityToken"];
            token.expirationTimeInGMTFormat = [object objectForKey:@"expiration"];
            NSLog(@"get token: %@", token);
            return token;
        }
    }];

    OSSClientConfiguration * conf = [OSSClientConfiguration new];
    conf.maxRetryCount = 2;
    conf.timeoutIntervalForRequest = 30;
    conf.timeoutIntervalForResource = 24 * 60 * 60;

    self.client = [[OSSClient alloc] initWithEndpoint:endPoint credentialProvider:credential clientConfiguration:conf];

如下是Log:
Start resolved network to see if in IPv6-Only env
[-[OSSIPv6Adapter isIPv6OnlyNetwork]]: Not IPv6-Only network now
[-[OSSIPv6Adapter appDidBecomeActiveFunc]]: App become active, refresh IPv6-Only status.

iOS 7 ResumableuploadFile 死锁

一直卡在这里,

        uploadPart.uploadPartData = [handle readDataOfLength:(NSUInteger)readLength];
        BFTask * uploadPartTask = [self uploadPart:uploadPart];
        [uploadPartTask waitUntilFinished];

经发现, 只要执行uploadPart有异常, 都会死锁在这里. 多个OSSClient实例也是一样的. 我觉得, 无论发生何异常, 都不应该死锁在这里. 这个异常, 在iOS 7上面可以重现

关于获取图片资源的处理

我没有找到关于OSSGetObjectRequestxOssProcess属性的格式文档。
比如:有一个规则名为abc的图片规则样式,xOssProcess的值应该是什么呢?
我试了好多值都没用:abc@!abc, !abc

还有就是对私有bucket的图片资源,生成时效性的url。无法加入图片处理配置。

有时候任务调用cancel无法取消

检查了networking.m文件,可能问题发生在:调用cancel时,如果sessionTask还未建立,则不执行任何动作。考虑到,sessionTask建立前,获取sts token可能存在网络交互,导致较长耗时,这个过程中cancel的概率是有一定概率的,不能忽略这种情况。

所以,应该在requestdelegate中加入cancelled标志,建立sessionTask前判断下如果已经取消,就放弃任务。

和facebook库有冲突啊

duplicate symbol kBFMultipleErrorsError in:
*
/Build/Products/Debug-iphonesimulator/libAliyunOSSiOS.a(OSSTask.o)
*/FacebookSDK.framework/FacebookSDK(Bolts.o)
duplicate symbol warnBlockingOperationOnMainThread in:
*
/Build/Products/Debug-iphonesimulator/libAliyunOSSiOS.a(OSSTask.o)
*
/FacebookSDK.framework/FacebookSDK(BFTask.o)
ld: 2 duplicate symbols for architecture x86_64

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.