Filestack Swift SDK
这是 Filestack 的官方 Swift SDK,一个 API 和内容管理系统,可轻松将强大的文件上传和转换功能添加到任何 Web 或移动应用中。
资源
要求
- Xcode 10.2+ (支持 SPM 需要 Xcode 12+)
- Swift 4.2+ / Objective-C
- iOS 11.0+
安装
CocoaPods
CocoaPods 是 Cocoa 项目的依赖项管理器。您可以使用以下命令安装它:
$ gem install cocoapods
要使用 CocoaPods 将 FilestackSDK 集成到您的 Xcode 项目中,在您的 Podfile
中指定它:
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '11.0'
use_frameworks!
target '<Your Target Name>' do
pod 'FilestackSDK', '~> 2.7.0'
end
然后,运行以下命令:
$ pod install
Carthage
Carthage 是一个去中心化的依赖项管理器,负责构建您的依赖项并为您提供二进制框架。
您可以使用以下命令使用 Homebrew 安装 Carthage:
$ brew update
$ brew install carthage
要使用 Carthage 将 FilestackSDK 集成到您的 Xcode 项目中,在您的 Cartfile
中指定它:
github "filestack/filestack-swift" ~> 2.7.0
运行 carthage update
来构建框架,并将构建好的 FilestackSDK.framework
拖入您的 Xcode 项目。
Swift 包管理器
将 https://github.com/filestack/filestack-swift.git
添加到您的 Xcode 项目的 Swift 包管理器依赖中。
如果您正在将 FilestackSDK
添加到您自己的 Swift 包中,请在您的 Package.swift
中声明该依赖。
dependencies: [
.package(url: "https://github.com/filestack/filestack-swift.git", .upToNextMajor(from: "2.7.0"))
]
手动
嵌入式框架
打开终端,切换到你的顶级项目目录,如果你的项目还没有初始化成git仓库,请运行以下命令:
$ git init
通过以下命令添加FilestackSDK及其依赖项作为git子模块:
$ git submodule add https://github.com/filestack/filestack-swift.git
打开新的filestack-swift
文件夹,并将FilestackSDK.xcodeproj
拖放到你的应用Xcode项目的Project Navigator中。
应该出现在你的应用程序蓝色项目图标下面。它位于其他所有Xcode组之上或之下都不重要。在Project Navigator中选择FilestackSDK.xcodeproj
,并验证部署目标与你的应用程序目标匹配。
接下来,在Project Navigator中(蓝色项目图标)选择你的应用程序项目,导航到目标配置窗口,并在侧边栏的“Targets”标题下选择应用程序目标。
在窗口顶部的标签栏中,打开“General”面板。
在“Embedded Binaries”部分下点击+按钮,并选择iOS的FilestackSDK.framework
。
使用方法
集成到Swift项目中
-
将框架导入到你的代码中
import FilestackSDK
-
通过提供你的API密钥和可选的
Security
对象来实例化一个Client
对象// Initialize a `Policy` with the expiry time and permissions you need. let oneDayInSeconds: TimeInterval = 60 * 60 * 24 // expires tomorrow let policy = Policy(// Set your expiry time (24 hours in our case) expiry: Date(timeIntervalSinceNow: oneDayInSeconds), // Set the permissions you want your policy to have call: [.pick, .read, .store]) // Initialize a `Security` object by providing a `Policy` object and your app secret. // You can find and/or enable your app secret in the Developer Portal. guard let security = try? Security(policy: policy, appSecret: "YOUR-APP-SECRET") else { return } // Initialize your `Client` object by passing a valid API key, and security options. let client = Client(apiKey: "YOUR-API-KEY", security: security)
集成到Objective-C项目中
-
将框架导入到你的代码中
@import FilestackSDK;
-
通过提供你的API密钥和可选的
FSSecurity
对象来实例化一个FSClient
对象// Initialize a `FSPolicy` object with the expiry time and permissions you need. NSTimeInterval oneDayInSeconds = 60 * 60 * 24; // expires tomorrow NSDate *expiryDate = [[NSDate alloc] initWithTimeIntervalSinceNow:oneDayInSeconds]; FSPolicyCall permissions = FSPolicyCallPick | FSPolicyCallRead | FSPolicyCallStore; FSPolicy *policy = [[FSPolicy alloc] initWithExpiry:expiryDate call:permissions]; NSError *error; // Initialize a `Security` object by providing a `FSPolicy` object and your app secret. // You can find and/or enable your app secret in the Developer Portal. FSSecurity *security = [[FSSecurity alloc] initWithPolicy:policy appSecret:@"YOUR-APP-SECRET" error:&error]; if (error != nil) { NSLog(@"Error instantiating policy object: %@", error.localizedDescription); return; } // Initialize your `Client` object by passing a valid API key, and security options. FSClient *client = [[FSClient alloc] initWithApiKey:@"YOUR-API-KEY" security:security];
有关更多信息,请参阅我们的API参考。
直接上传文件到存储位置
常规和智能摄取上传都使用了类Client
中可用的相同API函数。但是,如果你的账户启用了智能摄取支持,而你更喜欢使用常规上传机制,你可以通过将useIntelligentIngestionIfAvailable
参数设置为false
来禁用它(请参阅下面的相关示例。)
Swift示例
// Define upload options (see `UploadOptions` for all the available options)
// Here we use `.defaults` which implies:
// * preferIntelligentIngestion = true
// * startImmediately = true
// * deleteTemporaryFilesAfterUpload = false
// * storeOptions = StorageOptions(location: .s3, access: .private)
// * defaultPartUploadConcurrency = 5
// * defaultChunkUploadConcurrency = 8
// * chunkSize = 5mbs
let uploadOptions = UploadOptions.defaults
// For instance, if you don't want to use Intelligent Ingestion regardless of whether it is available:
uploadOptions.preferIntelligentIngestion = false
// You may also easily override the default store options:
uploadOptions.storeOptions = StorageOptions(// Store location (e.g. S3, Dropbox, Rackspace, Azure, Google Cloud Storage)
location: .s3,
// AWS Region for S3 (e.g. "us-east-1", "eu-west-1", "ap-northeast-1", etc.)
region: "us-east-1",
// The name of your S3 bucket
container: "YOUR-S3-BUCKET",
// Destination path in the store.
// You may use a path to a folder (e.g. /public/) or,
// alternatively a path containing a filename (e.g. /public/oncorhynchus.jpg).
// When using a path to a folder, the uploaded file will be stored at that folder using a
// filename derived from the original filename.
// When using a path to a filename, the uploaded file will be stored at the given path
// using the filename indicated in the path.
path: "/public/oncorhynchus.jpg",
// Custom MIME type (useful when uploadable has no way of knowing its MIME type)
mimeType: "image/jpg",
// Access permissions (either public or private)
access: .public,
// An array of workflow IDs to trigger for each upload
workflows: ["WF-1", "WF-2"]
)
let uploadable = URL(...) // may also be Data or arrays of URL or Data.
// Call the function in your `Client` instance that takes care of uploading your Uploadable.
// Please notice that most arguments have sensible defaults and may be ommited.
let uploader = client.upload(// You may pass an URL, Data or arrays of URL or Data
using: uploadable,
// Set the upload options here. If none given, `UploadOptions.defaults`
// is assumed.
options: uploadOptions,
// Set the dispatch queue where you want your upload progress
// and completion handlers to be called.
// Remember that any UI updates should be performed on the
// main queue.
// You can omit this parameter, and the main queue will be
// used by default.
queue: .main,
// Set your upload progress handler here (optional)
uploadProgress: { progress in
// Here you may update the UI to reflect the upload progress.
print("Progress: \(progress)")
}) { response in
// Try to obtain Filestack handle
if let json = response?.json, let handle = json["handle"] as? String {
// Use Filestack handle
} else if let error = response?.error {
// Handle error
}
}
// Start upload (only useful when `startImmediately` option is `false`)
uploader.start()
// Cancel ongoing upload.
uploader.cancel()
// Query progress.
uploader.progress // returns a `Progress` object
Objective-C示例
// Define upload options (see `FSUploadOptions` for all the available options)
// Here we use `.defaults` which implies:
// * preferIntelligentIngestion = true
// * startImmediately = true
// * deleteTemporaryFilesAfterUpload = false
// * storeOptions = FSStorageOptions.defaults (= location:S3, access:private)
// * defaultPartUploadConcurrency = 5
// * defaultChunkUploadConcurrency = 8
// * chunkSize = 5mbs
FSUploadOptions *uploadOptions = FSUploadOptions.defaults;
// For instance, if you don't want to use Intelligent Ingestion regardless of whether it is available:
uploadOptions.preferIntelligentIngestion = NO;
// You may also easily override the default store options:
uploadOptions.storeOptions = [[FSStorageOptions alloc] initWithLocation:FSStorageLocationS3 access:FSStorageAccessPrivate];
// AWS Region for S3 (e.g. "us-east-1", "eu-west-1", "ap-northeast-1", etc.)
uploadOptions.storeOptions.region = @"us-east-1";
// The name of your S3 bucket
uploadOptions.storeOptions.container = @"YOUR-S3-BUCKET";
// Destination path in the store.
// You may use a path to a folder (e.g. /public/) or,
// alternatively a path containing a filename (e.g. /public/oncorhynchus.jpg).
// When using a path to a folder, the uploaded file will be stored at that folder using a
// filename derived from the original filename.
// When using a path to a filename, the uploaded file will be stored at the given path
// using the filename indicated in the path.
uploadOptions.storeOptions.path = @"/public/oncorhynchus.jpg";
// Custom MIME type (useful when uploadable has no way of knowing its MIME type)
uploadOptions.storeOptions.mimeType = @"image/jpg";
// An array of workflow IDs to trigger for each upload
uploadOptions.storeOptions.workflows = @[@"WF-1", @"WF-2"];
// Some local URL to be uploaded
NSURL *someURL = ...;
FSUploader *uploader = [client uploadURLUsing:someURL
options:uploadOptions
queue:dispatch_get_main_queue()
uploadProgress:^(NSProgress * _Nonnull progress) {
// Here you may update the UI to reflect the upload progress.
NSLog(@"Progress: %@", progress);
}
completionHandler:^(FSNetworkJSONResponse * _Nullable response) {
NSDictionary *jsonResponse = response.json;
NSString *handle = jsonResponse[@"handle"];
NSError *error = response.error;
if (handle) {
// Use Filestack handle
NSLog(@"Handle is: %@", handle);
} else if (error) {
// Handle error
NSLog(@"Error is: %@", error);
}
}
];
// Other alternative uploading methods are available in `FSClient`:
// - For multiple URL uploading: `uploadMultipleURLs:options:queue:uploadProgress:completionHandler:)`
// - For data uploading: `uploadDataUsing:options:queue:uploadProgress:completionHandler:)`
// - For multiple data uploading: `uploadMultipleDataUsing:options:queue:uploadProgress:completionHandler:)`
// Start upload (only useful when `startImmediately` option is `false`)
[uploader start];
// Cancel ongoing upload.
[uploader cancel];
// Query progress.
uploader.progress // returns an `NSProgress` object
启用后台上传支持
在版本2.3
中,我们为在后台会话中上传文件添加了支持。要激活此功能,请按照以下操作进行
// Set `UploadService.shared.useBackgroundSession` to true to allow uploads in the background.
FilestackSDK.UploadService.shared.useBackgroundSession = true
版本管理
Filestack Swift SDK遵循语义版本控制。
问题
如果您遇到问题,请创建一个 Github 问题。
贡献
请详细查看 CONTRIBUTING.md。
致谢
感谢所有 贡献者。