测试已测试 | ✓ |
语言语言 | Obj-CObjective C |
许可 | MIT |
发布日期最后发布 | 2016年4月 |
由 Mark Robert Masterson 维护。
Transloadit iOS SDK 与 iOS 7 和 Xcode 5 配合使用,并启用 ARC,或与任何 newer version 配合使用。
这是 transloadit.com API 的官方 iOS SDK。
它允许您在 iPhone 或 iPad 应用程序中轻松使用 Transloadit 服务。
SDK 易于配置、使用和扩展。请参见以下详细信息。
下面的示例应用是简单 iOS 应用程序的一部分。
//
// AppDelegate.m
// TransloaditArchiveTest
//
// Created by Szabó Tamás on 2014.01.31..
// Copyright (c) 2014 Synthesis-Net. All rights reserved.
//
#import "AppDelegate.h"
#import "Transloadit.h"
#import "Step.h"
#import "AssemblyBuilder.h"
#import "TransloaditResponse.h"
#import "TransloaditLogger.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
//Create Transloadit instance
NSObject<ITransloadit>* transloadit = [[Transloadit alloc] init:@"YOUR-API-KEY"];
//Create assembly builder to build up the assembly
NSObject<IAssemblyBuilder>* assembly = [[AssemblyBuilder alloc] init];
//Set template ID
[assembly setTemplateID:@"YOUR-TEMPLATE-ID"];
NSString* path=[NSString stringWithFormat:@"%@/%@",[[NSBundle bundleForClass:[self class]] resourcePath],@"TEST_IMAGE_FILE"];
NSData* img = [NSData dataWithContentsOfFile:path];
// Alternately here is how to load the data from a UIImage
// UIImage *someImage;
// ...initialize someImage with a valid UIImage
// NSData *img = UIImageJPEGRepresentation(someImage, 0.85);
NSError* error;
//Add a file to be uploaded with autogenerated key
[assembly addFileWithName:@"myphoto.jpg" file:img withError:error];
if(error!=nil)
{
TRANSLOADIT_LOG_ERROR(self.class,error);
return YES;
}
//Invoke assembly, and wait for the result
TransloaditResponse* response =[transloadit invokeAssembly:assembly withError:error];
if(error!=nil)
{
TRANSLOADIT_LOG_ERROR_WITH_MESSAGE(self.class,@"Error has occured while completing assembly");
return YES;
}
if([response isSuccess])
{
NSDictionary *data = [response getData];
// if you have a filter robot called files like this: https://transloadit.com/demos/file-filter/decline-video-bigger-than-20mb-or-longer-than-5min
// then you can get a url to the original file like this (Note that results.files is an array)
// NSString *originalFileURL = data[@"results"][@"files"][0][@"url"];
// if you have a robot named thumbnanils like this: https://transloadit.com/demos/misc/multiple-encoding-steps-for-the-same-file
// then you can get the first thumbnail like this
// NSString *thumbnailUrl = data[@"results"][@"thumbnails"][0][@"url"];
TRANSLOADIT_LOG_INFO(self.class,@"Assembly %@ result",[data objectForKey:@"assembly_id"]);
}else
{
TRANSLOADIT_LOG_ERROR_WITH_MESSAGE(self.class,@"Error has occured while completing assembly");
}
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
- (void)applicationWillTerminate:(UIApplication *)application
{
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
@end
//
// AppDelegate.m
// TransloaditArchiveTest
//
// Created by Szabó Tamás on 2014.01.31..
// Copyright (c) 2014 Synthesis-Net. All rights reserved.
//
#import "AppDelegate.h"
#import "Transloadit.h"
#import "Step.h"
#import "AssemblyBuilder.h"
#import "TransloaditResponse.h"
#import "TransloaditLogger.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
//Create Transloadit instance
NSObject<ITransloadit>* transloadit = [[Transloadit alloc] init:@"YOUR-API-KEY"];
//Create assembly builder to build up the assembly
NSObject<IAssemblyBuilder>* assembly = [[AssemblyBuilder alloc] init];
//Set template ID
[assembly setTemplateID:@"YOUR-TEMPLATE-ID"];
NSString* path=[NSString stringWithFormat:@"%@/%@",[[NSBundle bundleForClass:[self class]] resourcePath],@"TEST_IMAGE_FILE"];
NSData* img = [NSData dataWithContentsOfFile:path];
// Alternately here is how to load the data from a UIImage
// UIImage *someImage;
// ...initialize someImage with a valid UIImage
// NSData *img = UIImageJPEGRepresentation(someImage, 0.85);
NSError* error;
//Add a file to be uploaded with autogenerated key
[assembly addFileWithName:@"myphoto.jpg" file:img withError:error];
IF(error!=nil)
{
TRANSLOADIT_LOG_ERROR(self.class,error);
return YES;
}
//Add a file to be uploaded with custom key
[assembly addFileWithName:@"custom_file" file:img withError:error];
if(error!=nil)
{
TRANSLOADIT_LOG_ERROR(self.class,error);
return YES;
}
//Define the step, you can define more in the same assembly
NSObject<IStep>* step=[[Step alloc] init];
[step setOptionKey:@"robot" object:@"/image/resize"];
[step setOptionKey:@"width" object:@(75)];
[step setOptionKey:@"height" object:@(75)];
[step setOptionKey:@"resize_strategy" object:@"pad"];
[step setOptionKey:@"background" object:@"#000000"];
//Add the step to the assembly
[assembly addStepName:@"thumb" step:step];
//Set notification URL
[assembly setNotifyURL:@"http://your-service.net/ready"];
//Set the expiration date time of the request for the assembly
//Assembly will be expired in 120 minutes from now
NSDate* time=[[NSDate alloc] init];
[assembly setAuthExpires:[time dateByAddingTimeInterval:120*60]];
//Invoke assembly, and wait for the result
TransloaditResponse* response =[transloadit invokeAssembly:assembly withError:error];
if(error!=nil)
{
TRANSLOADIT_LOG_ERROR_WITH_MESSAGE(self.class,@"Error has occured while completing assembly");
return YES;
}
if([response isSuccess])
{
NSDictionary *data = [response getData];
// if you have a filter robot called "files" like this: https://transloadit.com/demos/file-filter/decline-video-bigger-than-20mb-or-longer-than-5min
// then you can get a url to the original file like this (Note that results.files is an array)
// NSString *originalFileURL = data[@"results"][@"files"][0][@"url"];
// if you have a robot named "thumbnanils" like this: https://transloadit.com/demos/misc/multiple-encoding-steps-for-the-same-file
// the you can get the first thumbnail like this
// NSString *thumbnailUrl = data[@"results"][@"thumbnails"][0][@"url"];
TRANSLOADIT_LOG_INFO(self.class,@"Assembly %@ result",[data objectForKey:@"assembly_id"]);
}else
{
TRANSLOADIT_LOG_ERROR_WITH_MESSAGE(self.class,@"Error has occured while completing assembly");
}
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
- (void)applicationWillTerminate:(UIApplication *)application
{
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
@end
您需要下载必要的静态库和头文件并将其集成到您的应用中。您还可以将源代码拉取出来,并与您的应用一起编译。
Transloadit iOS SDK 未使用任何外部库。SDK 仅与启用 Automatic Reference Counting 的情况下一起使用。
如果您想在应用程序中使用 Transloadit iOS SDK,您需要将其作为静态库添加,或者可以直接使用源代码(更简单)。
要直接使用SDK源,请将TransloaditLib目录复制到您的XCode项目中。
Transloadit服务与assembly一起工作。assembly必须包含用于身份验证和处理的全部信息。每个assembly必须包含身份验证信息和步骤或模板ID。您可以设置自定义的值,例如自定义字段和文件。
注意:模板ID是您在Transloadit账户中创建的Transloadit模板的ID。
使用该类,您可以创建一个Transloadit实例,该实例将处理您的应用发送的所有assembly。
NSObject<ITransloadit>* transloadit = [[Transloadit alloc] init:@"YOUR-API-KEY"];
注意:您可以将Transloadit实例用作单例实例。
要构建assembly,您需要使用AssemblyBuilder
。
NSObject<IAssemblyBuilder>* builder = [[AssemblyBuilder alloc] init];
如前所述,要定义assembly的步骤,您可以使用Step
类。每个步骤必须具有选项,可以使用-(void)setOptionKey:(NSString*)key object:(NSObject*)value;
方法设置这些选项。该步骤将在您上传或预定义的资源上执行。
// Step below will resize the uploaded image to 75x75 size
// with the pad resize strategy and with a black background color
NSObject<IStep>* step=[[Step alloc] init];
[step setOptionKey:@"robot" object:@"/image/resize"];
[step setOptionKey:@"width" object:@(75)];
[step setOptionKey:@"height" object:@(75)];
[step setOptionKey:@"resize_strategy" object:@"pad"];
[step setOptionKey:@"background" object:@"#000000"];
要将该步骤添加到您的assembly中,您需要调用-(void)addStepName:(NSString*)name step:(NSObject<IStep>*)step;
方法,其中name
参数是步骤的键。您可以在同一assembly的后续步骤中引用它,即使您添加了更多步骤。
[builder addStepName:@"resize" step:step];
作为预创建模板的参数,可以为每个assembly设置自定义字段。可以使用-(void)setFieldKey:(NSString*)key value:(NSString*)value withError:(NSError*)error;
方法设置自定义字段,其中key
参数是字段的唯一键,而value
参数是字段的值。
如果自定义字段集合中没有定义有效的键,则将创建该键,并设置相关值。如果已定义了有效的键,则将使用传入的值覆盖它。
某些字段键由SDK使用。您不能将这些键用作自定义字段键,例如“notify_url”、“params”、“signature”、“template_id”。如果您尝试使用这些键之一,则将抛出NSError
。
如果您尝试使用已定义为文件键的自定义字段键(在下一节中介绍文件),则会抛出NSError
。
[builder setFieldKey:@"field_key" value:@"field_value" withError:error]
您可以在创建的builder
对象上调用-(void)addFile:(NSData*) file withError:(NSError*)error;
或-(void)addFileWithName:(NSString*)key file:(NSData*)file withError:(NSError*) error;
方法,其中key
参数是文件的唯一键,而file
参数是文件的NSData。
如果您仅使用file
参数调用该方法,则文件的键将是一个自动生成的键。如果您同时使用这两个参数调用该方法,则将使用指定的键添加文件。如果键已定义为自定义字段键或文件键,则将为文件设置一个自动生成的键。
[builder addFile:img withError:error];
或[assembly addFileWithName:@"custom_file" file:img withError:error];
您可以根据以下示例设置认证信息。
Transloadit 构造函数设置 API 密钥。
可以在 builder
对象上调用以下方法
-(void)setAuthExpires:(NSDate*)dateTime;
- 设置请求到期日期(默认 120 分钟)-(void)setAuthMaxSize:(int)maxSize;
- 设置请求的最大大小(以字节为单位);请参考 Transloadit 文档:[https://transloadit.com/docs/api-docs#authentication-implementations](https://transloadit.com/docs/api-docs#authentication-implementations)NSDate* time=[[NSDate alloc] init];
[builder setAuthExpires:[time dateByAddingTimeInterval:120*60]];//Request will be expired after the current date time + 120 minutes
[builder setAuthMaxSize:1024];
注意:这些方法是可选的
您可以通过在 builder
对象上调用 -(void)setNotifyURL:(NSString*)notifyURL;
为您的组件定义通知 URL,该 URL 将在 Transloadit 服务器上完成组件后进行请求。
[builder setNotifyURL:@"http://your-service.net/ready"];
如果您的组件已完成,则将向指定的通知 URL 发送 POST 请求。此请求将包含有关创建的组件状态的信息,并将包含有关结果文件的所有信息。如果 Transloadit 已将 assembly_url
作为 GET 参数发送,则该 URL 将由 TransloaditRequest 调用。
例如:您有一个移动应用程序,该应用程序通过 iOS SDK 调用组件,您有一个用 PHP 编写的 REST API 服务,该服务可以处理组件完成后发送的请求。您需要做的是将 PHP Transloadit SDK 集成到您的 PHP REST API 服务中,并调用
Transloadit::response()
方法,然后您就可以使用组件的结果(例如创建数据库记录)了。
您可以使用 -(void)setTemplateID:(NSString*)templateID;
来定义将用于在 Transloadit 服务器上处理您的组件的模板 ID,其中 templateID
参数是预创建模板的 ID。
[builder setTemplateID:@"ID-OF-PRECEREATED-TEMPLATE"];
一旦构建了组件,您就可以使用 -(TransloaditResponse*)invokeAssembly:(NSObject<IAssemblyBuilder>*)assembly withError:(NSError*)error;
方法将它们发送到 Transloadit 服务器,其中 builder
参数是可在 transloadit
对象上调用的构建的 AssemblyBuilder
类的实例。组装的结果将表示在一个 ITransloaditResponse
实例中。
TransloaditResponse* response =[transloadit invokeAssembly:builder withError:error];
一旦请求完成并创建了 response
对象,您就可以检查其属性
[response getData]
- 返回作为字典 (NSDictionary
) 的响应[response getResponseString]
- 返回响应字符串[response isSuccess]
- 返回请求的成功注意:
[response getData]
主字典可以存储子字典作为主字典的值
Transloadit iOS SDK 允许您在服务器上删除一个组件。您可以在创建的 transloadit
对象上调用 -(TransloaditResponse*)deleteAssembly:(NSString*)assemblyID;
方法,其中 assemblyID
参数是现有组件的 ID。在您要取消组件时,此调用很有用。
´TransloaditResponse* response =[transloadit deleteAssembly:@"YOUR-CREATED-ASSEMBLY-ID"]);´
您可以像调用组装一样处理此响应。
SDK为您提供记录信息和错误的可能性。您可以使用默认的TransloaditLogger
与logger宏一起使用。
TRANSLOADIT_LOG_INFO(type,message,...)
- 记录信息,其中type
是发送对象的类型,message
是带参数的自定义日志消息,parameters
是自定义日志消息的参数TRANSLOADIT_LOG_ERROR_WITH_ERROR_AND_MESSAGE(type,error,message,...)
- 记录错误(建议在抛出异常时使用),其中type
是发送对象的类型,exception
是抛出的异常,message
是带参数的自定义日志消息,parameters
是自定义日志消息的参数*注意: *
TRANSLOADIT_LOG_ERROR_
宏有更多的参数定义
SDK可以被扩展。您可以使用接口创建自己的实现,并可以扩展预先创建的类。
要运行所有单元测试,您需要XCTest。从Xcode 5运行测试。
要运行测试,您需要填写Constants.h文件。