Swiftpack.co - Package - filestack/filestack-swift

Code Climate Build Status

Filestack Swift SDK

This is the official Swift SDK for Filestack - API and content management system that makes it easy to add powerful file uploading and transformation capabilities to any web or mobile application.

Resources

Requirements

  • Xcode 10.2+ (Xcode 12+ required for SPM support)
  • Swift 4.2+ / Objective-C
  • iOS 11.0+

Installing

CocoaPods

CocoaPods is a dependency manager for Cocoa projects. You can install it with the following command:

$ gem install cocoapods

To integrate FilestackSDK into your Xcode project using CocoaPods, specify it in your Podfile:

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '11.0'
use_frameworks!

target '<Your Target Name>' do
    pod 'FilestackSDK', '~> 2.5.1'
end

Then, run the following command:

$ pod install

Carthage

Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.

You can install Carthage with Homebrew using the following command:

$ brew update
$ brew install carthage

To integrate FilestackSDK into your Xcode project using Carthage, specify it in your Cartfile:

github "filestack/filestack-swift" ~> 2.5.1

Run carthage update to build the framework and drag the built FilestackSDK.framework into your Xcode project. Additionally, add Alamofire.framework to the embedded frameworks build phase of your app's target.

Swift Package Manager

Add https://github.com/filestack/filestack-swift.git as a Swift Package Manager dependency to your Xcode project.

Alternatively, if you are adding FilestackSDK to your own Swift Package, declare the dependency in your Package.swift:

dependencies: [
    .package(url: "https://github.com/filestack/filestack-swift.git", .upToNextMajor(from: "2.5.1"))
]

Manually

Embedded Framework

Open up Terminal, cd into your top-level project directory, and run the following command "if" your project is not initialized as a git repository:

$ git init

Add FilestackSDK and its dependencies as git submodules by running the following commands:

$ git submodule add https://github.com/filestack/filestack-swift.git
$ git submodule add https://github.com/Alamofire/Alamofire.git

Open the new filestack-swift folder, and drag the FilestackSDK.xcodeproj into the Project Navigator of your application's Xcode project.

It should appear nested underneath your application's blue project icon. Whether it is above or below all the other Xcode groups does not matter. Select the FilestackSDK.xcodeproj in the Project Navigator and verify the deployment target matches that of your application target.

Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the "Targets" heading in the sidebar.

In the tab bar at the top of that window, open the "General" panel.

Click on the + button under the "Embedded Binaries" section and choose the FilestackSDK.framework for iOS.

Repeat the same process for adding Alamofire.

Usage

Integration into a Swift project
  1. Import the framework into your code:

    import FilestackSDK
    
  2. Instantiate a Client object by providing your API key and, optionally, a Security object:

    // 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)
    
Integration into an Objective-C project
  1. Import the framework into your code:

    @import FilestackSDK;
    
  2. Instantiate a FSClient object by providing your API key and, optionally, a FSSecurity object:

    // 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];
    

For more information, please consult our API Reference.

Uploading files directly to a storage location

Both regular and Intelligent Ingestion uploads use the same API function available in the Client class. However, if your account has Intelligent Ingestion support enabled and you prefer using the regular uploading mechanism, you could disable it by setting the useIntelligentIngestionIfAvailable argument to false (see the relevant examples below.)

Swift Example
// 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 Example
// 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
Enabling background upload support

New in version 2.3, we added support for uploading files in a background session. In order to activate this feature, please do the following:

// Set `UploadService.shared.useBackgroundSession` to true to allow uploads in the background.
FilestackSDK.UploadService.shared.useBackgroundSession = true

Versioning

Filestack Swift SDK follows the Semantic Versioning.

Issues

If you have problems, please create a Github Issue.

Contributing

Please see CONTRIBUTING.md for details.

Credits

Thank you to all the contributors.

Github

link
Stars: 10

Used By

Total: 0

Releases

Version 2.5.1 - 2020-10-19 14:09:37

  • Ensuring automatic deletion of uploaded files logic is triggered in case the upload process is cancelled before starting.

Version 2.5.0 - 2020-10-16 11:18:57

  • Added optional setting to allow automatic deletion of uploaded files if they are located in the user's temporary directory.

Version 2.4.1 - 2020-10-02 13:51:29

  • Improved memory usage when using the regular upload mechanism.

Version 2.4.0 - 2020-09-30 18:33:58

  • Added support for Upload Tags.
  • Added support for Swift Package Manager.

Version 2.3.2 - 2020-07-30 18:06:37

  • Fixed transforms using the wrong base URL resulting in 404 responses.

Version 2.3.1 - 2020-07-09 13:52:42

  • Cancelling an upload is now also reflected on its associated progress object.
  • Fixed a possible race condition when cancelling an upload operation right after it started.

Version 2.3 - 2020-07-08 12:35:21

  • Added support for background uploads (see "Enabling background upload support" in README.md for more information.)
  • Improved upload progress reporting.
  • Improved retry and cancellation logic in upload operations.
  • Significantly improved performance of MD5 and Hmac calculations by relying on CommonCrypto.
  • Removed CryptoSwift dependency.

Version 2.2.2 - 2020-05-04 10:14:14

  • Added filename property to Uploadable and default implementation for URL (addresses #19.)
  • Improved reliability of MultipartUpload abort logic (addresses #18.)
  • Removed unnecessary files from Copy Bundle Resources phase (addresses #17.)
  • Updated CryptoSwift dependency to ~> 1.3 in Cartfile and podspec.

Version 2.2 - 2019-09-18 14:26:18

  • Added upload(using:options:queue:uploadProgress:completionHandler:) taking one or multiple Uploadable items as input to Client and deprecated multiPartUpload(...) and multiFileUpload(...).
  • Added equivalent new upload functionality for Objective-C that allows uploads of one or several local NSURL or NSData.
  • Client upload functions now return types based on protocols, such as Uploadable, DeferredAdd, Cancellable, Monitorizable or combinations of these.
  • Added UploadOptions class that allows customizing the upload behavior in a much more fine-grained way.
  • Added CustomStringConvertible conformance to most public classes using newly added helper Tools.describe(subject:only:except:).
  • Added static defaults function to StorageOptions defaulting to StorageOptions(location: .S3, access: .private).
  • Removed unused storage property from Client and marked init(apiKey:security:storage:) as deprecated.
  • Exposed more API to Objective-C.
  • Updated Alamofire dependency to ~> 4.9.
  • Updated CryptoSwift dependency to ~> 1.0.
  • Improved documentation.