pixlee-ios-sdk-carthage
这个 SDK 让 Pixlee 客户轻松将 Pixlee 相册集成到他们的原生 iOS 应用中。它包括对 Pixlee 相册 API 的原生封装以及一些可快速开始使用的内置和可定制 UI 元素。
入门
此存储库包含 Pixlee iOS SDK 和一个示例项目,以展示其使用方法。
SDK
在访问 Pixlee API 之前,您必须初始化 PXLClient
。要设置 API 密钥,请调用 [PXLClient sharedClient]
上的 setApiKey:
。然后,您可以使用该单例实例对 Pixlee API 进行调用。
要加载相册中的照片,有两个方法:https://developers.pixlee.com/reference#get-approved-content-from-album 或 https://developers.pixlee.com/reference#get-approved-content-for-product。
如果您正在检索单个相册的内容,则会使用到 PXLAlbum
类。通过调用 [PXLAlbum albumWithIdentifier:<ALBUM ID HERE>]
创建一个实例。您可以在调用 loadNextPageOfPhotos:
加载照片之前设置 sortOptions
和 filterOptions
(更多详情请参考头文件)。相册将按页加载其照片,连续调用 loadNextPageOfPhotos:
将按顺序加载每一页。
使用CocoaPods包含Pixlee SDK
- 在你的项目中安装和设置CocoaPods https://guides.cocoapods.org.cn/using/getting-started.html
- 通过添加以下内容将 https://cocoapods.org.cn/pods/pixlee_api 添加到你的Podfile中
target 'MyApp' do
pod 'pixlee_api', '~> 1.74.32' (Replace with current version, you can find the current version at https://github.com/pixlee/ios-sdk-carthage/releases)
end
- 运行 Pod install
如果你使用的是 Swift,请参考 Swift 部分,或联系我们 [email protected]
使用Carthage包含Pixlee SDK
如果你正在构建iOS、tvOS或watchOS
- 创建一个Cartfile,在其中列出你想要在项目中使用的框架。
- 运行
carthage update
。这将把依赖项放入Carthage/Checkouts目录,然后构建每个依赖项或下载已编译的框架。 - 在你的应用程序目标的“通用”设置选项卡中,在“链接框架和库”部分,从磁盘上的Carthage/Build目录拖放你想要使用的每个框架。
- 在应用程序目标的“构建阶段”设置选项卡中,点击“+”图标并选择“新运行脚本阶段”。创建一个运行脚本,其中指定你的shell(例如:
/bin/sh
),在shell下面添加以下内容到脚本区域
/usr/local/bin/carthage copy-frameworks
并在“输入文件”下添加你想要使用的框架的路径,例如
$(SRCROOT)/Carthage/Build/iOS/Box.framework
$(SRCROOT)/Carthage/Build/iOS/Result.framework
$(SRCROOT)/Carthage/Build/iOS/ReactiveCocoa.framework
此脚本可以通过通用二进制触发的一个App Store提交错误,并确保在存档时复制必要的位代码相关文件和dSYMs。
在构建产品目录中复制调试信息后,Xcode将能够在任何时候你停在断点时解析堆栈跟踪。这还将允许你在调试器中步进第三方代码。
当你将应用程序存档以提交到App Store或TestFlight时,Xcode也将这些文件复制到应用程序包的.xcarchive
的dSYMs子目录。
过滤和排序
有关可用的过滤器排序信息请见此处:[开发者文档](https://developers.pixlee.com/reference#consuming-content)
截至当前,以下过滤器受SDK支持
min_instagram_followers
min_twitter_followers
denied_photos
starred_photos
flagged_photos (Note: false is equivalent to null here.)
deleted_photos
has_permission (Note: false is equivalent to null here.)
has_product
in_stock_only (Note: false is equivalent to null here.)
content_source
content_type
filter_by_subcaption
has_action_link
submitted_date_start
submitted_date_end
in_categories
computer_vision
filter_by_location
filter_by_radius
以下是SDK支持的排序
recency - The date the content was collected.
random - Randomized.
pixlee_shares - Number of times the content was shared from a Pixlee widget.
pixlee_likes - Number of likes the content received from a Pixlee widget.
popularity - Popularity of the content on its native platform.
dynamic - Our "secret sauce" -- a special sort that highlights high performance content and updates according to the continued performance of live content.
示例
//=========================================================
//These parameters are examples. Please adjust, add or remove them during implementation.
//=========================================================
//Create an Instance of Album with the sku Identifier
PXLAlbum *album = [PXLAlbum albumWithIdentifier:PXLSkuAlbumIdentifier];
// Create and set filter options on the album.
PXLAlbumFilterOptions *filterOptions = [PXLAlbumFilterOptions new];
NSString *dateStr = @"20190101";
// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyyMMdd"];
NSDate *date = [dateFormat dateFromString:dateStr];
filterOptions.submittedDateStart = date;
//These parameters are examples. Please adjust, add or remove them during implementation.
album.filterOptions = filterOptions;
// Create and set sort options on the album.
PXLAlbumSortOptions *sortOptions = [PXLAlbumSortOptions new];
sortOptions.sortType = PXLAlbumSortTypeRandom;
album.sortOptions = sortOptions;
album.perPage = 100;
[album loadNextPageOfPhotos:^(NSArray *photos, NSError *error) {
NSLog(@"%@",error);
if (photos.count) {
NSMutableArray *indexPaths = @[].mutableCopy;
NSInteger firstIndex = [album.photos indexOfObject:[photos firstObject]];
NSLog(@"%@", [album.photos objectAtIndex:0]);
}
}];
如果您需要检索skuid的内容,请使用`PXLAlbum`类。通过调用[PXLAlbum albumWithSkuIdentifier:
创建实例。您可以为必要的设置`sortOptions`和`filterOptions`(请参阅头文件以获取更多详细信息),然后调用`loadNextPageOfPhotosFromSku:`加载照片。专辑将按页面顺序加载其照片,连续调用`loadNextPageOfPhotosFromSku:`会按顺序加载每个页面。
示例
//=========================================================
//These parameters are examples. Please adjust, add or remove them during implementation.
//=========================================================
//Create an Instance of Album with the sku Identifier
PXLAlbum *album = [PXLAlbum albumWithSkuIdentifier:PXLSkuAlbumIdentifier];
// Create and set filter options on the album.
PXLAlbumFilterOptions *filterOptions = [PXLAlbumFilterOptions new];
NSString *dateStr = @"20190101";
// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyyMMdd"];
NSDate *date = [dateFormat dateFromString:dateStr];
filterOptions.submittedDateStart = date;
//These parameters are examples. Please adjust, add or remove them during implementation.
album.filterOptions = filterOptions;
// Create and set sort options on the album.
PXLAlbumSortOptions *sortOptions = [PXLAlbumSortOptions new];
sortOptions.sortType = PXLAlbumSortTypeRandom;
album.sortOptions = sortOptions;
album.perPage = 100;
[album loadNextPageOfPhotosFromSku:^(NSArray *photos, NSError *error) {
NSLog(@"%@",error);
if (photos.count) {
NSMutableArray *indexPaths = @[].mutableCopy;
NSInteger firstIndex = [album.photos indexOfObject:[photos firstObject]];
NSLog(@"%@", [album.photos objectAtIndex:0]);
}
}];
注意
此外,您可以使用`PXLAlbumFilterOptions`和`PXLAlbumSortOptions`来控制专辑加载数据的方式。要使用这些,请通过调用`[PXLAlbumFilterOptions new]`或`[PXLAlbumSortOptions new]`创建一个新实例,设置必要的属性,然后将这些对象设置到专辑的`filterOptions`和`sortOptions`属性上。确保在调用`loadNextPageOfPhotos:`之前设置这些选项。
一旦专辑从服务器加载了照片,它将实例化PXLPhoto
对象,这些对象可以由您的UI消耗。`PXLPhoto`公开了通过Pixlee API提供的所有照片数据,并提供了根据您的需求所需的几个图像大小URL。
为了帮助您快速入门,我们还构建了一个专辑视图控制器和照片详细视图控制器,您可以在您的应用中使用和自定义这些控制器。`PXLAlbumViewController`使用`UICollectionView`显示专辑中的照片,并包括一个切换到网格视图/列表视图的切换器。使用`albumViewControllerWithAlbumId:`创建实例或如果需要其他方式创建实例,请设置`album`属性。一旦设置了专辑,您可以调用`loadNextPageOfPhotos`开始加载过程。专辑视图控制器被设置为在用户滚动时自动加载更多照片页面,从而实现无限滚动效果。
如果用户在`PXLAlbumViewController`中点击照片,我们展示一个带PXLPhotoDetailViewController
的详细视图。您可以通过实例化PXLPhotoDetailViewController
的一个实例并设置其photo
属性来自定义详细视图。照片详细视图被配置为显示
- 大图
- 发布者的用户名
- 显示照片发布时间的戳
- 照片的平台来源(例如Instagram)
- 照片的标题(如果有的话)
- 与该照片相关联的产品(以产品水平列表形式显示)
分析
该 SDK 支持以下事件
Add to Cart : Call this whenever and wherever an add to cart event happens
User Completes Checkout: Call this whenever a user completes a checkout and makes a purchase
User Visits a Page with a Pixlee Widget: Call this whenever a user visits a page which as a Pixlee Widget on it
User Clicks on the Pixlee Widget : Call this whenever a user clicks on an item in the Pixlee widget
PXLAlbums → Load More: Call this whenever a user clicks 'Load More' button on the widget
PXLPhoto → Action Link Clicked: Call this whenever a user make an action after clicking on an item in the Pixlee widget
示例:添加到购物车
//Setup some constants
static NSString * const currency = @"USD";
//Product 1 example
static NSString * const product_sku = @"SL-BENJ";
static NSString * const price = @"13.00";
NSNumber * const quantity = @2;
//EVENT add:cart refer to pixlee_sdk/PXLAbum.h or The Readme or https://developers.pixlee.com/docs/analytics-events-tracking-pixel-guide
[PXLAnalytics triggerEventAddCart:product_sku :quantity :price :currency callback:^(NSError *error) {
NSLog(@"logged");
}];
用户完成结账
//Setup some constants
static NSString * const currency = @"USD";
//Product 1 example
static NSString * const product_sku = @"SL-BENJ";
static NSString * const price = @"13.00";
NSNumber * const quantity = @2;
//product 2 example
static NSString * const product_sku2 = @"AD-1324S";
static NSString * const price2 = @"53.07";
NSNumber * const quantity2 = @5;
NSMutableDictionary *cart1 = [[NSMutableDictionary alloc]initWithCapacity:10];
[cart1 setObject:price forKey:@"price"];
[cart1 setObject:product_sku forKey:@"product_sku"];
[cart1 setObject:quantity forKey:@"quantity"];
NSMutableDictionary *cart2 = [[NSMutableDictionary alloc]initWithCapacity:10];
[cart2 setObject:price2 forKey:@"price"];
[cart2 setObject:product_sku2 forKey:@"product_sku"];
[cart2 setObject:quantity2 forKey:@"quantity"];
NSNumber * quantity_total = @7;
NSNumber * const order_id = @234232;
NSNumber * const cart_total = @18.00;
NSMutableArray *cart_contents =[NSMutableArray arrayWithObjects:cart1,cart2,nil];
//EVENT converted:photo refer to pixlee_sdk/PXLAbum.h or The Readme or https://developers.pixlee.com/docs/analytics-events-tracking-pixel-guide
[PXLAnalytics triggerEventConvertedPhoto:cart_contents :cart_total :quantity_total :order_id :currency callback:^(NSError *error) {
NSLog(@"logged");
}];
示例:用户访问带有 Pixlee 小部件的页面
注意事项
在 LoadNextPage 事件之后触发此事件很重要
PXLAlbum *album = [PXLAlbum albumWithSkuIdentifier:PXLSkuAlbumIdentifier];
// If you are using https://developers.pixlee.com/reference#get-approved-content-from-album // api/v2/album/@album_id/Photos
// If you are using api/v2/album/sku_from
// Refer to pixlee_sdk PXLAbum.h
[self.album loadNextPageOfPhotosFromSku:^(NSArray *photos, NSError *error){
//It's important to trigger these events after the LoadNextPage event
//EVENT opened:widget refer to pixlee_sdk/PXLAbum.h or The Readme or https://developers.pixlee.com/docs/analytics-events-tracking-pixel-guide
[self.album triggerEventOpenedWidget:@"horizontal" callback:^(NSError *error) {
NSLog(@"logged");
}];
}];
示例:用户点击 Pixlee 小部件
// photo being the PXLPhoto that been clicked
PXLPhoto *photo = photo
//EVENT opened:lightbox refer to pixlee_sdk/PXLAbum.h or The Readme or https://developers.pixlee.com/docs/analytics-events-tracking-pixel-guide
[photo triggerEventOpenedLightbox:^(NSError *error) {
NSLog(@"logged");
}];
示例用户单击项目后执行操作
[PXLPhoto getPhotoWithId:@"299469263" callback:^(PXLPhoto *photo, NSError *error) {
PXLProduct *p = [photo.products objectAtIndex:0];
NSString *url = [p.link.absoluteString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@",url);
[photo triggerEventActionClicked:url callback:^(NSError *error) {
NSLog(@"triggered");
}];
}];
示例用户点击加载更多
[self.album loadNextPageOfPhotosFromSku:^(NSArray *photos, NSError *error){
NSLog(@"%@",error);
if (photos.count) {
NSMutableArray *indexPaths = @[].mutableCopy;
NSInteger firstIndex = [self.album.photos indexOfObject:[photos firstObject]];
NSLog(@"%@", [self.album.photos objectAtIndex:0]);
[photos enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSInteger itemNum = firstIndex + idx;
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:itemNum inSection:0];
[indexPaths addObject:indexPath];
}];
[self.albumCollectionView insertItemsAtIndexPaths:indexPaths];
}
[self.album triggerEventLoadMoreClicked:^(NSError *error) {
NSLog(@"logged");
}];
}];
上传图片到相册
要上传图片到相册,请使用PXLALbum类中可用的uploadImage类函数。不要忘记设置您的PXLCLIENTSECRETKEY。
///---------------------
/// @name Initialization
///---------------------
/**
Creates and returns an album with the specified sku identifier.
@param photo_uri image url.albumId is the Pixlee id to upload the image. email the user email. Username of the user uploading the email. approved photo state. connected_user_id optional. callback function.
@return A new `PXLAlbum` object.
*/
+ (NSURLSessionDataTask *)uploadImage:(NSNumber *)albumId :(NSString *)title :(NSString *)email :(NSString *)username :(NSString *)photo_uri :(BOOL *)approved :(NSString *)connected_user_id callback:(void (^)(NSError *))completionBlock;
Swift
如果您尝试在Swift项目中使用Objective-C Pixlee API,请按照以下步骤操作。您还可以查看位于 ~example_swift/ 的示例项目。
- 创建一个Cartfile,在其中列出你想要在项目中使用的框架。
- 运行
carthage update
。这将把依赖项放入Carthage/Checkouts目录,然后构建每个依赖项或下载已编译的框架。 - 在你的应用程序目标的“通用”设置选项卡中,在“链接框架和库”部分,从磁盘上的Carthage/Build目录拖放你想要使用的每个框架。
- 在应用程序目标的“构建阶段”设置选项卡中,点击“+”图标并选择“新运行脚本阶段”。创建一个运行脚本,其中指定你的shell(例如:
/bin/sh
),在shell下面添加以下内容到脚本区域 - 向当前项目添加一个bridging_header.h,按照以下步骤创建一个 https://developer.apple.com/documentation/swift/imported_c_and_objective-c_apis/importing_objective-c_into_swift
- 按照如下方式导入Pixlee SDK的头文件
//
// Use this file to import your target's public headers that you would like to expose to Swift.
//
#import <pixlee_sdk/PXLPhoto.h>
#import <pixlee_sdk/PXLAlbumFilterOptions.h>
#import <pixlee_sdk/PXLAlbumSortOptions.h>
#import <pixlee_sdk/PXLClient.h>
#import <pixlee_sdk/PXLAlbum.h>
- 现在这些文件可以在所有Swift代码中访问,并且可以像之前一样使用。
Swift示例
要从sku数字加载相册,您可以运行以下Swift代码,请检查example_swift项目目录
let album: PXLAlbum = PXLAlbum(skuIdentifier: PXLSkuAlbumIdentifier)
let filterOptions:PXLAlbumFilterOptions = PXLAlbumFilterOptions()
album.filterOptions = filterOptions
// Create and set sort options on the album.
let sortOptions = PXLAlbumSortOptions()
sortOptions.sortType = PXLAlbumSortType.random
sortOptions.ascending = true
album.sortOptions = sortOptions
album.perPage = 1
album.loadNextPageOfPhotos(fromSku: { photos, error in
if let error = error {
print("\(error)")
}
print(type(of: photos))
if photos?.count != nil {
// var indexPaths: [AnyHashable] = []
// var firstIndex: Int? = nil
if let arr = photos as? Array<PXLPhoto> {
for p in arr{
print(p.cdnLargeUrl)
}
print(arr)
}
}
})
Swift 单元测试
要运行测试,请转到 swift_example 项目,并在 Xcode 中运行测试。注意:运行测试前,请勿忘记设置 secret_key 和 api_key。
Swift 类型转换
遗憾的是,在使用 Objective-C 库时类型转换并不完全起作用。您需要手动将 Pixlee API 的返回对象转换类型,例如 let arr = photos as? Array<PXLPhoto>
。
请查看代码片段以查看完整版本。
album.loadNextPageOfPhotos(fromSku: { photos, error in
if let error = error {
print("\(error)")
}
print(type(of: photos)) # Optional<Array<Any>>
if let arr = photos as? Array<PXLPhoto> {
}
})
重要
如果您使用的是 Xcode 10,新的构建系统与示例项目不兼容。一个临时的解决方案是切换到旧的构建系统,方法是在 Xcode 中转到(文件 -> 工作空间设置 -> 构建系统 -> 旧构建系统)。但使用 CLI 进行编译仍然无效。
示例
要运行示例项目,请首先从仓库中克隆项目,然后在示例目录中运行 carthage update
。然后在 PXLAppDelegate.m
中将 PXLClientAPIKey
设置为您的 API 密钥(可在 Pixlee 桌面版获取)。然后在 PXLExampleAlbumViewController.m
中将您希望显示的相册 ID 设置为 PXLAlbumIdentifier
。
要运行项目,请打开 Xcode 中的 example.xcodeproj。
运行项目后,您应能看到该相册中的照片网格。
故障排除
如果您在 macOS 上运行 carthage update
时出错,请通过执行 rm -rf ~/Library/Caches/org.carthage.CarthageKit
来清除您的 Carthage 缓存。
授权条款
pixlee-ios-sdk 采用 MIT 许可协议。