Compare commits
54 Commits
c38a09cd8b
...
dev_lottie
| Author | SHA1 | Date | |
|---|---|---|---|
| cb3c9f184a | |||
| cb5819e330 | |||
| 5af2612ff7 | |||
| cac2f13b88 | |||
| edf88721da | |||
| 915b329805 | |||
| 1673a2f4be | |||
| e4cebeac85 | |||
| c7021e382e | |||
| ffea9d2022 | |||
| 90c1e7ff6c | |||
| 59d04bb33c | |||
| eb0d3aaa71 | |||
| 10dfe9b1d6 | |||
| 6993bfd682 | |||
| 247a87891e | |||
| 9af91cc4bc | |||
| 4f23118ec0 | |||
| 482756f6f0 | |||
| 85a3694e35 | |||
| f58bf61500 | |||
| 783d088f22 | |||
| 74476cd592 | |||
| 9b43274e93 | |||
| 8ce1d95c8c | |||
| e8c88a6148 | |||
| e218c1bf3d | |||
| c5326a3079 | |||
| 9101ffaab0 | |||
| e594711fa3 | |||
| 7fd084e529 | |||
| 11b25241bf | |||
| 8fcfce7376 | |||
| 23317c9fd4 | |||
| 045d5eaff8 | |||
| 72b6dbb157 | |||
| e78b56e2cb | |||
| 6c05026402 | |||
| 13facba33a | |||
| 935284388c | |||
| 4c7fd9049f | |||
| 0031b7a5f6 | |||
| 02dd204744 | |||
| f28f7de49d | |||
| c2859f888a | |||
| a2b51189aa | |||
| 2f2f20cfc2 | |||
| 377e88b6db | |||
| 1deca2ae5b | |||
| efb04d134e | |||
| a6c077a42d | |||
| d4ebfb9909 | |||
| a9625369f7 | |||
| 5e44ac155b |
11
CustomKeyboard/CustomKeyboard.entitlements
Normal file
11
CustomKeyboard/CustomKeyboard.entitlements
Normal file
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>keychain-access-groups</key>
|
||||
<array>
|
||||
<string>$(AppIdentifierPrefix)com.loveKey.nyx.shared</string>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
|
||||
24
CustomKeyboard/Info.plist
Normal file
24
CustomKeyboard/Info.plist
Normal file
@@ -0,0 +1,24 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>NSExtension</key>
|
||||
<dict>
|
||||
<key>NSExtensionAttributes</key>
|
||||
<dict>
|
||||
<key>IsASCIICapable</key>
|
||||
<false/>
|
||||
<key>PrefersRightToLeft</key>
|
||||
<false/>
|
||||
<key>PrimaryLanguage</key>
|
||||
<string>en-US</string>
|
||||
<key>RequestsOpenAccess</key>
|
||||
<true/>
|
||||
</dict>
|
||||
<key>NSExtensionPointIdentifier</key>
|
||||
<string>com.apple.keyboard-service</string>
|
||||
<key>NSExtensionPrincipalClass</key>
|
||||
<string>KeyboardViewController</string>
|
||||
</dict>
|
||||
</dict>
|
||||
</plist>
|
||||
12
CustomKeyboard/KeyboardViewController.h
Normal file
12
CustomKeyboard/KeyboardViewController.h
Normal file
@@ -0,0 +1,12 @@
|
||||
//
|
||||
// KeyboardViewController.h
|
||||
// CustomKeyboard
|
||||
//
|
||||
// Created by Mac on 2025/10/27.
|
||||
//
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
@interface KeyboardViewController : UIInputViewController
|
||||
|
||||
@end
|
||||
220
CustomKeyboard/KeyboardViewController.m
Normal file
220
CustomKeyboard/KeyboardViewController.m
Normal file
@@ -0,0 +1,220 @@
|
||||
//
|
||||
// KeyboardViewController.m
|
||||
// CustomKeyboard
|
||||
//
|
||||
// Created by Mac on 2025/10/27.
|
||||
//
|
||||
|
||||
#import "KeyboardViewController.h"
|
||||
#import "KBKeyBoardMainView.h"
|
||||
|
||||
#import "KBKey.h"
|
||||
#import "KBFunctionView.h"
|
||||
#import "KBSettingView.h"
|
||||
#import "Masonry.h"
|
||||
#import "KBAuthManager.h"
|
||||
#import "KBFullAccessManager.h"
|
||||
|
||||
static CGFloat KEYBOARDHEIGHT = 256 + 20;
|
||||
|
||||
@interface KeyboardViewController () <KBKeyBoardMainViewDelegate, KBFunctionViewDelegate>
|
||||
@property (nonatomic, strong) UIButton *nextKeyboardButton; // 系统“下一个键盘”按钮(可选)
|
||||
@property (nonatomic, strong) KBKeyBoardMainView *keyBoardMainView; // 功能面板视图(点击工具栏第0个时显示)
|
||||
@property (nonatomic, strong) KBFunctionView *functionView; // 功能面板视图(点击工具栏第0个时显示)
|
||||
@property (nonatomic, strong) KBSettingView *settingView; // 设置页
|
||||
@end
|
||||
|
||||
@implementation KeyboardViewController
|
||||
|
||||
{
|
||||
BOOL _kb_didTriggerLoginDeepLinkOnce;
|
||||
}
|
||||
|
||||
- (void)viewDidLoad {
|
||||
[super viewDidLoad];
|
||||
[self setupUI];
|
||||
// 指定 HUD 的承载视图(扩展里无法取到 App 的 KeyWindow)
|
||||
[KBHUD setContainerView:self.view];
|
||||
// 绑定完全访问管理器,便于统一感知和联动网络开关
|
||||
[[KBFullAccessManager shared] bindInputController:self];
|
||||
__unused id token = [[NSNotificationCenter defaultCenter] addObserverForName:KBFullAccessChangedNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(__unused NSNotification * _Nonnull note) {
|
||||
// 如需,可在此刷新与完全访问相关的 UI
|
||||
}];
|
||||
}
|
||||
|
||||
|
||||
- (void)setupUI {
|
||||
// 固定键盘整体高度
|
||||
[self.view.heightAnchor constraintEqualToConstant:KEYBOARDHEIGHT].active = YES;
|
||||
// 预置功能面板(默认隐藏),与键盘区域共享相同布局
|
||||
self.functionView.hidden = YES;
|
||||
[self.view addSubview:self.functionView];
|
||||
[self.functionView mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.left.right.equalTo(self.view);
|
||||
make.top.equalTo(self.view).offset(4);
|
||||
make.bottom.equalTo(self.view.mas_bottom).offset(-4);
|
||||
}];
|
||||
|
||||
[self.view addSubview:self.keyBoardMainView];
|
||||
[self.keyBoardMainView mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.left.right.equalTo(self.view);
|
||||
make.top.equalTo(self.view).offset(4);
|
||||
make.bottom.equalTo(self.view.mas_bottom).offset(-4);
|
||||
}];
|
||||
}
|
||||
|
||||
|
||||
|
||||
#pragma mark - Private
|
||||
|
||||
/// 切换显示功能面板/键盘主视图
|
||||
- (void)showFunctionPanel:(BOOL)show {
|
||||
// 简单显隐切换,复用相同的布局区域
|
||||
self.functionView.hidden = !show;
|
||||
self.keyBoardMainView.hidden = show;
|
||||
|
||||
// 可选:把当前显示的视图置顶,避免层级遮挡
|
||||
if (show) {
|
||||
[self.view bringSubviewToFront:self.functionView];
|
||||
} else {
|
||||
[self.view bringSubviewToFront:self.keyBoardMainView];
|
||||
}
|
||||
}
|
||||
|
||||
/// 显示/隐藏设置页(高度与 keyBoardMainView 一致),右侧滑入/滑出
|
||||
- (void)showSettingView:(BOOL)show {
|
||||
if (show) {
|
||||
// if (!self.settingView) {
|
||||
self.settingView = [[KBSettingView alloc] init];
|
||||
self.settingView.hidden = YES;
|
||||
[self.view addSubview:self.settingView];
|
||||
[self.settingView mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
// 与键盘主视图完全等同的区域,保证高度、宽度一致
|
||||
make.edges.equalTo(self.keyBoardMainView);
|
||||
}];
|
||||
[self.settingView.backButton addTarget:self action:@selector(onTapSettingsBack) forControlEvents:UIControlEventTouchUpInside];
|
||||
// }
|
||||
[self.view bringSubviewToFront:self.settingView];
|
||||
// 以 keyBoardMainView 的实际宽度为准,避免首次添加时 self.view 宽度尚未计算
|
||||
[self.view layoutIfNeeded];
|
||||
CGFloat w = CGRectGetWidth(self.keyBoardMainView.bounds);
|
||||
if (w <= 0) { w = CGRectGetWidth(self.view.bounds); }
|
||||
if (w <= 0) { w = [UIScreen mainScreen].bounds.size.width; }
|
||||
self.settingView.transform = CGAffineTransformMakeTranslation(w, 0);
|
||||
self.settingView.hidden = NO;
|
||||
[UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
|
||||
self.settingView.transform = CGAffineTransformIdentity;
|
||||
} completion:nil];
|
||||
} else {
|
||||
if (!self.settingView || self.settingView.hidden) return;
|
||||
CGFloat w = CGRectGetWidth(self.keyBoardMainView.bounds);
|
||||
if (w <= 0) { w = CGRectGetWidth(self.view.bounds); }
|
||||
if (w <= 0) { w = [UIScreen mainScreen].bounds.size.width; }
|
||||
[UIView animateWithDuration:0.22 delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
|
||||
self.settingView.transform = CGAffineTransformMakeTranslation(w, 0);
|
||||
} completion:^(BOOL finished) {
|
||||
self.settingView.hidden = YES;
|
||||
}];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// MARK: - KBKeyBoardMainViewDelegate
|
||||
- (void)keyBoardMainView:(KBKeyBoardMainView *)keyBoardMainView didTapKey:(KBKey *)key {
|
||||
switch (key.type) {
|
||||
case KBKeyTypeCharacter:
|
||||
[self.textDocumentProxy insertText:key.output ?: key.title ?: @""]; break;
|
||||
case KBKeyTypeBackspace:
|
||||
[self.textDocumentProxy deleteBackward]; break;
|
||||
case KBKeyTypeSpace:
|
||||
[self.textDocumentProxy insertText:@" "]; break;
|
||||
case KBKeyTypeReturn:
|
||||
[self.textDocumentProxy insertText:@"\n"]; break;
|
||||
case KBKeyTypeGlobe:
|
||||
[self advanceToNextInputMode]; break;
|
||||
case KBKeyTypeCustom:
|
||||
// 点击自定义键(如“AI”)切换到功能面板
|
||||
[self showFunctionPanel:YES];
|
||||
break;
|
||||
case KBKeyTypeModeChange:
|
||||
case KBKeyTypeShift:
|
||||
// 这些已在 KBKeyBoardMainView/KBKeyboardView 内部处理
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)keyBoardMainView:(KBKeyBoardMainView *)keyBoardMainView didTapToolActionAtIndex:(NSInteger)index {
|
||||
if (index == 0) {
|
||||
[self showFunctionPanel:YES];
|
||||
} else {
|
||||
[self showFunctionPanel:NO];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)keyBoardMainViewDidTapSettings:(KBKeyBoardMainView *)keyBoardMainView {
|
||||
[self showSettingView:YES];
|
||||
}
|
||||
|
||||
// MARK: - KBFunctionViewDelegate
|
||||
- (void)functionView:(KBFunctionView *)functionView didTapToolActionAtIndex:(NSInteger)index {
|
||||
// 需求:当 index == 0 时,切回键盘主视图
|
||||
if (index == 0) {
|
||||
[self showFunctionPanel:NO];
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark - lazy
|
||||
- (KBKeyBoardMainView *)keyBoardMainView{
|
||||
if (!_keyBoardMainView) {
|
||||
_keyBoardMainView = [[KBKeyBoardMainView alloc] init];
|
||||
_keyBoardMainView.delegate = self;
|
||||
}
|
||||
return _keyBoardMainView;
|
||||
}
|
||||
|
||||
- (KBFunctionView *)functionView{
|
||||
if (!_functionView) {
|
||||
_functionView = [[KBFunctionView alloc] init];
|
||||
_functionView.delegate = self; // 监听功能面板顶部Bar点击
|
||||
}
|
||||
return _functionView;
|
||||
}
|
||||
|
||||
- (KBSettingView *)settingView {
|
||||
if (!_settingView) {
|
||||
_settingView = [[KBSettingView alloc] init];
|
||||
}
|
||||
return _settingView;
|
||||
}
|
||||
|
||||
|
||||
#pragma mark - Actions
|
||||
|
||||
- (void)onTapSettingsBack {
|
||||
[self showSettingView:NO];
|
||||
}
|
||||
|
||||
|
||||
// 当键盘第一次显示时,尝试唤起主 App 以提示登录(由主 App 决定是否真的弹登录)。
|
||||
- (void)viewDidAppear:(BOOL)animated {
|
||||
[super viewDidAppear:animated];
|
||||
if (!_kb_didTriggerLoginDeepLinkOnce) {
|
||||
_kb_didTriggerLoginDeepLinkOnce = YES;
|
||||
// 仅在未登录时尝试拉起主App登录
|
||||
if (!KBAuthManager.shared.isLoggedIn) {
|
||||
[self kb_tryOpenContainerForLoginIfNeeded];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (void)kb_tryOpenContainerForLoginIfNeeded {
|
||||
NSURL *url = [NSURL URLWithString:@"kbkeyboard://login?src=keyboard"];
|
||||
if (!url) return;
|
||||
__weak typeof(self) weakSelf = self;
|
||||
[self.extensionContext openURL:url completionHandler:^(__unused BOOL success) {
|
||||
// 即使失败也不重复尝试;避免打扰。
|
||||
__unused typeof(weakSelf) selfStrong = weakSelf;
|
||||
}];
|
||||
}
|
||||
@end
|
||||
43
CustomKeyboard/Manager/KBFullAccessManager.h
Normal file
43
CustomKeyboard/Manager/KBFullAccessManager.h
Normal file
@@ -0,0 +1,43 @@
|
||||
//
|
||||
// KBFullAccessManager.h
|
||||
// 统一封装:检测并管理键盘扩展的“允许完全访问”状态
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
typedef NS_ENUM(NSInteger, KBFullAccessState) {
|
||||
KBFullAccessStateUnknown = 0, // 无法确定(降级处理为未开启)
|
||||
KBFullAccessStateDenied, // 未开启完全访问
|
||||
KBFullAccessStateGranted // 已开启完全访问
|
||||
};
|
||||
|
||||
/// 状态变更通知(仅扩展进程内广播)
|
||||
extern NSNotificationName const KBFullAccessChangedNotification;
|
||||
|
||||
/// 键盘扩展“完全访问”状态管理
|
||||
@interface KBFullAccessManager : NSObject
|
||||
|
||||
+ (instancetype)shared;
|
||||
|
||||
/// 绑定当前的 UIInputViewController(用于调用系统私有选择器 hasFullAccess;按字符串反射,避免编译期引用)
|
||||
- (void)bindInputController:(UIInputViewController *)ivc;
|
||||
|
||||
/// 当前状态(内部做缓存;如需强制刷新,调用 refresh)
|
||||
- (KBFullAccessState)currentState;
|
||||
|
||||
/// 便捷判断
|
||||
- (BOOL)hasFullAccess;
|
||||
|
||||
/// 立即刷新一次状态(若状态有变化会发送 KBFullAccessChangedNotification)
|
||||
- (void)refresh;
|
||||
|
||||
/// 若未开启,则在传入视图上展示引导弹层(使用现有的 KBFullAccessGuideView);返回是否已开启
|
||||
- (BOOL)ensureFullAccessOrGuideInView:(UIView *)parent;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
100
CustomKeyboard/Manager/KBFullAccessManager.m
Normal file
100
CustomKeyboard/Manager/KBFullAccessManager.m
Normal file
@@ -0,0 +1,100 @@
|
||||
//
|
||||
// KBFullAccessManager.m
|
||||
//
|
||||
// 统一封装“允许完全访问”检测:
|
||||
// 1) 首选:反射调用 UIInputViewController 的 hasFullAccess(避免直接引用私有 API 标识)
|
||||
// 2) 兜底:无法判断时返回 Unknown(上层可按需降级为 Denied 并提示)
|
||||
//
|
||||
|
||||
#import "KBFullAccessManager.h"
|
||||
#import <objc/message.h>
|
||||
#if __has_include("KBNetworkManager.h")
|
||||
#import "KBNetworkManager.h"
|
||||
#endif
|
||||
#if __has_include("KBKeyboardPermissionManager.h")
|
||||
#import "KBKeyboardPermissionManager.h"
|
||||
#endif
|
||||
|
||||
NSNotificationName const KBFullAccessChangedNotification = @"KBFullAccessChangedNotification";
|
||||
|
||||
@interface KBFullAccessManager ()
|
||||
@property (nonatomic, weak) UIInputViewController *ivc;
|
||||
@property (nonatomic, assign) KBFullAccessState state;
|
||||
@end
|
||||
|
||||
@implementation KBFullAccessManager
|
||||
|
||||
+ (instancetype)shared {
|
||||
static KBFullAccessManager *m; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ m = [KBFullAccessManager new]; });
|
||||
return m;
|
||||
}
|
||||
|
||||
- (instancetype)init {
|
||||
if (self = [super init]) {
|
||||
_state = KBFullAccessStateUnknown;
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)bindInputController:(UIInputViewController *)ivc {
|
||||
self.ivc = ivc;
|
||||
[self refresh];
|
||||
}
|
||||
|
||||
- (KBFullAccessState)currentState { return _state; }
|
||||
|
||||
- (BOOL)hasFullAccess { return self.state == KBFullAccessStateGranted; }
|
||||
|
||||
- (void)refresh {
|
||||
KBFullAccessState newState = [self p_detectFullAccessState];
|
||||
if (newState != self.state) {
|
||||
self.state = newState;
|
||||
[[NSNotificationCenter defaultCenter] postNotificationName:KBFullAccessChangedNotification object:nil];
|
||||
[self p_applySideEffects];
|
||||
}
|
||||
}
|
||||
|
||||
- (BOOL)ensureFullAccessOrGuideInView:(UIView *)parent {
|
||||
[self refresh];
|
||||
if (self.state == KBFullAccessStateGranted) return YES;
|
||||
#if __has_include("KBFullAccessGuideView.h")
|
||||
// 动态引入,避免主 App 编译引用
|
||||
Class guideCls = NSClassFromString(@"KBFullAccessGuideView");
|
||||
if (guideCls && [guideCls respondsToSelector:NSSelectorFromString(@"showInView:")]) {
|
||||
SEL sel = NSSelectorFromString(@"showInView:");
|
||||
((void (*)(id, SEL, UIView *))objc_msgSend)(guideCls, sel, parent);
|
||||
}
|
||||
#endif
|
||||
return NO;
|
||||
}
|
||||
|
||||
#pragma mark - Detect
|
||||
|
||||
// 通过反射调用 hasFullAccess(若系统提供),否则返回 Unknown
|
||||
- (KBFullAccessState)p_detectFullAccessState {
|
||||
UIInputViewController *ivc = self.ivc;
|
||||
if (!ivc) return KBFullAccessStateUnknown;
|
||||
|
||||
SEL sel = NSSelectorFromString(@"hasFullAccess");
|
||||
if ([ivc respondsToSelector:sel]) {
|
||||
BOOL granted = ((BOOL (*)(id, SEL))objc_msgSend)(ivc, sel);
|
||||
return granted ? KBFullAccessStateGranted : KBFullAccessStateDenied;
|
||||
}
|
||||
// 无法判断时标记 Unknown(上层可按需处理为未开启)
|
||||
return KBFullAccessStateUnknown;
|
||||
}
|
||||
|
||||
#pragma mark - Side Effects
|
||||
|
||||
- (void)p_applySideEffects {
|
||||
#if __has_include("KBNetworkManager.h")
|
||||
// 根据完全访问状态切换网络总开关
|
||||
[KBNetworkManager shared].enabled = (self.state == KBFullAccessStateGranted);
|
||||
#endif
|
||||
#if __has_include("KBKeyboardPermissionManager.h")
|
||||
// 上报给主 App:记录最近一次“完全访问”状态(App 将据此决定是否展示引导页)
|
||||
[[KBKeyboardPermissionManager shared] reportFullAccessFromExtension:(self.state == KBFullAccessStateGranted)];
|
||||
#endif
|
||||
}
|
||||
|
||||
@end
|
||||
32
CustomKeyboard/Model/KBKey.h
Normal file
32
CustomKeyboard/Model/KBKey.h
Normal file
@@ -0,0 +1,32 @@
|
||||
//
|
||||
// KBKey.h
|
||||
// CustomKeyboard
|
||||
//
|
||||
// 简单的键位数据模型,用于描述键盘上的一个键。
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
typedef NS_ENUM(NSInteger, KBKeyType) {
|
||||
KBKeyTypeCharacter = 0, // 普通字符输出
|
||||
KBKeyTypeBackspace, // 删除
|
||||
KBKeyTypeShift, // 大小写切换
|
||||
KBKeyTypeModeChange, // 模式切换(如 123/ABC)
|
||||
KBKeyTypeSpace, // 空格
|
||||
KBKeyTypeReturn, // 回车/发送
|
||||
KBKeyTypeGlobe, // 系统地球键
|
||||
KBKeyTypeCustom, // 自定义功能占位
|
||||
KBKeyTypeSymbolsToggle // 数字面板内的“#+=/123”切换
|
||||
};
|
||||
|
||||
@interface KBKey : NSObject
|
||||
|
||||
@property (nonatomic, assign) KBKeyType type;
|
||||
@property (nonatomic, copy) NSString *title; // 显示标题
|
||||
@property (nonatomic, copy) NSString *output; // 字符键插入的文本
|
||||
|
||||
+ (instancetype)keyWithTitle:(NSString *)title output:(NSString *)output;
|
||||
+ (instancetype)keyWithTitle:(NSString *)title type:(KBKeyType)type;
|
||||
|
||||
@end
|
||||
27
CustomKeyboard/Model/KBKey.m
Normal file
27
CustomKeyboard/Model/KBKey.m
Normal file
@@ -0,0 +1,27 @@
|
||||
//
|
||||
// KBKey.m
|
||||
// CustomKeyboard
|
||||
//
|
||||
|
||||
#import "KBKey.h"
|
||||
|
||||
@implementation KBKey
|
||||
|
||||
+ (instancetype)keyWithTitle:(NSString *)title output:(NSString *)output {
|
||||
KBKey *k = [[KBKey alloc] init];
|
||||
k.type = KBKeyTypeCharacter;
|
||||
k.title = title ?: @"";
|
||||
k.output = output ?: title ?: @"";
|
||||
return k;
|
||||
}
|
||||
|
||||
+ (instancetype)keyWithTitle:(NSString *)title type:(KBKeyType)type {
|
||||
KBKey *k = [[KBKey alloc] init];
|
||||
k.type = type;
|
||||
k.title = title ?: @"";
|
||||
k.output = @"";
|
||||
return k;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
57
CustomKeyboard/Network/KBNetworkManager.h
Normal file
57
CustomKeyboard/Network/KBNetworkManager.h
Normal file
@@ -0,0 +1,57 @@
|
||||
//
|
||||
// KBNetworkManager.h
|
||||
// CustomKeyboard
|
||||
//
|
||||
// 轻量网络层封装(扩展安全)。支持 GET/POST(JSON)。
|
||||
// 注意:键盘扩展需要"允许完全访问"后才可联网,
|
||||
// 建议由宿主控制器在确认后调用 `setEnabled:YES` 再发起请求。
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
extern NSErrorDomain const KBNetworkErrorDomain;
|
||||
typedef NS_ERROR_ENUM(KBNetworkErrorDomain, KBNetworkError) {
|
||||
KBNetworkErrorDisabled = 1, // 未启用网络(例如未开启完全访问)
|
||||
KBNetworkErrorInvalidURL = 2,
|
||||
KBNetworkErrorInvalidResponse = 3,
|
||||
KBNetworkErrorDecodeFailed = 4,
|
||||
};
|
||||
|
||||
/// 简单的 JSON 回调:json 为 NSDictionary/NSArray 或者在非 JSON 情况下返回 NSData
|
||||
typedef void(^KBNetworkCompletion)(id _Nullable jsonOrData, NSURLResponse * _Nullable response, NSError * _Nullable error);
|
||||
|
||||
@interface KBNetworkManager : NSObject
|
||||
|
||||
/// 单例
|
||||
+ (instancetype)shared;
|
||||
|
||||
/// 是否允许网络(默认为 NO,宿主在合适时机置 YES)
|
||||
@property (atomic, assign, getter=isEnabled) BOOL enabled;
|
||||
|
||||
/// 可选的基础域名,例如 https://api.example.com
|
||||
@property (nonatomic, strong, nullable) NSURL *baseURL;
|
||||
|
||||
/// 全局默认请求头(每次请求会与局部 headers 合并,局部优先)
|
||||
@property (nonatomic, copy) NSDictionary<NSString *, NSString *> *defaultHeaders;
|
||||
|
||||
/// 超时时间(默认 10s)
|
||||
@property (nonatomic, assign) NSTimeInterval timeout;
|
||||
|
||||
/// GET 请求,parameters 会拼到 URL 上
|
||||
- (nullable NSURLSessionDataTask *)GET:(NSString *)path
|
||||
parameters:(nullable NSDictionary *)parameters
|
||||
headers:(nullable NSDictionary<NSString *, NSString *> *)headers
|
||||
completion:(KBNetworkCompletion)completion;
|
||||
|
||||
/// POST JSON 请求,jsonBody 会以 application/json 发送
|
||||
- (nullable NSURLSessionDataTask *)POST:(NSString *)path
|
||||
jsonBody:(nullable id)jsonBody
|
||||
headers:(nullable NSDictionary<NSString *, NSString *> *)headers
|
||||
completion:(KBNetworkCompletion)completion;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
169
CustomKeyboard/Network/KBNetworkManager.m
Normal file
169
CustomKeyboard/Network/KBNetworkManager.m
Normal file
@@ -0,0 +1,169 @@
|
||||
//
|
||||
// KBNetworkManager.m
|
||||
// CustomKeyboard
|
||||
//
|
||||
|
||||
#import "KBNetworkManager.h"
|
||||
#import "AFNetworking.h"
|
||||
#import "KBAuthManager.h"
|
||||
|
||||
NSErrorDomain const KBNetworkErrorDomain = @"com.company.keyboard.network";
|
||||
|
||||
@interface KBNetworkManager ()
|
||||
@property (nonatomic, strong) AFHTTPSessionManager *manager; // AFN 管理器(ephemeral 配置)
|
||||
// 私有错误派发
|
||||
- (void)fail:(KBNetworkError)code completion:(KBNetworkCompletion)completion;
|
||||
@end
|
||||
|
||||
@implementation KBNetworkManager
|
||||
|
||||
+ (instancetype)shared {
|
||||
static KBNetworkManager *m; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ m = [KBNetworkManager new]; });
|
||||
return m;
|
||||
}
|
||||
|
||||
- (instancetype)init {
|
||||
if (self = [super init]) {
|
||||
_enabled = NO; // 键盘扩展默认无网络能力,需外部显式开启
|
||||
_timeout = 10.0;
|
||||
_defaultHeaders = @{ @"Accept": @"application/json" };
|
||||
// 设置基础域名,路径可相对该地址拼接
|
||||
_baseURL = [NSURL URLWithString:KB_BASE_URL];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
#pragma mark - Public
|
||||
|
||||
- (NSURLSessionDataTask *)GET:(NSString *)path
|
||||
parameters:(NSDictionary *)parameters
|
||||
headers:(NSDictionary<NSString *,NSString *> *)headers
|
||||
completion:(KBNetworkCompletion)completion {
|
||||
if (![self ensureEnabled:completion]) return nil;
|
||||
NSString *urlString = [self buildURLStringWithPath:path];
|
||||
if (!urlString) { [self fail:KBNetworkErrorInvalidURL completion:completion]; return nil; }
|
||||
// 使用 AFHTTPRequestSerializer 生成带参数与头的请求
|
||||
AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
|
||||
serializer.timeoutInterval = self.timeout;
|
||||
NSMutableURLRequest *req = [serializer requestWithMethod:@"GET"
|
||||
URLString:urlString
|
||||
parameters:parameters
|
||||
error:NULL];
|
||||
[self applyHeaders:headers toMutableRequest:req contentType:nil];
|
||||
return [self startAFTaskWithRequest:req completion:completion];
|
||||
}
|
||||
|
||||
- (NSURLSessionDataTask *)POST:(NSString *)path
|
||||
jsonBody:(id)jsonBody
|
||||
headers:(NSDictionary<NSString *,NSString *> *)headers
|
||||
completion:(KBNetworkCompletion)completion {
|
||||
if (![self ensureEnabled:completion]) return nil;
|
||||
NSString *urlString = [self buildURLStringWithPath:path];
|
||||
if (!urlString) { [self fail:KBNetworkErrorInvalidURL completion:completion]; return nil; }
|
||||
// 用 JSON 序列化器生成 JSON Body 的请求
|
||||
AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];
|
||||
serializer.timeoutInterval = self.timeout;
|
||||
NSError *error = nil;
|
||||
NSMutableURLRequest *req = [serializer requestWithMethod:@"POST"
|
||||
URLString:urlString
|
||||
parameters:jsonBody
|
||||
error:&error];
|
||||
if (error) { if (completion) completion(nil, nil, error); return nil; }
|
||||
[self applyHeaders:headers toMutableRequest:req contentType:nil];
|
||||
return [self startAFTaskWithRequest:req completion:completion];
|
||||
}
|
||||
|
||||
#pragma mark - Core
|
||||
|
||||
- (BOOL)ensureEnabled:(KBNetworkCompletion)completion {
|
||||
if (!self.isEnabled) {
|
||||
NSError *e = [NSError errorWithDomain:KBNetworkErrorDomain code:KBNetworkErrorDisabled userInfo:@{NSLocalizedDescriptionKey: @"网络未启用(可能未开启完全访问)"}];
|
||||
if (completion) completion(nil, nil, e);
|
||||
return NO;
|
||||
}
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (NSString *)buildURLStringWithPath:(NSString *)path {
|
||||
if (path.length == 0) return nil;
|
||||
if ([path hasPrefix:@"http://"] || [path hasPrefix:@"https://"]) {
|
||||
return path;
|
||||
}
|
||||
if (self.baseURL) {
|
||||
return [NSURL URLWithString:path relativeToURL:self.baseURL].absoluteURL.absoluteString;
|
||||
}
|
||||
return path; // 当无 baseURL 且 path 不是完整 URL 时,让 AFN 处理(可能失败)
|
||||
}
|
||||
|
||||
- (void)applyHeaders:(NSDictionary<NSString *,NSString *> *)headers toMutableRequest:(NSMutableURLRequest *)req contentType:(NSString *)contentType {
|
||||
// 合并默认头与局部头,并注入授权头(若可用)。局部覆盖优先。
|
||||
NSMutableDictionary *all = [self.defaultHeaders mutableCopy] ?: [NSMutableDictionary new];
|
||||
NSDictionary *auth = [[KBAuthManager shared] authorizationHeader];
|
||||
[auth enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL *stop) { all[key] = obj; }];
|
||||
if (contentType) all[@"Content-Type"] = contentType;
|
||||
[headers enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL *stop) { all[key] = obj; }];
|
||||
[all enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL *stop) { [req setValue:obj forHTTPHeaderField:key]; }];
|
||||
}
|
||||
|
||||
- (NSURLSessionDataTask *)startAFTaskWithRequest:(NSURLRequest *)req completion:(KBNetworkCompletion)completion {
|
||||
// 响应先用原始数据返回,再按 Content-Type 解析 JSON(与原实现一致)
|
||||
self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
|
||||
NSURLSessionDataTask *task = [self.manager dataTaskWithRequest:req uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
|
||||
if (error) { if (completion) completion(nil, response, error); return; }
|
||||
NSData *data = (NSData *)responseObject;
|
||||
if (![data isKindOfClass:[NSData class]]) {
|
||||
if (completion) completion(nil, response, [NSError errorWithDomain:KBNetworkErrorDomain code:KBNetworkErrorInvalidResponse userInfo:@{NSLocalizedDescriptionKey:@"无数据"}]);
|
||||
return;
|
||||
}
|
||||
NSString *ct = nil;
|
||||
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
|
||||
ct = ((NSHTTPURLResponse *)response).allHeaderFields[@"Content-Type"];
|
||||
}
|
||||
BOOL looksJSON = (ct && [ct.lowercaseString containsString:@"application/json"]);
|
||||
if (looksJSON) {
|
||||
NSError *jsonErr = nil;
|
||||
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonErr];
|
||||
if (jsonErr) { if (completion) completion(nil, response, [NSError errorWithDomain:KBNetworkErrorDomain code:KBNetworkErrorDecodeFailed userInfo:@{NSLocalizedDescriptionKey:@"JSON解析失败"}]); return; }
|
||||
if (completion) completion(json, response, nil);
|
||||
} else {
|
||||
if (completion) completion(data, response, nil);
|
||||
}
|
||||
}];
|
||||
[task resume];
|
||||
return task;
|
||||
}
|
||||
|
||||
#pragma mark - AFHTTPSessionManager
|
||||
|
||||
- (AFHTTPSessionManager *)manager {
|
||||
if (!_manager) {
|
||||
NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration ephemeralSessionConfiguration];
|
||||
cfg.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
|
||||
cfg.timeoutIntervalForRequest = self.timeout;
|
||||
cfg.timeoutIntervalForResource = MAX(self.timeout, 30.0);
|
||||
if (@available(iOS 11.0, *)) { cfg.waitsForConnectivity = YES; }
|
||||
_manager = [[AFHTTPSessionManager alloc] initWithBaseURL:nil sessionConfiguration:cfg];
|
||||
// 默认不使用 JSON 解析器,保持原生数据,再按需解析
|
||||
_manager.responseSerializer = [AFHTTPResponseSerializer serializer];
|
||||
}
|
||||
return _manager;
|
||||
}
|
||||
|
||||
#pragma mark - Private helpers
|
||||
|
||||
- (void)fail:(KBNetworkError)code completion:(KBNetworkCompletion)completion {
|
||||
NSString *msg = @"网络错误";
|
||||
switch (code) {
|
||||
case KBNetworkErrorDisabled: msg = @"网络未启用(可能未开启完全访问)"; break;
|
||||
case KBNetworkErrorInvalidURL: msg = @"无效的URL"; break;
|
||||
case KBNetworkErrorInvalidResponse: msg = @"无效的响应"; break;
|
||||
case KBNetworkErrorDecodeFailed: msg = @"解析失败"; break;
|
||||
default: break;
|
||||
}
|
||||
NSError *e = [NSError errorWithDomain:KBNetworkErrorDomain
|
||||
code:code
|
||||
userInfo:@{NSLocalizedDescriptionKey: msg}];
|
||||
if (completion) completion(nil, nil, e);
|
||||
}
|
||||
|
||||
@end
|
||||
31
CustomKeyboard/PrefixHeader.pch
Normal file
31
CustomKeyboard/PrefixHeader.pch
Normal file
@@ -0,0 +1,31 @@
|
||||
//
|
||||
// PrefixHeader.pch
|
||||
// CustomKeyboard
|
||||
//
|
||||
// Created by Mac on 2025/10/27.
|
||||
//
|
||||
|
||||
#ifndef PrefixHeader_pch
|
||||
#define PrefixHeader_pch
|
||||
|
||||
// Include any system framework and library headers here that should be included in all compilation units.
|
||||
// You will also need to set the Prefix Header build setting of one or more of your targets to reference this file.
|
||||
|
||||
#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
|
||||
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
|
||||
#define imageNamed(s) [UIImage imageNamed:s]
|
||||
|
||||
// 公共配置
|
||||
#import "KBConfig.h"
|
||||
#import "Masonry.h"
|
||||
#import "KBHUD.h" // 复用 App 内的 HUD 封装
|
||||
#import "KBLocalizationManager.h" // 复用多语言封装(可在扩展内使用)
|
||||
|
||||
// 通用链接(Universal Links)统一配置
|
||||
// 配置好 AASA 与 Associated Domains 后,只需修改这里即可切换域名/path。
|
||||
#define KB_UL_BASE @"https://your.domain/ul" // 替换为你的真实域名与前缀路径
|
||||
#define KB_UL_LOGIN KB_UL_BASE @"/login"
|
||||
#define KB_UL_SETTINGS KB_UL_BASE @"/settings"
|
||||
|
||||
|
||||
#endif /* PrefixHeader_pch */
|
||||
19
CustomKeyboard/View/KBFullAccessGuideView.h
Normal file
19
CustomKeyboard/View/KBFullAccessGuideView.h
Normal file
@@ -0,0 +1,19 @@
|
||||
//
|
||||
// KBFullAccessGuideView.h
|
||||
// CustomKeyboard
|
||||
//
|
||||
// A lightweight overlay prompting user to enable "Allow Full Access".
|
||||
//
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
@interface KBFullAccessGuideView : UIView
|
||||
|
||||
/// Present the guide overlay inside a given parent view (or its window).
|
||||
+ (void)showInView:(UIView *)parent;
|
||||
|
||||
/// Dismiss if shown.
|
||||
+ (void)dismissFromView:(UIView *)parent;
|
||||
|
||||
@end
|
||||
|
||||
185
CustomKeyboard/View/KBFullAccessGuideView.m
Normal file
185
CustomKeyboard/View/KBFullAccessGuideView.m
Normal file
@@ -0,0 +1,185 @@
|
||||
//
|
||||
// KBFullAccessGuideView.m
|
||||
// CustomKeyboard
|
||||
// 没有开启完全访问的提示框
|
||||
|
||||
#import "KBFullAccessGuideView.h"
|
||||
#import "Masonry.h"
|
||||
|
||||
@interface KBFullAccessGuideView ()
|
||||
@property (nonatomic, strong) UIControl *backdrop;
|
||||
@property (nonatomic, strong) UIView *card;
|
||||
@end
|
||||
|
||||
@implementation KBFullAccessGuideView
|
||||
|
||||
+ (instancetype)build {
|
||||
KBFullAccessGuideView *v = [[KBFullAccessGuideView alloc] initWithFrame:CGRectZero];
|
||||
[v setupUI];
|
||||
return v;
|
||||
}
|
||||
|
||||
- (void)setupUI {
|
||||
self.backgroundColor = [UIColor clearColor];
|
||||
|
||||
self.backdrop = [[UIControl alloc] init];
|
||||
self.backdrop.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.35];
|
||||
// [self.backdrop addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
|
||||
[self addSubview:self.backdrop];
|
||||
[self.backdrop mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.edges.equalTo(self);
|
||||
}];
|
||||
|
||||
self.card = [[UIView alloc] init];
|
||||
self.card.backgroundColor = [UIColor whiteColor];
|
||||
self.card.layer.cornerRadius = 16;
|
||||
self.card.layer.masksToBounds = YES;
|
||||
[self addSubview:self.card];
|
||||
[self.card mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.center.equalTo(self);
|
||||
make.left.equalTo(self).offset(28);
|
||||
make.right.equalTo(self).offset(-28);
|
||||
}];
|
||||
|
||||
UILabel *title = [UILabel new];
|
||||
title.text = @"开启【允许完全访问】,体验完整功能";
|
||||
title.font = [UIFont boldSystemFontOfSize:16];
|
||||
title.textColor = [UIColor blackColor];
|
||||
title.textAlignment = NSTextAlignmentCenter;
|
||||
[self.card addSubview:title];
|
||||
[title mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.top.equalTo(self.card).offset(16);
|
||||
make.left.right.equalTo(self.card).insets(UIEdgeInsetsMake(0, 16, 0, 16));
|
||||
}];
|
||||
|
||||
// 模拟两行开关(纯展示,不真实控制)
|
||||
UIView *box = [UIView new];
|
||||
box.backgroundColor = [UIColor colorWithWhite:0.98 alpha:1.0];
|
||||
box.layer.cornerRadius = 12;
|
||||
[self.card addSubview:box];
|
||||
[box mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.top.equalTo(title.mas_bottom).offset(12);
|
||||
make.left.equalTo(self.card).offset(16);
|
||||
make.right.equalTo(self.card).offset(-16);
|
||||
make.height.mas_equalTo(100);
|
||||
}];
|
||||
|
||||
UILabel *row1 = [UILabel new]; row1.text = @"恋爱键盘"; row1.textColor = [UIColor blackColor];
|
||||
UILabel *row2 = [UILabel new]; row2.text = @"允许完全访问"; row2.textColor = [UIColor blackColor];
|
||||
[box addSubview:row1]; [box addSubview:row2];
|
||||
[row1 mas_makeConstraints:^(MASConstraintMaker *make) { make.left.equalTo(box).offset(16); make.top.equalTo(box).offset(14); }];
|
||||
UIView *line = [UIView new]; line.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1.0];
|
||||
[box addSubview:line];
|
||||
[line mas_makeConstraints:^(MASConstraintMaker *make) { make.left.equalTo(box).offset(12); make.right.equalTo(box).offset(-12); make.centerY.equalTo(box); make.height.mas_equalTo(1); }];
|
||||
[row2 mas_makeConstraints:^(MASConstraintMaker *make) { make.left.equalTo(box).offset(16); make.bottom.equalTo(box).offset(-14); }];
|
||||
|
||||
// 右侧绿色开关的装饰
|
||||
UIView* (^switchView)(void) = ^UIView *{
|
||||
UIView *sw = [UIView new];
|
||||
sw.backgroundColor = [UIColor colorWithRed:0.12 green:0.75 blue:0.35 alpha:1.0];
|
||||
sw.layer.cornerRadius = 15;
|
||||
UIView *dot = [UIView new];
|
||||
dot.backgroundColor = [UIColor whiteColor];
|
||||
dot.layer.cornerRadius = 12;
|
||||
[sw addSubview:dot];
|
||||
[dot mas_makeConstraints:^(MASConstraintMaker *make) { make.centerY.equalTo(sw); make.right.equalTo(sw).offset(-3); make.width.height.mas_equalTo(24); }];
|
||||
[sw mas_makeConstraints:^(MASConstraintMaker *make) { make.width.mas_equalTo(52); make.height.mas_equalTo(30); }];
|
||||
return sw;
|
||||
};
|
||||
UIView *sw1 = switchView(); UIView *sw2 = switchView();
|
||||
[box addSubview:sw1]; [box addSubview:sw2];
|
||||
[sw1 mas_makeConstraints:^(MASConstraintMaker *make) { make.right.equalTo(box).offset(-12); make.centerY.equalTo(row1); }];
|
||||
[sw2 mas_makeConstraints:^(MASConstraintMaker *make) { make.right.equalTo(box).offset(-12); make.centerY.equalTo(row2); }];
|
||||
|
||||
UIButton *go = [UIButton buttonWithType:UIButtonTypeSystem];
|
||||
go.backgroundColor = [UIColor blackColor];
|
||||
[go setTitle:@"去开启" forState:UIControlStateNormal];
|
||||
[go setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
|
||||
go.titleLabel.font = [UIFont boldSystemFontOfSize:18];
|
||||
go.layer.cornerRadius = 12;
|
||||
[go addTarget:self action:@selector(onTapGoEnable) forControlEvents:UIControlEventTouchUpInside];
|
||||
[self.card addSubview:go];
|
||||
[go mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.top.equalTo(box.mas_bottom).offset(16);
|
||||
make.left.equalTo(self.card).offset(16);
|
||||
make.right.equalTo(self.card).offset(-16);
|
||||
make.height.mas_equalTo(48);
|
||||
make.bottom.equalTo(self.card).offset(-16);
|
||||
}];
|
||||
}
|
||||
|
||||
- (void)presentIn:(UIView *)parent {
|
||||
UIView *container = parent.window ?: parent;
|
||||
self.frame = container.bounds;
|
||||
self.alpha = 0;
|
||||
[container addSubview:self];
|
||||
[self mas_makeConstraints:^(MASConstraintMaker *make) { make.edges.equalTo(container); }];
|
||||
[UIView animateWithDuration:0.2 animations:^{ self.alpha = 1; }];
|
||||
}
|
||||
|
||||
- (void)dismiss {
|
||||
[UIView animateWithDuration:0.18 animations:^{ self.alpha = 0; } completion:^(BOOL finished) {
|
||||
[self removeFromSuperview];
|
||||
}];
|
||||
}
|
||||
|
||||
+ (void)showInView:(UIView *)parent {
|
||||
if (!parent) return;
|
||||
// 避免重复
|
||||
for (UIView *v in (parent.window ?: parent).subviews) {
|
||||
if ([v isKindOfClass:[KBFullAccessGuideView class]]) return;
|
||||
}
|
||||
[[KBFullAccessGuideView build] presentIn:parent];
|
||||
}
|
||||
|
||||
+ (void)dismissFromView:(UIView *)parent {
|
||||
UIView *container = parent.window ?: parent;
|
||||
for (UIView *v in container.subviews) {
|
||||
if ([v isKindOfClass:[KBFullAccessGuideView class]]) {
|
||||
[(KBFullAccessGuideView *)v dismiss];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
#pragma mark - Actions
|
||||
|
||||
- (UIInputViewController *)kb_findInputController {
|
||||
UIResponder *res = self;
|
||||
while (res) {
|
||||
if ([res isKindOfClass:[UIInputViewController class]]) {
|
||||
return (UIInputViewController *)res;
|
||||
}
|
||||
res = res.nextResponder;
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
- (void)onTapGoEnable {
|
||||
// 在扩展中无法使用 UIApplication。改为委托宿主打开链接:
|
||||
// 方案:优先拉起主 App 并由主 App 打开设置页,避免宿主拦截。
|
||||
UIInputViewController *ivc = [self kb_findInputController];
|
||||
if (!ivc) { [self dismiss]; return; }
|
||||
|
||||
// 先尝试 Universal Link(如未配置可改为你的域名),失败再用自定义 scheme。
|
||||
NSURL *ul = [NSURL URLWithString:[NSString stringWithFormat:@"%@?src=kb_extension", KB_UL_SETTINGS]];
|
||||
void (^fallback)(void) = ^{
|
||||
NSURL *scheme = [NSURL URLWithString:@"kbkeyboard://settings?src=kb_extension"]; // 主App在 openURL 中处理
|
||||
[ivc.extensionContext openURL:scheme completionHandler:^(__unused BOOL ok2) {
|
||||
// 无论成功与否,都收起当前提示层,避免遮挡
|
||||
[self dismiss];
|
||||
}];
|
||||
};
|
||||
|
||||
if (ul) {
|
||||
[ivc.extensionContext openURL:ul completionHandler:^(BOOL ok) {
|
||||
if (ok) { [self dismiss]; }
|
||||
else { fallback(); }
|
||||
}];
|
||||
} else {
|
||||
fallback();
|
||||
}
|
||||
}
|
||||
@end
|
||||
39
CustomKeyboard/View/KBFunctionBarView.h
Normal file
39
CustomKeyboard/View/KBFunctionBarView.h
Normal file
@@ -0,0 +1,39 @@
|
||||
//
|
||||
// KBFunctionBarView.h
|
||||
// CustomKeyboard
|
||||
//
|
||||
// Created by Mac on 2025/10/28.
|
||||
//
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/// 功能区顶部的Bar:左侧4个按钮,右侧3个按钮
|
||||
@class KBFunctionBarView;
|
||||
|
||||
@protocol KBFunctionBarViewDelegate <NSObject>
|
||||
@optional
|
||||
/// 左侧 4 个按钮点击(index: 0~3)
|
||||
- (void)functionBarView:(KBFunctionBarView *)bar didTapLeftAtIndex:(NSInteger)index;
|
||||
/// 右侧 3 个按钮点击(index: 0~2)
|
||||
- (void)functionBarView:(KBFunctionBarView *)bar didTapRightAtIndex:(NSInteger)index;
|
||||
@end
|
||||
|
||||
@interface KBFunctionBarView : UIView
|
||||
|
||||
@property (nonatomic, weak, nullable) id<KBFunctionBarViewDelegate> delegate;
|
||||
|
||||
/// 左侧4个按钮(懒加载创建,等宽水平排布)
|
||||
@property (nonatomic, strong, readonly) NSArray<UIButton *> *leftButtons;
|
||||
|
||||
/// 右侧3个按钮(懒加载创建,等宽水平排布,靠右)
|
||||
@property (nonatomic, strong, readonly) NSArray<UIButton *> *rightButtons;
|
||||
|
||||
/// 配置按钮标题(可选)
|
||||
@property (nonatomic, copy) NSArray<NSString *> *leftTitles; // 默认 @[@"帮回", @"会说", @"话术", @"更多"]
|
||||
@property (nonatomic, copy) NSArray<NSString *> *rightTitles; // 默认 @[@"❤", @"收藏", @"宫格"]
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
161
CustomKeyboard/View/KBFunctionBarView.m
Normal file
161
CustomKeyboard/View/KBFunctionBarView.m
Normal file
@@ -0,0 +1,161 @@
|
||||
//
|
||||
// KBFunctionBarView.m
|
||||
// CustomKeyboard
|
||||
//
|
||||
// Created by Mac on 2025/10/28.
|
||||
// 功能 - barview
|
||||
|
||||
#import "KBFunctionBarView.h"
|
||||
#import "Masonry.h"
|
||||
|
||||
@interface KBFunctionBarView ()
|
||||
@property (nonatomic, strong) UIView *leftContainer; // 左侧按钮容器
|
||||
@property (nonatomic, strong) UIView *rightContainer; // 右侧按钮容器
|
||||
@property (nonatomic, strong) NSArray<UIButton *> *leftButtonsInternal;
|
||||
@property (nonatomic, strong) NSArray<UIButton *> *rightButtonsInternal;
|
||||
@end
|
||||
|
||||
@implementation KBFunctionBarView
|
||||
|
||||
- (instancetype)initWithFrame:(CGRect)frame{
|
||||
if (self = [super initWithFrame:frame]) {
|
||||
self.backgroundColor = [UIColor clearColor];
|
||||
_leftTitles = @[@"ABC"];
|
||||
_rightTitles = @[@"Upgrade VIP"];
|
||||
[self buildUI];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
#pragma mark - Public
|
||||
|
||||
- (NSArray<UIButton *> *)leftButtons { return self.leftButtonsInternal; }
|
||||
- (NSArray<UIButton *> *)rightButtons { return self.rightButtonsInternal; }
|
||||
|
||||
|
||||
#pragma mark - UI
|
||||
|
||||
- (void)buildUI {
|
||||
// 左右两个容器,方便分别布局
|
||||
[self addSubview:self.leftContainer];
|
||||
[self addSubview:self.rightContainer];
|
||||
|
||||
[self.rightContainer mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.right.equalTo(self.mas_right).offset(-12);
|
||||
make.centerY.equalTo(self.mas_centerY);
|
||||
make.height.mas_equalTo(36);
|
||||
}];
|
||||
|
||||
[self.leftContainer mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.left.equalTo(self.mas_left).offset(12);
|
||||
make.right.equalTo(self.rightContainer.mas_left).offset(-12);
|
||||
make.centerY.equalTo(self.mas_centerY);
|
||||
make.height.mas_equalTo(36);
|
||||
}];
|
||||
|
||||
// 左侧4个等宽按钮
|
||||
NSMutableArray<UIButton *> *leftBtns = [NSMutableArray arrayWithCapacity:4];
|
||||
UIView *prev = nil;
|
||||
for (NSInteger i = 0; i < self.leftTitles.count; i++) {
|
||||
UIButton *btn = [self buildButtonWithTitle:(i < self.leftTitles.count ? self.leftTitles[i] : [NSString stringWithFormat:@"L%ld", (long)i])];
|
||||
btn.tag = 100 + i;
|
||||
[btn addTarget:self action:@selector(onLeftTap:) forControlEvents:UIControlEventTouchUpInside];
|
||||
[self.leftContainer addSubview:btn];
|
||||
[btn mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
if (prev) {
|
||||
make.left.equalTo(prev.mas_right).offset(8);
|
||||
make.width.equalTo(prev);
|
||||
} else {
|
||||
make.left.equalTo(self.leftContainer.mas_left);
|
||||
}
|
||||
make.top.bottom.equalTo(self.leftContainer);
|
||||
}];
|
||||
prev = btn;
|
||||
[leftBtns addObject:btn];
|
||||
}
|
||||
[prev mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.right.equalTo(self.leftContainer.mas_right);
|
||||
}];
|
||||
self.leftButtonsInternal = leftBtns.copy;
|
||||
|
||||
// 右侧N个按钮(靠右、两两等宽)
|
||||
NSMutableArray<UIButton *> *rightBtns = [NSMutableArray arrayWithCapacity:3];
|
||||
for (NSInteger i = 0; i < self.rightTitles.count; i++) {
|
||||
UIButton *btn = [self buildButtonWithTitle:(i < self.rightTitles.count ? self.rightTitles[i] : [NSString stringWithFormat:@"R%ld", (long)i])];
|
||||
btn.tag = 200 + i;
|
||||
[self.rightContainer addSubview:btn];
|
||||
[btn addTarget:self action:@selector(onRightTap:) forControlEvents:UIControlEventTouchUpInside];
|
||||
[rightBtns addObject:btn];
|
||||
}
|
||||
|
||||
// 从右往左链式布局,保证整体靠右;支持 1/2/3... 任意数量
|
||||
UIView *prevRight = nil; // 指向右侧已布局的按钮
|
||||
for (NSInteger i = rightBtns.count - 1; i >= 0; i--) {
|
||||
UIButton *btn = rightBtns[i];
|
||||
[btn mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
if (!prevRight) {
|
||||
// 最右侧按钮贴右
|
||||
make.right.equalTo(self.rightContainer.mas_right);
|
||||
} else {
|
||||
// 其余按钮紧挨左侧兄弟,且与其等宽
|
||||
make.right.equalTo(prevRight.mas_left).offset(-8);
|
||||
make.width.equalTo(prevRight);
|
||||
}
|
||||
make.top.bottom.equalTo(self.rightContainer);
|
||||
}];
|
||||
prevRight = btn;
|
||||
}
|
||||
// 最左侧一个不超出容器左边(允许根据内容自然宽度收缩)
|
||||
if (prevRight) {
|
||||
[prevRight mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.left.greaterThanOrEqualTo(self.rightContainer.mas_left);
|
||||
}];
|
||||
}
|
||||
|
||||
self.rightButtonsInternal = rightBtns.copy;
|
||||
}
|
||||
|
||||
#pragma mark - Actions
|
||||
|
||||
- (void)onLeftTap:(UIButton *)sender {
|
||||
NSInteger idx = sender.tag - 100;
|
||||
if ([self.delegate respondsToSelector:@selector(functionBarView:didTapLeftAtIndex:)]) {
|
||||
[self.delegate functionBarView:self didTapLeftAtIndex:idx];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)onRightTap:(UIButton *)sender {
|
||||
NSInteger idx = sender.tag - 200;
|
||||
if ([self.delegate respondsToSelector:@selector(functionBarView:didTapRightAtIndex:)]) {
|
||||
[self.delegate functionBarView:self didTapRightAtIndex:idx];
|
||||
}
|
||||
}
|
||||
|
||||
- (UIButton *)buildButtonWithTitle:(NSString *)title {
|
||||
UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
|
||||
btn.layer.cornerRadius = 18;
|
||||
btn.layer.masksToBounds = YES;
|
||||
btn.backgroundColor = [UIColor colorWithWhite:1 alpha:0.9];
|
||||
btn.titleLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightMedium];
|
||||
[btn setTitle:title forState:UIControlStateNormal];
|
||||
[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
|
||||
return btn;
|
||||
}
|
||||
|
||||
#pragma mark - Lazy
|
||||
|
||||
- (UIView *)leftContainer {
|
||||
if (!_leftContainer) {
|
||||
_leftContainer = [[UIView alloc] init];
|
||||
}
|
||||
return _leftContainer;
|
||||
}
|
||||
|
||||
- (UIView *)rightContainer {
|
||||
if (!_rightContainer) {
|
||||
_rightContainer = [[UIView alloc] init];
|
||||
}
|
||||
return _rightContainer;
|
||||
}
|
||||
|
||||
@end
|
||||
23
CustomKeyboard/View/KBFunctionPasteView.h
Normal file
23
CustomKeyboard/View/KBFunctionPasteView.h
Normal file
@@ -0,0 +1,23 @@
|
||||
//
|
||||
// KBFunctionPasteView.h
|
||||
// CustomKeyboard
|
||||
//
|
||||
// Created by Mac on 2025/10/28.
|
||||
//
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/// 粘贴提示输入框区域(左侧图标+占位文案,圆角白底)
|
||||
@interface KBFunctionPasteView : UIView
|
||||
|
||||
/// 左侧图标
|
||||
@property (nonatomic, strong, readonly) UIImageView *iconView;
|
||||
|
||||
/// 提示文案,例如:点击粘贴TA的话
|
||||
@property (nonatomic, strong, readonly) UILabel *placeholderLabel;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
75
CustomKeyboard/View/KBFunctionPasteView.m
Normal file
75
CustomKeyboard/View/KBFunctionPasteView.m
Normal file
@@ -0,0 +1,75 @@
|
||||
//
|
||||
// KBFunctionPasteView.m
|
||||
// CustomKeyboard
|
||||
//
|
||||
// Created by Mac on 2025/10/28.
|
||||
// 粘贴View
|
||||
|
||||
#import "KBFunctionPasteView.h"
|
||||
#import "Masonry.h"
|
||||
|
||||
@interface KBFunctionPasteView ()
|
||||
@property (nonatomic, strong) UIImageView *iconViewInternal;
|
||||
@property (nonatomic, strong) UILabel *placeholderLabelInternal;
|
||||
@end
|
||||
|
||||
@implementation KBFunctionPasteView
|
||||
|
||||
- (instancetype)initWithFrame:(CGRect)frame {
|
||||
if (self = [super initWithFrame:frame]) {
|
||||
// 白底圆角容器
|
||||
self.backgroundColor = [UIColor colorWithWhite:1 alpha:0.95];
|
||||
self.layer.cornerRadius = 12.0;
|
||||
self.layer.masksToBounds = YES;
|
||||
|
||||
[self addSubview:self.iconViewInternal];
|
||||
[self addSubview:self.placeholderLabelInternal];
|
||||
|
||||
[self.iconViewInternal mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.left.equalTo(self.mas_left).offset(12);
|
||||
make.centerY.equalTo(self.mas_centerY);
|
||||
make.width.height.mas_equalTo(20);
|
||||
}];
|
||||
[self.placeholderLabelInternal mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.left.equalTo(self.iconViewInternal.mas_right).offset(8);
|
||||
make.right.equalTo(self.mas_right).offset(-12);
|
||||
make.centerY.equalTo(self.mas_centerY);
|
||||
}];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
#pragma mark - Lazy
|
||||
|
||||
- (UIImageView *)iconViewInternal {
|
||||
if (!_iconViewInternal) {
|
||||
_iconViewInternal = [[UIImageView alloc] init];
|
||||
// 用简单的系统表情代替资源图(项目可替换成实际图片)
|
||||
UILabel *emoji = [[UILabel alloc] init];
|
||||
emoji.text = @"📋"; // 粘贴/剪贴板含义
|
||||
emoji.font = [UIFont systemFontOfSize:18];
|
||||
emoji.textAlignment = NSTextAlignmentCenter;
|
||||
[_iconViewInternal addSubview:emoji];
|
||||
[emoji mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.edges.equalTo(_iconViewInternal);
|
||||
}];
|
||||
}
|
||||
return _iconViewInternal;
|
||||
}
|
||||
|
||||
- (UILabel *)placeholderLabelInternal {
|
||||
if (!_placeholderLabelInternal) {
|
||||
_placeholderLabelInternal = [[UILabel alloc] init];
|
||||
_placeholderLabelInternal.text = @"点击粘贴TA的话";
|
||||
_placeholderLabelInternal.textColor = [UIColor colorWithRed:0.20 green:0.64 blue:0.54 alpha:1.0];
|
||||
_placeholderLabelInternal.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
|
||||
}
|
||||
return _placeholderLabelInternal;
|
||||
}
|
||||
|
||||
#pragma mark - Expose
|
||||
|
||||
- (UIImageView *)iconView { return self.iconViewInternal; }
|
||||
- (UILabel *)placeholderLabel { return self.placeholderLabelInternal; }
|
||||
|
||||
@end
|
||||
23
CustomKeyboard/View/KBFunctionTagCell.h
Normal file
23
CustomKeyboard/View/KBFunctionTagCell.h
Normal file
@@ -0,0 +1,23 @@
|
||||
//
|
||||
// KBFunctionTagCell.h
|
||||
// CustomKeyboard
|
||||
//
|
||||
// Created by Codex on 2025/10/28.
|
||||
// 话术标签Cell:左图标+右标题,圆角灰白底
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface KBFunctionTagCell : UICollectionViewCell
|
||||
|
||||
/// 标题
|
||||
@property (nonatomic, strong, readonly) UILabel *titleLabel;
|
||||
|
||||
/// 头像/图标
|
||||
@property (nonatomic, strong, readonly) UIImageView *iconView;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
73
CustomKeyboard/View/KBFunctionTagCell.m
Normal file
73
CustomKeyboard/View/KBFunctionTagCell.m
Normal file
@@ -0,0 +1,73 @@
|
||||
//
|
||||
// KBFunctionTagCell.m
|
||||
// CustomKeyboard
|
||||
//
|
||||
// Created by Codex on 2025/10/28.
|
||||
//
|
||||
|
||||
#import "KBFunctionTagCell.h"
|
||||
#import "Masonry.h"
|
||||
|
||||
@interface KBFunctionTagCell ()
|
||||
@property (nonatomic, strong) UILabel *titleLabelInternal;
|
||||
@property (nonatomic, strong) UIImageView *iconViewInternal;
|
||||
@end
|
||||
|
||||
@implementation KBFunctionTagCell
|
||||
|
||||
- (instancetype)initWithFrame:(CGRect)frame {
|
||||
if (self = [super initWithFrame:frame]) {
|
||||
self.contentView.backgroundColor = [UIColor colorWithWhite:1 alpha:0.9];
|
||||
self.contentView.layer.cornerRadius = 12;
|
||||
self.contentView.layer.masksToBounds = YES;
|
||||
|
||||
[self.contentView addSubview:self.iconViewInternal];
|
||||
[self.contentView addSubview:self.titleLabelInternal];
|
||||
|
||||
[self.iconViewInternal mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.left.equalTo(self.contentView.mas_left).offset(10);
|
||||
make.centerY.equalTo(self.contentView.mas_centerY);
|
||||
make.width.height.mas_equalTo(24);
|
||||
}];
|
||||
[self.titleLabelInternal mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.left.equalTo(self.iconViewInternal.mas_right).offset(6);
|
||||
make.right.equalTo(self.contentView.mas_right).offset(-10);
|
||||
make.centerY.equalTo(self.contentView.mas_centerY);
|
||||
}];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
#pragma mark - Lazy
|
||||
|
||||
- (UIImageView *)iconViewInternal {
|
||||
if (!_iconViewInternal) {
|
||||
_iconViewInternal = [[UIImageView alloc] init];
|
||||
UILabel *emoji = [[UILabel alloc] init];
|
||||
emoji.text = @"🙂"; // 占位图标
|
||||
emoji.textAlignment = NSTextAlignmentCenter;
|
||||
emoji.font = [UIFont systemFontOfSize:20];
|
||||
[_iconViewInternal addSubview:emoji];
|
||||
[emoji mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.edges.equalTo(_iconViewInternal);
|
||||
}];
|
||||
}
|
||||
return _iconViewInternal;
|
||||
}
|
||||
|
||||
- (UILabel *)titleLabelInternal {
|
||||
if (!_titleLabelInternal) {
|
||||
_titleLabelInternal = [[UILabel alloc] init];
|
||||
_titleLabelInternal.font = [UIFont systemFontOfSize:15 weight:UIFontWeightSemibold];
|
||||
_titleLabelInternal.textColor = [UIColor blackColor];
|
||||
}
|
||||
return _titleLabelInternal;
|
||||
}
|
||||
|
||||
#pragma mark - Expose
|
||||
|
||||
- (UILabel *)titleLabel { return self.titleLabelInternal; }
|
||||
- (UIImageView *)iconView { return self.iconViewInternal; }
|
||||
|
||||
@end
|
||||
|
||||
38
CustomKeyboard/View/KBFunctionView.h
Normal file
38
CustomKeyboard/View/KBFunctionView.h
Normal file
@@ -0,0 +1,38 @@
|
||||
//
|
||||
// KBFunctionView.h
|
||||
// CustomKeyboard
|
||||
//
|
||||
// Created by Mac on 2025/10/28.
|
||||
//
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
@class KBFunctionBarView, KBFunctionPasteView,KBFunctionView;
|
||||
|
||||
@protocol KBFunctionViewDelegate <NSObject>
|
||||
@optional
|
||||
- (void)functionView:(KBFunctionView *_Nullable)functionView didTapToolActionAtIndex:(NSInteger)index;
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/// 整个功能面板视图:顶部Bar + 粘贴区 + 标签列表 + 右侧操作按钮
|
||||
@interface KBFunctionView : UIView
|
||||
|
||||
@property (nonatomic, weak) id<KBFunctionViewDelegate> delegate;
|
||||
|
||||
|
||||
@property (nonatomic, strong, readonly) UICollectionView *collectionView; // 话术分类/标签列表
|
||||
@property (nonatomic, strong, readonly) NSArray<NSString *> *items; // 简单数据源(演示用)
|
||||
|
||||
// 子视图暴露,便于外部接入事件
|
||||
@property (nonatomic, strong, readonly) KBFunctionBarView *barView;
|
||||
@property (nonatomic, strong, readonly) KBFunctionPasteView *pasteView;
|
||||
|
||||
@property (nonatomic, strong, readonly) UIButton *pasteButton; // 右侧-粘贴
|
||||
@property (nonatomic, strong, readonly) UIButton *deleteButton; // 右侧-删除
|
||||
@property (nonatomic, strong, readonly) UIButton *clearButton; // 右侧-清空
|
||||
@property (nonatomic, strong, readonly) UIButton *sendButton; // 右侧-发送
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
432
CustomKeyboard/View/KBFunctionView.m
Normal file
432
CustomKeyboard/View/KBFunctionView.m
Normal file
@@ -0,0 +1,432 @@
|
||||
//
|
||||
// KBFunctionView.m
|
||||
// CustomKeyboard
|
||||
//
|
||||
// Created by Mac on 2025/10/28.
|
||||
//
|
||||
|
||||
#import "KBFunctionView.h"
|
||||
#import "KBFunctionBarView.h"
|
||||
#import "KBFunctionPasteView.h"
|
||||
#import "KBFunctionTagCell.h"
|
||||
#import "Masonry.h"
|
||||
#import <MBProgressHUD.h>
|
||||
#import "KBFullAccessGuideView.h"
|
||||
#import "KBFullAccessManager.h"
|
||||
|
||||
static NSString * const kKBFunctionTagCellId = @"KBFunctionTagCellId";
|
||||
|
||||
@interface KBFunctionView () <UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, KBFunctionBarViewDelegate>
|
||||
// UI
|
||||
@property (nonatomic, strong) KBFunctionBarView *barViewInternal;
|
||||
@property (nonatomic, strong) KBFunctionPasteView *pasteViewInternal;
|
||||
@property (nonatomic, strong) UICollectionView *collectionViewInternal;
|
||||
@property (nonatomic, strong) UIView *rightButtonContainer; // 右侧竖排按钮容器
|
||||
@property (nonatomic, strong) UIButton *pasteButtonInternal;
|
||||
@property (nonatomic, strong) UIButton *deleteButtonInternal;
|
||||
@property (nonatomic, strong) UIButton *clearButtonInternal;
|
||||
@property (nonatomic, strong) UIButton *sendButtonInternal;
|
||||
|
||||
// Data
|
||||
@property (nonatomic, strong) NSArray<NSString *> *itemsInternal;
|
||||
|
||||
// 剪贴板自动检测
|
||||
@property (nonatomic, strong) NSTimer *pasteboardTimer; // 轮询定时器(轻量、主线程)
|
||||
@property (nonatomic, assign) NSInteger lastHandledPBCount; // 上次处理过的 changeCount,避免重复弹窗
|
||||
@end
|
||||
|
||||
@implementation KBFunctionView
|
||||
|
||||
- (instancetype)initWithFrame:(CGRect)frame {
|
||||
if (self = [super initWithFrame:frame]) {
|
||||
// 整体绿色背景(接近截图效果,项目可自行替换素材)
|
||||
self.backgroundColor = [UIColor colorWithRed:0.77 green:0.93 blue:0.82 alpha:1.0];
|
||||
|
||||
[self setupUI];
|
||||
[self reloadDemoData];
|
||||
|
||||
// 初始化剪贴板监控状态
|
||||
_lastHandledPBCount = [UIPasteboard generalPasteboard].changeCount;
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)dealloc {
|
||||
[self stopPasteboardMonitor];
|
||||
}
|
||||
|
||||
#pragma mark - UI
|
||||
|
||||
- (void)setupUI {
|
||||
// 1. 顶部 Bar
|
||||
[self addSubview:self.barViewInternal];
|
||||
[self.barViewInternal mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.left.right.equalTo(self);
|
||||
make.top.equalTo(self.mas_top).offset(6);
|
||||
make.height.mas_equalTo(48);
|
||||
}];
|
||||
|
||||
// 右侧竖排按钮容器
|
||||
[self addSubview:self.rightButtonContainer];
|
||||
[self.rightButtonContainer mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.right.equalTo(self.mas_right).offset(-12);
|
||||
make.top.equalTo(self.barViewInternal.mas_bottom).offset(8);
|
||||
make.bottom.equalTo(self.mas_bottom).offset(-10);
|
||||
make.width.mas_equalTo(72);
|
||||
}];
|
||||
|
||||
// 右侧四个按钮
|
||||
[self.rightButtonContainer addSubview:self.pasteButtonInternal];
|
||||
[self.rightButtonContainer addSubview:self.deleteButtonInternal];
|
||||
[self.rightButtonContainer addSubview:self.clearButtonInternal];
|
||||
[self.rightButtonContainer addSubview:self.sendButtonInternal];
|
||||
|
||||
// 竖向排布:粘贴、删除、清空为等高,发送略高
|
||||
CGFloat smallH = 44;
|
||||
CGFloat bigH = 56;
|
||||
CGFloat vSpace = 10;
|
||||
[self.pasteButtonInternal mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.top.equalTo(self.rightButtonContainer.mas_top);
|
||||
make.left.right.equalTo(self.rightButtonContainer);
|
||||
make.height.mas_equalTo(smallH);
|
||||
}];
|
||||
[self.deleteButtonInternal mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.top.equalTo(self.pasteButtonInternal.mas_bottom).offset(vSpace);
|
||||
make.left.right.equalTo(self.rightButtonContainer);
|
||||
make.height.equalTo(self.pasteButtonInternal);
|
||||
}];
|
||||
[self.clearButtonInternal mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.top.equalTo(self.deleteButtonInternal.mas_bottom).offset(vSpace);
|
||||
make.left.right.equalTo(self.rightButtonContainer);
|
||||
make.height.equalTo(self.pasteButtonInternal);
|
||||
}];
|
||||
[self.sendButtonInternal mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.top.equalTo(self.clearButtonInternal.mas_bottom).offset(vSpace);
|
||||
make.left.right.equalTo(self.rightButtonContainer);
|
||||
make.height.mas_equalTo(bigH);
|
||||
make.bottom.lessThanOrEqualTo(self.rightButtonContainer.mas_bottom); // 底部可伸缩
|
||||
}];
|
||||
|
||||
// 2. 粘贴区(位于右侧按钮左侧)
|
||||
[self addSubview:self.pasteViewInternal];
|
||||
[self.pasteViewInternal mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.left.equalTo(self.mas_left).offset(12);
|
||||
make.right.equalTo(self.rightButtonContainer.mas_left).offset(-12);
|
||||
make.top.equalTo(self.barViewInternal.mas_bottom).offset(8);
|
||||
make.height.mas_equalTo(48);
|
||||
}];
|
||||
|
||||
// 3. CollectionView
|
||||
[self addSubview:self.collectionViewInternal];
|
||||
[self.collectionViewInternal mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.left.equalTo(self.mas_left).offset(12);
|
||||
make.right.equalTo(self.rightButtonContainer.mas_left).offset(-12);
|
||||
make.top.equalTo(self.pasteViewInternal.mas_bottom).offset(10);
|
||||
make.bottom.equalTo(self.mas_bottom).offset(-10);
|
||||
}];
|
||||
}
|
||||
|
||||
#pragma mark - Data
|
||||
|
||||
- (void)reloadDemoData {
|
||||
// 演示数据(可由外部替换)
|
||||
self.itemsInternal = @[@"高情商", @"暖味拉扯", @"风趣幽默", @"撩女生", @"社交惬匿", @"情场高手", @"一枚暖男", @"聊天搭子", @"表达爱意", @"更多话术"];
|
||||
[self.collectionViewInternal reloadData];
|
||||
}
|
||||
|
||||
#pragma mark - UICollectionView
|
||||
|
||||
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
|
||||
return self.itemsInternal.count;
|
||||
}
|
||||
|
||||
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
|
||||
KBFunctionTagCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kKBFunctionTagCellId forIndexPath:indexPath];
|
||||
cell.titleLabel.text = self.itemsInternal[indexPath.item];
|
||||
return cell;
|
||||
}
|
||||
|
||||
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
|
||||
// 三列等宽
|
||||
CGFloat totalW = collectionView.bounds.size.width;
|
||||
CGFloat space = 10.0;
|
||||
NSInteger columns = 3;
|
||||
CGFloat width = floor((totalW - space * (columns - 1)) / columns);
|
||||
return CGSizeMake(width, 48);
|
||||
}
|
||||
|
||||
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
|
||||
return 10.0;
|
||||
}
|
||||
|
||||
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
|
||||
return 12.0;
|
||||
}
|
||||
|
||||
// 用户点击功能标签:优先 UL 拉起主App,失败再 Scheme;两次都失败则提示开启完全访问
|
||||
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
|
||||
|
||||
[KBHUD showInfo:@"处理中…"];
|
||||
// return;
|
||||
|
||||
UIInputViewController *ivc = [self findInputViewController];
|
||||
if (!ivc) return;
|
||||
|
||||
NSString *title = (indexPath.item < self.itemsInternal.count) ? self.itemsInternal[indexPath.item] : @"";
|
||||
NSString *encodedTitle = [title stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]] ?: @"";
|
||||
|
||||
NSURL *ul = [NSURL URLWithString:[NSString stringWithFormat:@"%@?src=functionView&index=%ld&title=%@", KB_UL_LOGIN, (long)indexPath.item, encodedTitle]];
|
||||
if (!ul) return;
|
||||
|
||||
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
|
||||
[ivc.extensionContext openURL:ul completionHandler:^(BOOL ok) {
|
||||
if (ok) return; // Universal Link 成功
|
||||
|
||||
NSURL *scheme = [NSURL URLWithString:[NSString stringWithFormat:@"kbkeyboard://login?src=functionView&index=%ld&title=%@", (long)indexPath.item, encodedTitle]];
|
||||
[ivc.extensionContext openURL:scheme completionHandler:^(BOOL ok2) {
|
||||
if (!ok2) {
|
||||
// 两条路都失败:大概率未开完全访问或宿主拦截。统一交由 Manager 引导。
|
||||
dispatch_async(dispatch_get_main_queue(), ^{ [[KBFullAccessManager shared] ensureFullAccessOrGuideInView:self]; });
|
||||
}
|
||||
}];
|
||||
}];
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
#pragma mark - Button Actions
|
||||
|
||||
- (void)onTapPaste {
|
||||
// 用户点击“粘贴”时才读取剪贴板:
|
||||
// - iOS16+ 会在跨 App 首次读取时自动弹出系统权限弹窗;
|
||||
// - iOS15 及以下不会弹窗,直接返回内容;
|
||||
// 注意:不要在非用户触发的时机主动读取(如 viewDidLoad),否则会造成“立刻弹窗”的体验。
|
||||
UIPasteboard *pb = [UIPasteboard generalPasteboard];
|
||||
NSString *text = pb.string; // 读取纯文本(可能触发系统粘贴权限弹窗)
|
||||
|
||||
if (text.length > 0) {
|
||||
// 将粘贴内容展示到左侧“粘贴区”的占位文案上
|
||||
self.pasteView.placeholderLabel.text = text;
|
||||
// 如果需要多行展示,可按需放开(高度由外部约束决定,默认一行会截断)
|
||||
// self.pasteView.placeholderLabel.numberOfLines = 0;
|
||||
} else {
|
||||
// 无可用文本或用户拒绝了粘贴权限;保持占位文案不变
|
||||
NSLog(@"粘贴板无可用文本或未授权粘贴");
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark - 自动监控剪贴板(复制即弹窗)
|
||||
// 说明:
|
||||
// - 仅在视图可见时开启轮询,避免不必要的读取与打扰;
|
||||
// - 当检测到 changeCount 变化,立即读 pasteboard.string:
|
||||
// * iOS16+:此处会触发系统“是否允许粘贴”弹窗;
|
||||
// * iOS15:不会弹窗,直接得到文本;
|
||||
// - 无论允许/拒绝,都把本次 changeCount 记为已处理,避免一直重复询问。
|
||||
|
||||
- (void)startPasteboardMonitor {
|
||||
if (self.pasteboardTimer) return;
|
||||
__weak typeof(self) weakSelf = self;
|
||||
self.pasteboardTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 repeats:YES block:^(NSTimer * _Nonnull timer) {
|
||||
__strong typeof(weakSelf) self = weakSelf; if (!self) return;
|
||||
UIPasteboard *pb = [UIPasteboard generalPasteboard];
|
||||
NSInteger cc = pb.changeCount;
|
||||
if (cc <= self.lastHandledPBCount) return; // 没有新复制
|
||||
self.lastHandledPBCount = cc; // 标记已处理,避免重复
|
||||
|
||||
// 实际读取触发系统弹窗(iOS16+)
|
||||
NSString *text = pb.string;
|
||||
if (text.length > 0) {
|
||||
self.pasteView.placeholderLabel.text = text;
|
||||
}
|
||||
}];
|
||||
}
|
||||
|
||||
- (void)stopPasteboardMonitor {
|
||||
[self.pasteboardTimer invalidate];
|
||||
self.pasteboardTimer = nil;
|
||||
}
|
||||
|
||||
- (void)didMoveToWindow {
|
||||
[super didMoveToWindow];
|
||||
if (self.window && !self.isHidden) {
|
||||
[self startPasteboardMonitor];
|
||||
} else {
|
||||
[self stopPasteboardMonitor];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setHidden:(BOOL)hidden {
|
||||
BOOL wasHidden = self.isHidden;
|
||||
[super setHidden:hidden];
|
||||
if (wasHidden != hidden) {
|
||||
if (!hidden && self.window) {
|
||||
[self startPasteboardMonitor];
|
||||
} else {
|
||||
[self stopPasteboardMonitor];
|
||||
}
|
||||
}
|
||||
}
|
||||
- (void)onTapDelete {
|
||||
NSLog(@"点击:删除");
|
||||
UIInputViewController *ivc = [self findInputViewController];
|
||||
id<UITextDocumentProxy> proxy = ivc.textDocumentProxy;
|
||||
[proxy deleteBackward];
|
||||
}
|
||||
- (void)onTapClear {
|
||||
NSLog(@"点击:清空");
|
||||
// 连续删除:仅清空光标之前的输入(不改动 pasteView 的内容)
|
||||
UIInputViewController *ivc = [self findInputViewController];
|
||||
id<UITextDocumentProxy> proxy = ivc.textDocumentProxy;
|
||||
// 逐批读取 documentContextBeforeInput 并删除,避免 50 字符窗口限制带来的残留
|
||||
NSInteger guard = 0; // 上限保护,避免极端情况下长时间阻塞
|
||||
while (guard < 10000) {
|
||||
NSString *before = proxy.documentContextBeforeInput ?: @"";
|
||||
NSInteger count = before.length;
|
||||
if (count <= 0) { break; } // 光标前已无内容
|
||||
for (NSInteger i = 0; i < count; i++) {
|
||||
[proxy deleteBackward];
|
||||
}
|
||||
guard += count;
|
||||
}
|
||||
}
|
||||
- (void)onTapSend {
|
||||
NSLog(@"点击:发送");
|
||||
// 发送:插入换行。大多数聊天类 App 会把回车视为“发送”
|
||||
UIInputViewController *ivc = [self findInputViewController];
|
||||
id<UITextDocumentProxy> proxy = ivc.textDocumentProxy;
|
||||
[proxy insertText:@"\n"];
|
||||
}
|
||||
|
||||
#pragma mark - Lazy
|
||||
|
||||
- (KBFunctionBarView *)barViewInternal {
|
||||
if (!_barViewInternal) {
|
||||
_barViewInternal = [[KBFunctionBarView alloc] init];
|
||||
_barViewInternal.delegate = self; // 顶部功能Bar事件下发到本View
|
||||
}
|
||||
return _barViewInternal;
|
||||
}
|
||||
|
||||
#pragma mark - KBFunctionBarViewDelegate
|
||||
|
||||
- (void)functionBarView:(KBFunctionBarView *)bar didTapLeftAtIndex:(NSInteger)index {
|
||||
// 将事件继续透传给上层(如键盘控制器),用于切换界面或其它业务
|
||||
if ([self.delegate respondsToSelector:@selector(functionView:didTapToolActionAtIndex:)]) {
|
||||
[self.delegate functionView:self didTapToolActionAtIndex:index];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)functionBarView:(KBFunctionBarView *)bar didTapRightAtIndex:(NSInteger)index {
|
||||
// 右侧按钮点击,如收藏/宫格等,按需继续向外抛出(这里暂不定义单独协议方法,可在此内部处理或扩展)
|
||||
}
|
||||
|
||||
- (KBFunctionPasteView *)pasteViewInternal {
|
||||
if (!_pasteViewInternal) {
|
||||
_pasteViewInternal = [[KBFunctionPasteView alloc] init];
|
||||
}
|
||||
return _pasteViewInternal;
|
||||
}
|
||||
|
||||
- (UICollectionView *)collectionViewInternal {
|
||||
if (!_collectionViewInternal) {
|
||||
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
|
||||
layout.sectionInset = UIEdgeInsetsZero; // 外边距交由约束控制
|
||||
_collectionViewInternal = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
|
||||
_collectionViewInternal.backgroundColor = [UIColor clearColor];
|
||||
_collectionViewInternal.dataSource = self;
|
||||
_collectionViewInternal.delegate = self;
|
||||
[_collectionViewInternal registerClass:[KBFunctionTagCell class] forCellWithReuseIdentifier:kKBFunctionTagCellId];
|
||||
}
|
||||
return _collectionViewInternal;
|
||||
}
|
||||
|
||||
- (UIView *)rightButtonContainer {
|
||||
if (!_rightButtonContainer) {
|
||||
_rightButtonContainer = [[UIView alloc] init];
|
||||
_rightButtonContainer.backgroundColor = [UIColor clearColor];
|
||||
}
|
||||
return _rightButtonContainer;
|
||||
}
|
||||
|
||||
- (UIButton *)buildRightButtonWithTitle:(NSString *)title color:(UIColor *)color {
|
||||
UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
|
||||
btn.backgroundColor = color;
|
||||
btn.layer.cornerRadius = 12.0;
|
||||
btn.layer.masksToBounds = YES;
|
||||
btn.titleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightSemibold];
|
||||
[btn setTitle:title forState:UIControlStateNormal];
|
||||
[btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
|
||||
return btn;
|
||||
}
|
||||
|
||||
- (UIButton *)pasteButtonInternal {
|
||||
if (!_pasteButtonInternal) {
|
||||
_pasteButtonInternal = [self buildRightButtonWithTitle:@"粘贴" color:[UIColor colorWithRed:0.13 green:0.73 blue:0.60 alpha:1.0]];
|
||||
[_pasteButtonInternal addTarget:self action:@selector(onTapPaste) forControlEvents:UIControlEventTouchUpInside];
|
||||
}
|
||||
return _pasteButtonInternal;
|
||||
}
|
||||
|
||||
- (UIButton *)deleteButtonInternal {
|
||||
if (!_deleteButtonInternal) {
|
||||
// 浅灰底深色文字,更接近截图里“删除”样式
|
||||
_deleteButtonInternal = [UIButton buttonWithType:UIButtonTypeSystem];
|
||||
_deleteButtonInternal.backgroundColor = [UIColor colorWithWhite:0.92 alpha:1.0];
|
||||
_deleteButtonInternal.layer.cornerRadius = 12.0;
|
||||
_deleteButtonInternal.layer.masksToBounds = YES;
|
||||
_deleteButtonInternal.titleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightSemibold];
|
||||
[_deleteButtonInternal setTitle:@"删除" forState:UIControlStateNormal];
|
||||
[_deleteButtonInternal setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
|
||||
[_deleteButtonInternal addTarget:self action:@selector(onTapDelete) forControlEvents:UIControlEventTouchUpInside];
|
||||
}
|
||||
return _deleteButtonInternal;
|
||||
}
|
||||
|
||||
- (UIButton *)clearButtonInternal {
|
||||
if (!_clearButtonInternal) {
|
||||
_clearButtonInternal = [UIButton buttonWithType:UIButtonTypeSystem];
|
||||
_clearButtonInternal.backgroundColor = [UIColor colorWithWhite:0.92 alpha:1.0];
|
||||
_clearButtonInternal.layer.cornerRadius = 12.0;
|
||||
_clearButtonInternal.layer.masksToBounds = YES;
|
||||
_clearButtonInternal.titleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightSemibold];
|
||||
[_clearButtonInternal setTitle:@"清空" forState:UIControlStateNormal];
|
||||
[_clearButtonInternal setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
|
||||
[_clearButtonInternal addTarget:self action:@selector(onTapClear) forControlEvents:UIControlEventTouchUpInside];
|
||||
}
|
||||
return _clearButtonInternal;
|
||||
}
|
||||
|
||||
- (UIButton *)sendButtonInternal {
|
||||
if (!_sendButtonInternal) {
|
||||
_sendButtonInternal = [self buildRightButtonWithTitle:@"发送" color:[UIColor colorWithRed:0.13 green:0.73 blue:0.60 alpha:1.0]];
|
||||
[_sendButtonInternal addTarget:self action:@selector(onTapSend) forControlEvents:UIControlEventTouchUpInside];
|
||||
}
|
||||
return _sendButtonInternal;
|
||||
}
|
||||
|
||||
#pragma mark - Expose
|
||||
|
||||
- (UICollectionView *)collectionView { return self.collectionViewInternal; }
|
||||
- (NSArray<NSString *> *)items { return self.itemsInternal; }
|
||||
- (KBFunctionBarView *)barView { return self.barViewInternal; }
|
||||
- (KBFunctionPasteView *)pasteView { return self.pasteViewInternal; }
|
||||
- (UIButton *)pasteButton { return self.pasteButtonInternal; }
|
||||
- (UIButton *)deleteButton { return self.deleteButtonInternal; }
|
||||
- (UIButton *)clearButton { return self.clearButtonInternal; }
|
||||
- (UIButton *)sendButton { return self.sendButtonInternal; }
|
||||
|
||||
#pragma mark - Find Owner Controller
|
||||
|
||||
// 在视图的响应链中查找宿主 UIInputViewController(KeyboardViewController)
|
||||
- (UIInputViewController *)findInputViewController {
|
||||
UIResponder *responder = self;
|
||||
while (responder) {
|
||||
if ([responder isKindOfClass:[UIInputViewController class]]) {
|
||||
return (UIInputViewController *)responder;
|
||||
}
|
||||
responder = responder.nextResponder;
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
@end
|
||||
33
CustomKeyboard/View/KBKeyBoardMainView.h
Normal file
33
CustomKeyboard/View/KBKeyBoardMainView.h
Normal file
@@ -0,0 +1,33 @@
|
||||
//
|
||||
// KBKeyBoardMainView.h
|
||||
// CustomKeyboard
|
||||
//
|
||||
// Created by Mac on 2025/10/28.
|
||||
//
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
|
||||
@class KBKeyBoardMainView, KBKey;
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@protocol KBKeyBoardMainViewDelegate <NSObject>
|
||||
@optional
|
||||
/// 键被点击的回调
|
||||
- (void)keyBoardMainView:(KBKeyBoardMainView *)keyBoardMainView didTapKey:(KBKey *)key;
|
||||
|
||||
/// 顶部工具栏按钮点击回调(index: 0~3)。
|
||||
/// 需求:当 index == 0 时,由外部(KeyboardViewController)决定是否切换到功能面板
|
||||
- (void)keyBoardMainView:(KBKeyBoardMainView *)keyBoardMainView didTapToolActionAtIndex:(NSInteger)index;
|
||||
|
||||
/// 点击了右侧设置按钮
|
||||
- (void)keyBoardMainViewDidTapSettings:(KBKeyBoardMainView *)keyBoardMainView;
|
||||
@end
|
||||
|
||||
@interface KBKeyBoardMainView : UIView
|
||||
@property (nonatomic, weak) id<KBKeyBoardMainViewDelegate> delegate;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
118
CustomKeyboard/View/KBKeyBoardMainView.m
Normal file
118
CustomKeyboard/View/KBKeyBoardMainView.m
Normal file
@@ -0,0 +1,118 @@
|
||||
//
|
||||
// KBKeyBoardMainView.m
|
||||
// CustomKeyboard
|
||||
//
|
||||
// Created by Mac on 2025/10/28.
|
||||
//
|
||||
|
||||
#import "KBKeyBoardMainView.h"
|
||||
#import "KBToolBar.h"
|
||||
#import "KBKeyboardView.h"
|
||||
#import "KBFunctionView.h"
|
||||
#import "KBKey.h"
|
||||
#import "Masonry.h"
|
||||
|
||||
@interface KBKeyBoardMainView ()<KBToolBarDelegate, KBKeyboardViewDelegate>
|
||||
@property (nonatomic, strong) KBToolBar *topBar;
|
||||
@property (nonatomic, strong) KBKeyboardView *keyboardView;
|
||||
// 注意:功能面板的展示/隐藏由外部控制器决定,此处不再直接管理显隐
|
||||
@end
|
||||
@implementation KBKeyBoardMainView
|
||||
|
||||
- (instancetype)initWithFrame:(CGRect)frame {
|
||||
if (self = [super initWithFrame:frame]) {
|
||||
self.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1.0];
|
||||
// 顶部栏
|
||||
self.topBar = [[KBToolBar alloc] init];
|
||||
self.topBar.delegate = self;
|
||||
[self addSubview:self.topBar];
|
||||
[self.topBar mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.left.right.equalTo(self);
|
||||
make.top.equalTo(self.mas_top).offset(6);
|
||||
make.height.mas_equalTo(40);
|
||||
}];
|
||||
|
||||
// 键盘区域
|
||||
self.keyboardView = [[KBKeyboardView alloc] init];
|
||||
self.keyboardView.delegate = self;
|
||||
[self addSubview:self.keyboardView];
|
||||
[self.keyboardView mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.left.right.equalTo(self);
|
||||
make.top.equalTo(self.topBar.mas_bottom).offset(4);
|
||||
make.bottom.equalTo(self.mas_bottom).offset(-4);
|
||||
}];
|
||||
|
||||
// 功能面板切换交由外部控制器处理;此处不直接创建/管理
|
||||
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
|
||||
#pragma mark - KBToolBarDelegate
|
||||
|
||||
- (void)toolBar:(KBToolBar *)toolBar didTapActionAtIndex:(NSInteger)index {
|
||||
// 将事件抛给外部控制器,由其决定是否切换到功能面板
|
||||
if ([self.delegate respondsToSelector:@selector(keyBoardMainView:didTapToolActionAtIndex:)]) {
|
||||
[self.delegate keyBoardMainView:self didTapToolActionAtIndex:index];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)toolBarDidTapSettings:(KBToolBar *)toolBar {
|
||||
if ([self.delegate respondsToSelector:@selector(keyBoardMainViewDidTapSettings:)]) {
|
||||
[self.delegate keyBoardMainViewDidTapSettings:self];
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark - KBKeyboardViewDelegate
|
||||
|
||||
- (void)keyboardView:(KBKeyboardView *)keyboard didTapKey:(KBKey *)key {
|
||||
switch (key.type) {
|
||||
case KBKeyTypeCharacter:
|
||||
// 文本插入交由上层控制器处理
|
||||
if ([self.delegate respondsToSelector:@selector(keyBoardMainView:didTapKey:)]) {
|
||||
[self.delegate keyBoardMainView:self didTapKey:key];
|
||||
}
|
||||
break;
|
||||
case KBKeyTypeBackspace:
|
||||
if ([self.delegate respondsToSelector:@selector(keyBoardMainView:didTapKey:)]) {
|
||||
[self.delegate keyBoardMainView:self didTapKey:key];
|
||||
}
|
||||
break;
|
||||
case KBKeyTypeSpace:
|
||||
if ([self.delegate respondsToSelector:@selector(keyBoardMainView:didTapKey:)]) {
|
||||
[self.delegate keyBoardMainView:self didTapKey:key];
|
||||
}
|
||||
break;
|
||||
case KBKeyTypeReturn:
|
||||
if ([self.delegate respondsToSelector:@selector(keyBoardMainView:didTapKey:)]) {
|
||||
[self.delegate keyBoardMainView:self didTapKey:key];
|
||||
}
|
||||
break;
|
||||
case KBKeyTypeModeChange: {
|
||||
// 切换 字母 <-> 数字 布局
|
||||
keyboard.layoutStyle = (keyboard.layoutStyle == KBKeyboardLayoutStyleLetters) ? KBKeyboardLayoutStyleNumbers : KBKeyboardLayoutStyleLetters;
|
||||
[keyboard reloadKeys];
|
||||
} break;
|
||||
case KBKeyTypeGlobe:
|
||||
if ([self.delegate respondsToSelector:@selector(keyBoardMainView:didTapKey:)]) {
|
||||
[self.delegate keyBoardMainView:self didTapKey:key];
|
||||
}
|
||||
break;
|
||||
case KBKeyTypeCustom:
|
||||
// 自定义占位:切换语言或其它操作
|
||||
if ([self.delegate respondsToSelector:@selector(keyBoardMainView:didTapKey:)]) {
|
||||
[self.delegate keyBoardMainView:self didTapKey:key];
|
||||
}
|
||||
break;
|
||||
case KBKeyTypeShift:
|
||||
// Shift 已在 KBKeyboardView 内部处理
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// 切换功能面板交由外部控制器处理(此处不再实现)
|
||||
|
||||
// 设置页展示改由 KeyboardViewController 统一处理
|
||||
|
||||
@end
|
||||
20
CustomKeyboard/View/KBKeyButton.h
Normal file
20
CustomKeyboard/View/KBKeyButton.h
Normal file
@@ -0,0 +1,20 @@
|
||||
//
|
||||
// KBKeyButton.h
|
||||
// CustomKeyboard
|
||||
//
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
@class KBKey;
|
||||
|
||||
/// 自定义键按钮(UIButton 子类):圆角外观,按下高亮效果。
|
||||
@interface KBKeyButton : UIButton
|
||||
|
||||
@property (nonatomic, strong) KBKey *key;
|
||||
|
||||
/// 配置基础样式(背景、圆角等)。创建按钮时调用。
|
||||
- (void)applyDefaultStyle;
|
||||
|
||||
/// 根据选中/高亮等状态刷新外观
|
||||
- (void)refreshStateAppearance;
|
||||
|
||||
@end
|
||||
56
CustomKeyboard/View/KBKeyButton.m
Normal file
56
CustomKeyboard/View/KBKeyButton.m
Normal file
@@ -0,0 +1,56 @@
|
||||
//
|
||||
// KBKeyButton.m
|
||||
// CustomKeyboard
|
||||
//
|
||||
|
||||
#import "KBKeyButton.h"
|
||||
#import "KBKey.h"
|
||||
|
||||
@implementation KBKeyButton
|
||||
|
||||
- (instancetype)initWithFrame:(CGRect)frame {
|
||||
if (self = [super initWithFrame:frame]) {
|
||||
[self applyDefaultStyle];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)applyDefaultStyle {
|
||||
self.titleLabel.font = [UIFont systemFontOfSize:18 weight:UIFontWeightSemibold]; // 字体样式
|
||||
[self setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
|
||||
[self setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
|
||||
self.backgroundColor = [UIColor whiteColor];
|
||||
self.layer.cornerRadius = 6.0; // 圆角
|
||||
self.layer.masksToBounds = NO;
|
||||
self.layer.shadowColor = [UIColor colorWithWhite:0 alpha:0.1].CGColor; // 阴影效果
|
||||
self.layer.shadowOpacity = 1.0;
|
||||
self.layer.shadowOffset = CGSizeMake(0, 1);
|
||||
self.layer.shadowRadius = 1.5;
|
||||
[self refreshStateAppearance];
|
||||
}
|
||||
|
||||
- (void)setHighlighted:(BOOL)highlighted {
|
||||
[super setHighlighted:highlighted];
|
||||
// 简单按压反馈:选中态不改变透明度,避免和高亮态冲突
|
||||
if (self.isSelected) {
|
||||
self.alpha = 1.0;
|
||||
} else {
|
||||
self.alpha = highlighted ? 0.2 : 1.0;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setSelected:(BOOL)selected {
|
||||
[super setSelected:selected];
|
||||
[self refreshStateAppearance];
|
||||
}
|
||||
|
||||
- (void)refreshStateAppearance {
|
||||
// 选中态用于 Shift/CapsLock 等特殊按键的高亮显示
|
||||
if (self.isSelected) {
|
||||
self.backgroundColor = [UIColor colorWithWhite:0.85 alpha:1.0];
|
||||
} else {
|
||||
self.backgroundColor = [UIColor whiteColor];
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
33
CustomKeyboard/View/KBKeyboardView.h
Normal file
33
CustomKeyboard/View/KBKeyboardView.h
Normal file
@@ -0,0 +1,33 @@
|
||||
//
|
||||
// KBKeyboardView.h
|
||||
// CustomKeyboard
|
||||
//
|
||||
// 键盘主容器,内部管理按键行布局。
|
||||
//
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
@class KBKeyboardView, KBKey;
|
||||
|
||||
typedef NS_ENUM(NSInteger, KBKeyboardLayoutStyle) {
|
||||
KBKeyboardLayoutStyleLetters = 0,
|
||||
KBKeyboardLayoutStyleNumbers
|
||||
};
|
||||
|
||||
@protocol KBKeyboardViewDelegate <NSObject>
|
||||
@optional
|
||||
/// 键被点击的回调
|
||||
- (void)keyboardView:(KBKeyboardView *)keyboard didTapKey:(KBKey *)key;
|
||||
@end
|
||||
|
||||
@interface KBKeyboardView : UIView
|
||||
|
||||
@property (nonatomic, weak) id<KBKeyboardViewDelegate> delegate;
|
||||
@property (nonatomic, assign) KBKeyboardLayoutStyle layoutStyle; // 布局样式(字母/数字)
|
||||
@property (nonatomic, assign, getter=isShiftOn) BOOL shiftOn; // 大小写状态
|
||||
// 在数字布局中,是否显示“更多符号”(#+=)页
|
||||
@property (nonatomic, assign) BOOL symbolsMoreOn;
|
||||
|
||||
- (void)reloadKeys; // 当布局样式/大小写变化时调用
|
||||
|
||||
@end
|
||||
303
CustomKeyboard/View/KBKeyboardView.m
Normal file
303
CustomKeyboard/View/KBKeyboardView.m
Normal file
@@ -0,0 +1,303 @@
|
||||
//
|
||||
// KBKeyboardView.m
|
||||
// CustomKeyboard
|
||||
//
|
||||
|
||||
#import "KBKeyboardView.h"
|
||||
#import "KBKeyButton.h"
|
||||
#import "KBKey.h"
|
||||
|
||||
@interface KBKeyboardView ()
|
||||
@property (nonatomic, strong) UIView *row1;
|
||||
@property (nonatomic, strong) UIView *row2;
|
||||
@property (nonatomic, strong) UIView *row3;
|
||||
@property (nonatomic, strong) UIView *row4;
|
||||
@property (nonatomic, strong) NSArray<NSArray<KBKey *> *> *keysForRows;
|
||||
@end
|
||||
|
||||
@implementation KBKeyboardView
|
||||
|
||||
- (instancetype)initWithFrame:(CGRect)frame {
|
||||
if (self = [super initWithFrame:frame]) {
|
||||
self.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1.0];
|
||||
_layoutStyle = KBKeyboardLayoutStyleLetters;
|
||||
// 默认小写:与需求一致,初始不开启 Shift
|
||||
_shiftOn = NO;
|
||||
_symbolsMoreOn = NO; // 数字面板默认第一页(123)
|
||||
[self buildBase];
|
||||
[self reloadKeys];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
// 当切换大布局(字母/数字)时,重置数字二级页状态
|
||||
- (void)setLayoutStyle:(KBKeyboardLayoutStyle)layoutStyle {
|
||||
_layoutStyle = layoutStyle;
|
||||
if (_layoutStyle != KBKeyboardLayoutStyleNumbers) {
|
||||
_symbolsMoreOn = NO;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)buildBase {
|
||||
[self addSubview:self.row1];
|
||||
[self addSubview:self.row2];
|
||||
[self addSubview:self.row3];
|
||||
[self addSubview:self.row4];
|
||||
|
||||
CGFloat vSpacing = 8;
|
||||
[self.row1 mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.top.equalTo(self.mas_top).offset(8);
|
||||
make.left.right.equalTo(self);
|
||||
make.height.mas_equalTo(44);
|
||||
}];
|
||||
[self.row2 mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.top.equalTo(self.row1.mas_bottom).offset(vSpacing);
|
||||
make.left.right.equalTo(self);
|
||||
make.height.equalTo(self.row1);
|
||||
}];
|
||||
[self.row3 mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.top.equalTo(self.row2.mas_bottom).offset(vSpacing);
|
||||
make.left.right.equalTo(self);
|
||||
make.height.equalTo(self.row1);
|
||||
}];
|
||||
[self.row4 mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.top.equalTo(self.row3.mas_bottom).offset(vSpacing);
|
||||
make.left.right.equalTo(self);
|
||||
make.height.equalTo(self.row1);
|
||||
make.bottom.equalTo(self.mas_bottom).offset(-6);
|
||||
}];
|
||||
}
|
||||
|
||||
- (void)reloadKeys {
|
||||
// 移除旧按钮
|
||||
for (UIView *row in @[self.row1, self.row2, self.row3, self.row4]) {
|
||||
[row.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
|
||||
}
|
||||
|
||||
self.keysForRows = [self buildKeysForCurrentLayout];
|
||||
[self buildRow:self.row1 withKeys:self.keysForRows[0]];
|
||||
// 第二行:字母布局时通过左右等宽占位让整行居中
|
||||
CGFloat row2Spacer = (self.layoutStyle == KBKeyboardLayoutStyleLetters) ? 0.5 : 0.0;
|
||||
[self buildRow:self.row2 withKeys:self.keysForRows[1] edgeSpacerMultiplier:row2Spacer];
|
||||
[self buildRow:self.row3 withKeys:self.keysForRows[2]];
|
||||
[self buildRow:self.row4 withKeys:self.keysForRows[3]];
|
||||
}
|
||||
|
||||
- (NSArray<NSArray<KBKey *> *> *)buildKeysForCurrentLayout {
|
||||
if (self.layoutStyle == KBKeyboardLayoutStyleNumbers) {
|
||||
// 数字/符号布局:3 行主键 + 底部控制行
|
||||
NSArray *r1 = nil;
|
||||
NSArray *r2 = nil;
|
||||
NSArray *r3 = nil;
|
||||
|
||||
if (!self.symbolsMoreOn) {
|
||||
// 数字第一页(123)
|
||||
r1 = @[ [KBKey keyWithTitle:@"1" output:@"1"], [KBKey keyWithTitle:@"2" output:@"2"], [KBKey keyWithTitle:@"3" output:@"3"],
|
||||
[KBKey keyWithTitle:@"4" output:@"4"], [KBKey keyWithTitle:@"5" output:@"5"], [KBKey keyWithTitle:@"6" output:@"6"],
|
||||
[KBKey keyWithTitle:@"7" output:@"7"], [KBKey keyWithTitle:@"8" output:@"8"], [KBKey keyWithTitle:@"9" output:@"9"], [KBKey keyWithTitle:@"0" output:@"0"] ];
|
||||
r2 = @[ [KBKey keyWithTitle:@"-" output:@"-"], [KBKey keyWithTitle:@"/" output:@"/"], [KBKey keyWithTitle:@":" output:@":"],
|
||||
[KBKey keyWithTitle:@";" output:@";"], [KBKey keyWithTitle:@"(" output:@"("], [KBKey keyWithTitle:@")" output:@")"],
|
||||
[KBKey keyWithTitle:@"$" output:@"$"], [KBKey keyWithTitle:@"&" output:@"&"], [KBKey keyWithTitle:@"@" output:@"@"], [KBKey keyWithTitle:@"\"" output:@"\""] ];
|
||||
r3 = @[ [KBKey keyWithTitle:@"#+=" type:KBKeyTypeSymbolsToggle],
|
||||
[KBKey keyWithTitle:@"," output:@","], [KBKey keyWithTitle:@"." output:@"."], [KBKey keyWithTitle:@"?" output:@"?"],
|
||||
[KBKey keyWithTitle:@"!" output:@"!"], [KBKey keyWithTitle:@"'" output:@"'"],
|
||||
[KBKey keyWithTitle:@"⌫" type:KBKeyTypeBackspace] ];
|
||||
} else {
|
||||
// 数字第二页(#+=):前两行替换为更多符号,左下角按钮文案改为“123”
|
||||
r1 = @[ [KBKey keyWithTitle:@"[" output:@"["], [KBKey keyWithTitle:@"]" output:@"]"], [KBKey keyWithTitle:@"{" output:@"{"],
|
||||
[KBKey keyWithTitle:@"}" output:@"}"], [KBKey keyWithTitle:@"#" output:@"#"], [KBKey keyWithTitle:@"%" output:@"%"],
|
||||
[KBKey keyWithTitle:@"^" output:@"^"], [KBKey keyWithTitle:@"*" output:@"*"], [KBKey keyWithTitle:@"+" output:@"+"],
|
||||
[KBKey keyWithTitle:@"=" output:@"="] ];
|
||||
r2 = @[ [KBKey keyWithTitle:@"_" output:@"_"], [KBKey keyWithTitle:@"\\" output:@"\\"], [KBKey keyWithTitle:@"|" output:@"|"],
|
||||
[KBKey keyWithTitle:@"~" output:@"~"], [KBKey keyWithTitle:@"<" output:@"<"], [KBKey keyWithTitle:@">" output:@">"],
|
||||
[KBKey keyWithTitle:@"$" output:@"$"], [KBKey keyWithTitle:@"€" output:@"€"], [KBKey keyWithTitle:@"£" output:@"£"],
|
||||
[KBKey keyWithTitle:@"•" output:@"•"] ];
|
||||
r3 = @[ [KBKey keyWithTitle:@"123" type:KBKeyTypeSymbolsToggle],
|
||||
[KBKey keyWithTitle:@"," output:@","], [KBKey keyWithTitle:@"." output:@"."], [KBKey keyWithTitle:@"?" output:@"?"],
|
||||
[KBKey keyWithTitle:@"!" output:@"!"], [KBKey keyWithTitle:@"'" output:@"'"],
|
||||
[KBKey keyWithTitle:@"⌫" type:KBKeyTypeBackspace] ];
|
||||
}
|
||||
|
||||
NSArray *r4 = @[ [KBKey keyWithTitle:@"abc" type:KBKeyTypeModeChange],
|
||||
[KBKey keyWithTitle:@"AI" type:KBKeyTypeCustom],
|
||||
[KBKey keyWithTitle:@"space" type:KBKeyTypeSpace],
|
||||
[KBKey keyWithTitle:@"发送" type:KBKeyTypeReturn] ];
|
||||
|
||||
return @[r1, r2, r3, r4];
|
||||
}
|
||||
|
||||
// 字母布局(QWERTY)
|
||||
NSArray *r1 = @[ @"Q", @"W", @"E", @"R", @"T", @"Y", @"U", @"I", @"O", @"P" ];
|
||||
NSArray *r2 = @[ @"A", @"S", @"D", @"F", @"G", @"H", @"J", @"K", @"L" ];
|
||||
NSArray *r3chars = @[ @"Z", @"X", @"C", @"V", @"B", @"N", @"M" ];
|
||||
|
||||
NSMutableArray *row1 = [NSMutableArray arrayWithCapacity:r1.count];
|
||||
// 字母键标题与输出同时随 Shift 切换大小写,界面与输入保持一致
|
||||
for (NSString *s in r1) {
|
||||
NSString *shown = self.shiftOn ? s : s.lowercaseString;
|
||||
[row1 addObject:[KBKey keyWithTitle:shown output:shown]];
|
||||
}
|
||||
|
||||
NSMutableArray *row2 = [NSMutableArray arrayWithCapacity:r2.count];
|
||||
for (NSString *s in r2) {
|
||||
NSString *shown = self.shiftOn ? s : s.lowercaseString;
|
||||
[row2 addObject:[KBKey keyWithTitle:shown output:shown]];
|
||||
}
|
||||
|
||||
NSMutableArray *row3 = [NSMutableArray array];
|
||||
[row3 addObject:[KBKey keyWithTitle:@"⇧" type:KBKeyTypeShift]];
|
||||
for (NSString *s in r3chars) {
|
||||
NSString *shown = self.shiftOn ? s : s.lowercaseString;
|
||||
[row3 addObject:[KBKey keyWithTitle:shown output:shown]];
|
||||
}
|
||||
[row3 addObject:[KBKey keyWithTitle:@"⌫" type:KBKeyTypeBackspace]];
|
||||
|
||||
NSArray *row4 = @[ [KBKey keyWithTitle:@"123" type:KBKeyTypeModeChange],
|
||||
[KBKey keyWithTitle:@"AI" type:KBKeyTypeCustom],
|
||||
[KBKey keyWithTitle:@"space" type:KBKeyTypeSpace],
|
||||
[KBKey keyWithTitle:@"发送" type:KBKeyTypeReturn] ];
|
||||
|
||||
return @[row1.copy, row2.copy, row3.copy, row4];
|
||||
}
|
||||
|
||||
- (void)buildRow:(UIView *)row withKeys:(NSArray<KBKey *> *)keys {
|
||||
[self buildRow:row withKeys:keys edgeSpacerMultiplier:0.0];
|
||||
}
|
||||
|
||||
- (void)buildRow:(UIView *)row withKeys:(NSArray<KBKey *> *)keys edgeSpacerMultiplier:(CGFloat)edgeSpacerMultiplier {
|
||||
CGFloat hInset = 6; // 行左右内边距
|
||||
CGFloat spacing = 6; // 键与键之间的间距
|
||||
UIView *previous = nil;
|
||||
UIView *leftSpacer = nil;
|
||||
UIView *rightSpacer = nil;
|
||||
if (edgeSpacerMultiplier > 0.0) {
|
||||
leftSpacer = [UIView new];
|
||||
rightSpacer = [UIView new];
|
||||
leftSpacer.backgroundColor = [UIColor clearColor];
|
||||
rightSpacer.backgroundColor = [UIColor clearColor];
|
||||
[row addSubview:leftSpacer];
|
||||
[row addSubview:rightSpacer];
|
||||
[leftSpacer mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.left.equalTo(row.mas_left).offset(hInset);
|
||||
make.centerY.equalTo(row);
|
||||
make.height.mas_equalTo(1);
|
||||
}];
|
||||
[rightSpacer mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.right.equalTo(row.mas_right).offset(-hInset);
|
||||
make.centerY.equalTo(row);
|
||||
make.height.mas_equalTo(1);
|
||||
}];
|
||||
}
|
||||
for (NSInteger i = 0; i < keys.count; i++) {
|
||||
KBKey *key = keys[i];
|
||||
KBKeyButton *btn = [[KBKeyButton alloc] init];
|
||||
btn.key = key;
|
||||
[btn setTitle:key.title forState:UIControlStateNormal];
|
||||
[btn addTarget:self action:@selector(onKeyTapped:) forControlEvents:UIControlEventTouchUpInside];
|
||||
[row addSubview:btn];
|
||||
|
||||
// Shift 按钮选中态随大小写状态变化
|
||||
if (key.type == KBKeyTypeShift) {
|
||||
btn.selected = self.shiftOn;
|
||||
}
|
||||
|
||||
[btn mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.top.bottom.equalTo(row);
|
||||
if (previous) {
|
||||
make.left.equalTo(previous.mas_right).offset(spacing);
|
||||
} else {
|
||||
if (leftSpacer) {
|
||||
make.left.equalTo(leftSpacer.mas_right).offset(spacing);
|
||||
} else {
|
||||
make.left.equalTo(row.mas_left).offset(hInset);
|
||||
}
|
||||
}
|
||||
}];
|
||||
|
||||
// 宽度规则:字符键等宽;特殊键按倍数放大
|
||||
if (key.type == KBKeyTypeCharacter) {
|
||||
if (previous && previous != nil) {
|
||||
if (((KBKeyButton *)previous).key.type == KBKeyTypeCharacter) {
|
||||
[btn mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.width.equalTo(previous);
|
||||
}];
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// special keys: give 1.5x of a character key by deferring constraint equalities after loop
|
||||
}
|
||||
|
||||
previous = btn;
|
||||
}
|
||||
// 右侧使用内边距或右占位
|
||||
[previous mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
if (rightSpacer) {
|
||||
make.right.equalTo(rightSpacer.mas_left).offset(-spacing);
|
||||
} else {
|
||||
make.right.equalTo(row.mas_right).offset(-hInset);
|
||||
}
|
||||
}];
|
||||
|
||||
// 第二遍:以首个字符键为基准,统一设置特殊键宽度倍数
|
||||
KBKeyButton *firstChar = nil;
|
||||
for (KBKeyButton *b in row.subviews) {
|
||||
if ([b isKindOfClass:[KBKeyButton class]] && b.key.type == KBKeyTypeCharacter) { firstChar = b; break; }
|
||||
}
|
||||
// 若该行没有字符键(例如底部控制行),则使用行内第一个按钮作为基准宽度
|
||||
if (!firstChar) {
|
||||
for (KBKeyButton *b in row.subviews) { if ([b isKindOfClass:[KBKeyButton class]]) { firstChar = b; break; } }
|
||||
}
|
||||
if (firstChar) {
|
||||
for (KBKeyButton *b in row.subviews) {
|
||||
if (![b isKindOfClass:[KBKeyButton class]]) continue;
|
||||
if (b.key.type == KBKeyTypeCharacter) continue;
|
||||
CGFloat multiplier = 1.5;
|
||||
if (b.key.type == KBKeyTypeSpace) multiplier = 4.0;
|
||||
if (b.key.type == KBKeyTypeReturn) multiplier = 1.8;
|
||||
if (b.key.type == KBKeyTypeModeChange || b.key.type == KBKeyTypeGlobe || b.key.type == KBKeyTypeShift || b.key.type == KBKeyTypeBackspace) {
|
||||
multiplier = 1.5;
|
||||
}
|
||||
[b mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.width.equalTo(firstChar).multipliedBy(multiplier);
|
||||
}];
|
||||
}
|
||||
// 如果有左右占位,则把占位宽度设置为字符键宽度的一定倍数,以实现整体居中
|
||||
if (leftSpacer && rightSpacer) {
|
||||
[leftSpacer mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.width.equalTo(firstChar).multipliedBy(edgeSpacerMultiplier);
|
||||
}];
|
||||
[rightSpacer mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.width.equalTo(firstChar).multipliedBy(edgeSpacerMultiplier);
|
||||
}];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark - Actions
|
||||
|
||||
- (void)onKeyTapped:(KBKeyButton *)sender {
|
||||
KBKey *key = sender.key;
|
||||
if (key.type == KBKeyTypeShift) {
|
||||
self.shiftOn = !self.shiftOn;
|
||||
[self reloadKeys];
|
||||
return;
|
||||
}
|
||||
if (key.type == KBKeyTypeSymbolsToggle) {
|
||||
// 在数字布局内切换 123 <-> #+=
|
||||
self.symbolsMoreOn = !self.symbolsMoreOn;
|
||||
[self reloadKeys];
|
||||
return;
|
||||
}
|
||||
if ([self.delegate respondsToSelector:@selector(keyboardView:didTapKey:)]) {
|
||||
[self.delegate keyboardView:self didTapKey:key];
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark - Lazy
|
||||
|
||||
- (UIView *)row1 { if (!_row1) _row1 = [UIView new]; return _row1; }
|
||||
- (UIView *)row2 { if (!_row2) _row2 = [UIView new]; return _row2; }
|
||||
- (UIView *)row3 { if (!_row3) _row3 = [UIView new]; return _row3; }
|
||||
- (UIView *)row4 { if (!_row4) _row4 = [UIView new]; return _row4; }
|
||||
|
||||
@end
|
||||
20
CustomKeyboard/View/KBSettingView.h
Normal file
20
CustomKeyboard/View/KBSettingView.h
Normal file
@@ -0,0 +1,20 @@
|
||||
//
|
||||
// KBSettingView.h
|
||||
// CustomKeyboard
|
||||
//
|
||||
// 简单的设置页面:左上角返回箭头按钮 + 占位内容区域。
|
||||
//
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface KBSettingView : UIView
|
||||
|
||||
/// 左上角返回按钮(外部添加 target 实现返回)
|
||||
@property (nonatomic, strong, readonly) UIButton *backButton;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
71
CustomKeyboard/View/KBSettingView.m
Normal file
71
CustomKeyboard/View/KBSettingView.m
Normal file
@@ -0,0 +1,71 @@
|
||||
//
|
||||
// KBSettingView.m
|
||||
// CustomKeyboard
|
||||
//
|
||||
|
||||
#import "KBSettingView.h"
|
||||
#import "Masonry.h"
|
||||
|
||||
@interface KBSettingView ()
|
||||
@property (nonatomic, strong) UIButton *backButtonInternal;
|
||||
@property (nonatomic, strong) UILabel *titleLabel;
|
||||
@end
|
||||
|
||||
@implementation KBSettingView
|
||||
|
||||
- (instancetype)initWithFrame:(CGRect)frame {
|
||||
if (self = [super initWithFrame:frame]) {
|
||||
// 背景做成淡色,和主界面区分
|
||||
self.backgroundColor = [UIColor colorWithWhite:1 alpha:0.96];
|
||||
|
||||
[self addSubview:self.backButtonInternal];
|
||||
[self.backButtonInternal mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.left.equalTo(self.mas_left).offset(10);
|
||||
make.top.equalTo(self.mas_top).offset(8);
|
||||
make.width.height.mas_equalTo(32);
|
||||
}];
|
||||
|
||||
self.titleLabel = [[UILabel alloc] init];
|
||||
self.titleLabel.text = @"设置";
|
||||
self.titleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightSemibold];
|
||||
self.titleLabel.textColor = [UIColor blackColor];
|
||||
[self addSubview:self.titleLabel];
|
||||
[self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.centerY.equalTo(self.backButtonInternal.mas_centerY);
|
||||
make.centerX.equalTo(self.mas_centerX);
|
||||
}];
|
||||
|
||||
// 占位内容
|
||||
UILabel *place = [[UILabel alloc] init];
|
||||
place.text = @"这里是设置内容占位";
|
||||
place.textColor = [UIColor darkGrayColor];
|
||||
place.font = [UIFont systemFontOfSize:14];
|
||||
[self addSubview:place];
|
||||
[place mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.center.equalTo(self);
|
||||
}];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
#pragma mark - Lazy
|
||||
|
||||
- (UIButton *)backButtonInternal {
|
||||
if (!_backButtonInternal) {
|
||||
_backButtonInternal = [UIButton buttonWithType:UIButtonTypeSystem];
|
||||
_backButtonInternal.layer.cornerRadius = 16;
|
||||
_backButtonInternal.layer.masksToBounds = YES;
|
||||
_backButtonInternal.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1.0];
|
||||
[_backButtonInternal setTitle:@"←" forState:UIControlStateNormal]; // 返回箭头
|
||||
[_backButtonInternal setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
|
||||
_backButtonInternal.titleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightSemibold];
|
||||
}
|
||||
return _backButtonInternal;
|
||||
}
|
||||
|
||||
#pragma mark - Expose
|
||||
|
||||
- (UIButton *)backButton { return self.backButtonInternal; }
|
||||
|
||||
@end
|
||||
|
||||
36
CustomKeyboard/View/KBToolBar.h
Normal file
36
CustomKeyboard/View/KBToolBar.h
Normal file
@@ -0,0 +1,36 @@
|
||||
//
|
||||
// KBToolBar.h
|
||||
// CustomKeyboard
|
||||
//
|
||||
// Created by Mac on 2025/10/28.
|
||||
//
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@class KBToolBar;
|
||||
|
||||
@protocol KBToolBarDelegate <NSObject>
|
||||
@optional
|
||||
/// 左侧 4 个功能按钮点击(index: 0~3)
|
||||
- (void)toolBar:(KBToolBar *)toolBar didTapActionAtIndex:(NSInteger)index;
|
||||
/// 右侧设置按钮点击
|
||||
- (void)toolBarDidTapSettings:(KBToolBar *)toolBar;
|
||||
@end
|
||||
|
||||
/// 顶部工具栏:左侧 4 个按钮,右侧 1 个设置按钮。
|
||||
@interface KBToolBar : UIView
|
||||
|
||||
@property (nonatomic, weak, nullable) id<KBToolBarDelegate> delegate;
|
||||
|
||||
/// 左侧 4 个按钮的标题。默认值:@[@"Item1", @"Item2", @"Item3", @"Item4"]。
|
||||
@property (nonatomic, copy) NSArray<NSString *> *leftButtonTitles;
|
||||
|
||||
/// 暴露按钮以便外部定制(只读;首次访问时懒加载创建)
|
||||
@property (nonatomic, strong, readonly) NSArray<UIButton *> *leftButtons;
|
||||
@property (nonatomic, strong, readonly) UIButton *settingsButton;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
145
CustomKeyboard/View/KBToolBar.m
Normal file
145
CustomKeyboard/View/KBToolBar.m
Normal file
@@ -0,0 +1,145 @@
|
||||
//
|
||||
// KBToolBar.m
|
||||
// CustomKeyboard
|
||||
//
|
||||
// Created by Mac on 2025/10/28.
|
||||
//
|
||||
|
||||
#import "KBToolBar.h"
|
||||
|
||||
@interface KBToolBar ()
|
||||
@property (nonatomic, strong) UIView *leftContainer;
|
||||
@property (nonatomic, strong) NSArray<UIButton *> *leftButtonsInternal;
|
||||
@property (nonatomic, strong) UIButton *settingsButtonInternal;
|
||||
@end
|
||||
|
||||
@implementation KBToolBar
|
||||
|
||||
- (instancetype)initWithFrame:(CGRect)frame{
|
||||
if (self = [super initWithFrame:frame]) {
|
||||
self.backgroundColor = [UIColor clearColor];
|
||||
_leftButtonTitles = @[@"Item1", @"Item2", @"Item3", @"Item4"]; // 默认标题
|
||||
[self setupUI];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
|
||||
#pragma mark - Public
|
||||
|
||||
- (NSArray<UIButton *> *)leftButtons {
|
||||
return self.leftButtonsInternal;
|
||||
}
|
||||
|
||||
- (UIButton *)settingsButton {
|
||||
return self.settingsButtonInternal;
|
||||
}
|
||||
|
||||
- (void)setLeftButtonTitles:(NSArray<NSString *> *)leftButtonTitles {
|
||||
_leftButtonTitles = [leftButtonTitles copy];
|
||||
// Update titles if buttons already exist
|
||||
[self.leftButtonsInternal enumerateObjectsUsingBlock:^(UIButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
|
||||
if (idx < self.leftButtonTitles.count) {
|
||||
[obj setTitle:self.leftButtonTitles[idx] forState:UIControlStateNormal];
|
||||
}
|
||||
}];
|
||||
}
|
||||
|
||||
#pragma mark - 视图搭建
|
||||
|
||||
- (void)setupUI {
|
||||
[self addSubview:self.leftContainer];
|
||||
[self addSubview:self.settingsButtonInternal];
|
||||
|
||||
// 右侧设置按钮
|
||||
[self.settingsButtonInternal mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.right.equalTo(self.mas_right).offset(-12);
|
||||
make.centerY.equalTo(self.mas_centerY);
|
||||
make.width.height.mas_equalTo(32);
|
||||
}];
|
||||
|
||||
// 左侧容器占用剩余空间
|
||||
[self.leftContainer mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.left.equalTo(self.mas_left).offset(12);
|
||||
make.right.equalTo(self.settingsButtonInternal.mas_left).offset(-12);
|
||||
make.centerY.equalTo(self.mas_centerY);
|
||||
make.height.mas_equalTo(32);
|
||||
}];
|
||||
|
||||
// 在左侧容器中创建 4 个等宽按钮
|
||||
NSMutableArray<UIButton *> *buttons = [NSMutableArray arrayWithCapacity:4];
|
||||
UIView *previous = nil;
|
||||
for (NSInteger i = 0; i < 4; i++) {
|
||||
UIButton *btn = [self buildActionButtonAtIndex:i];
|
||||
[self.leftContainer addSubview:btn];
|
||||
[buttons addObject:btn];
|
||||
[btn mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
if (previous) {
|
||||
make.left.equalTo(previous.mas_right).offset(8);
|
||||
make.width.equalTo(previous);
|
||||
} else {
|
||||
make.left.equalTo(self.leftContainer.mas_left);
|
||||
}
|
||||
make.top.bottom.equalTo(self.leftContainer);
|
||||
}];
|
||||
previous = btn;
|
||||
}
|
||||
// 最后一个按钮贴右侧
|
||||
[previous mas_makeConstraints:^(MASConstraintMaker *make) {
|
||||
make.right.equalTo(self.leftContainer.mas_right);
|
||||
}];
|
||||
self.leftButtonsInternal = buttons.copy;
|
||||
}
|
||||
|
||||
- (UIButton *)buildActionButtonAtIndex:(NSInteger)idx {
|
||||
UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
|
||||
btn.layer.cornerRadius = 16;
|
||||
btn.layer.masksToBounds = YES;
|
||||
btn.backgroundColor = [UIColor colorWithWhite:1 alpha:0.9];
|
||||
btn.titleLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightMedium];
|
||||
NSString *title = (idx < self.leftButtonTitles.count) ? self.leftButtonTitles[idx] : [NSString stringWithFormat:@"Item%ld", (long)(idx+1)];
|
||||
[btn setTitle:title forState:UIControlStateNormal];
|
||||
[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
|
||||
btn.tag = idx;
|
||||
[btn addTarget:self action:@selector(onLeftAction:) forControlEvents:UIControlEventTouchUpInside];
|
||||
return btn;
|
||||
}
|
||||
|
||||
#pragma mark - Actions
|
||||
|
||||
- (void)onLeftAction:(UIButton *)sender {
|
||||
if ([self.delegate respondsToSelector:@selector(toolBar:didTapActionAtIndex:)]) {
|
||||
[self.delegate toolBar:self didTapActionAtIndex:sender.tag];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)onSettings {
|
||||
if ([self.delegate respondsToSelector:@selector(toolBarDidTapSettings:)]) {
|
||||
[self.delegate toolBarDidTapSettings:self];
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark - Lazy
|
||||
|
||||
- (UIView *)leftContainer {
|
||||
if (!_leftContainer) {
|
||||
_leftContainer = [[UIView alloc] init];
|
||||
_leftContainer.backgroundColor = [UIColor clearColor];
|
||||
}
|
||||
return _leftContainer;
|
||||
}
|
||||
|
||||
- (UIButton *)settingsButtonInternal {
|
||||
if (!_settingsButtonInternal) {
|
||||
_settingsButtonInternal = [UIButton buttonWithType:UIButtonTypeSystem];
|
||||
_settingsButtonInternal.layer.cornerRadius = 16;
|
||||
_settingsButtonInternal.layer.masksToBounds = YES;
|
||||
_settingsButtonInternal.backgroundColor = [UIColor colorWithWhite:1 alpha:0.9];
|
||||
[_settingsButtonInternal setTitle:@"⚙︎" forState:UIControlStateNormal]; // 简单的齿轮符号
|
||||
[_settingsButtonInternal setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
|
||||
[_settingsButtonInternal addTarget:self action:@selector(onSettings) forControlEvents:UIControlEventTouchUpInside];
|
||||
}
|
||||
return _settingsButtonInternal;
|
||||
}
|
||||
|
||||
@end
|
||||
33
Podfile
Normal file
33
Podfile
Normal file
@@ -0,0 +1,33 @@
|
||||
# Uncomment the next line to define a global platform for your project
|
||||
source 'https://github.com/CocoaPods/Specs.git'
|
||||
platform :ios, '13.0'
|
||||
|
||||
target 'keyBoard' do
|
||||
# Comment the next line if you don't want to use dynamic frameworks
|
||||
use_frameworks!
|
||||
|
||||
pod 'AFNetworking','4.0.1'
|
||||
pod 'Bugly', :configurations => ['Release']
|
||||
pod 'Masonry', '1.1.0'
|
||||
pod 'MBProgressHUD', '1.2.0'
|
||||
pod 'MJExtension', '3.4.2'
|
||||
pod 'MJRefresh', '3.7.9'
|
||||
pod 'SDWebImage', '5.21.1'
|
||||
pod 'DZNEmptyDataSet', '1.8.1'
|
||||
pod 'lottie-ios', :git => 'https://github.com/airbnb/lottie-ios.git', :branch => 'lottie/objectiveC'
|
||||
pod 'LookinServer', :configurations => ['Debug']
|
||||
end
|
||||
|
||||
target 'CustomKeyboard' do
|
||||
# Comment the next line if you don't want to use dynamic frameworks
|
||||
use_frameworks!
|
||||
|
||||
pod 'AFNetworking','4.0.1'
|
||||
|
||||
pod 'Masonry', '1.1.0'
|
||||
pod 'MBProgressHUD', '1.2.0'
|
||||
pod 'MJExtension', '3.4.2'
|
||||
pod 'DZNEmptyDataSet', '1.8.1'
|
||||
end
|
||||
|
||||
|
||||
79
Podfile.lock
Normal file
79
Podfile.lock
Normal file
@@ -0,0 +1,79 @@
|
||||
PODS:
|
||||
- AFNetworking (4.0.1):
|
||||
- AFNetworking/NSURLSession (= 4.0.1)
|
||||
- AFNetworking/Reachability (= 4.0.1)
|
||||
- AFNetworking/Security (= 4.0.1)
|
||||
- AFNetworking/Serialization (= 4.0.1)
|
||||
- AFNetworking/UIKit (= 4.0.1)
|
||||
- AFNetworking/NSURLSession (4.0.1):
|
||||
- AFNetworking/Reachability
|
||||
- AFNetworking/Security
|
||||
- AFNetworking/Serialization
|
||||
- AFNetworking/Reachability (4.0.1)
|
||||
- AFNetworking/Security (4.0.1)
|
||||
- AFNetworking/Serialization (4.0.1)
|
||||
- AFNetworking/UIKit (4.0.1):
|
||||
- AFNetworking/NSURLSession
|
||||
- Bugly (2.6.1)
|
||||
- DZNEmptyDataSet (1.8.1)
|
||||
- LookinServer (1.2.8):
|
||||
- LookinServer/Core (= 1.2.8)
|
||||
- LookinServer/Core (1.2.8)
|
||||
- lottie-ios (2.5.3)
|
||||
- Masonry (1.1.0)
|
||||
- MBProgressHUD (1.2.0)
|
||||
- MJExtension (3.4.2)
|
||||
- MJRefresh (3.7.9)
|
||||
- SDWebImage (5.21.1):
|
||||
- SDWebImage/Core (= 5.21.1)
|
||||
- SDWebImage/Core (5.21.1)
|
||||
|
||||
DEPENDENCIES:
|
||||
- AFNetworking (= 4.0.1)
|
||||
- Bugly
|
||||
- DZNEmptyDataSet (= 1.8.1)
|
||||
- LookinServer
|
||||
- lottie-ios (from `https://github.com/airbnb/lottie-ios.git`, branch `lottie/objectiveC`)
|
||||
- Masonry (= 1.1.0)
|
||||
- MBProgressHUD (= 1.2.0)
|
||||
- MJExtension (= 3.4.2)
|
||||
- MJRefresh (= 3.7.9)
|
||||
- SDWebImage (= 5.21.1)
|
||||
|
||||
SPEC REPOS:
|
||||
https://github.com/CocoaPods/Specs.git:
|
||||
- AFNetworking
|
||||
- Bugly
|
||||
- DZNEmptyDataSet
|
||||
- LookinServer
|
||||
- Masonry
|
||||
- MBProgressHUD
|
||||
- MJExtension
|
||||
- MJRefresh
|
||||
- SDWebImage
|
||||
|
||||
EXTERNAL SOURCES:
|
||||
lottie-ios:
|
||||
:branch: lottie/objectiveC
|
||||
:git: https://github.com/airbnb/lottie-ios.git
|
||||
|
||||
CHECKOUT OPTIONS:
|
||||
lottie-ios:
|
||||
:commit: e44ed5a2a0bffa588933e0ca1bd1f0171ffaa096
|
||||
:git: https://github.com/airbnb/lottie-ios.git
|
||||
|
||||
SPEC CHECKSUMS:
|
||||
AFNetworking: 3bd23d814e976cd148d7d44c3ab78017b744cd58
|
||||
Bugly: 217ac2ce5f0f2626d43dbaa4f70764c953a26a31
|
||||
DZNEmptyDataSet: 9525833b9e68ac21c30253e1d3d7076cc828eaa7
|
||||
LookinServer: 1b2b61c6402ae29fa22182d48f5cd067b4e99e80
|
||||
lottie-ios: b8e2ada09dfff3d1ad5df18d27e1adb7e690680d
|
||||
Masonry: 678fab65091a9290e40e2832a55e7ab731aad201
|
||||
MBProgressHUD: 3ee5efcc380f6a79a7cc9b363dd669c5e1ae7406
|
||||
MJExtension: e97d164cb411aa9795cf576093a1fa208b4a8dd8
|
||||
MJRefresh: ff9e531227924c84ce459338414550a05d2aea78
|
||||
SDWebImage: f29024626962457f3470184232766516dee8dfea
|
||||
|
||||
PODFILE CHECKSUM: 049030aa18b7c16780ea2521136c0b79261ff26b
|
||||
|
||||
COCOAPODS: 1.16.2
|
||||
49
Pods/AFNetworking/AFNetworking/AFCompatibilityMacros.h
generated
Normal file
49
Pods/AFNetworking/AFNetworking/AFCompatibilityMacros.h
generated
Normal file
@@ -0,0 +1,49 @@
|
||||
// AFCompatibilityMacros.h
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#ifndef AFCompatibilityMacros_h
|
||||
#define AFCompatibilityMacros_h
|
||||
|
||||
#ifdef API_AVAILABLE
|
||||
#define AF_API_AVAILABLE(...) API_AVAILABLE(__VA_ARGS__)
|
||||
#else
|
||||
#define AF_API_AVAILABLE(...)
|
||||
#endif // API_AVAILABLE
|
||||
|
||||
#ifdef API_UNAVAILABLE
|
||||
#define AF_API_UNAVAILABLE(...) API_UNAVAILABLE(__VA_ARGS__)
|
||||
#else
|
||||
#define AF_API_UNAVAILABLE(...)
|
||||
#endif // API_UNAVAILABLE
|
||||
|
||||
#if __has_warning("-Wunguarded-availability-new")
|
||||
#define AF_CAN_USE_AT_AVAILABLE 1
|
||||
#else
|
||||
#define AF_CAN_USE_AT_AVAILABLE 0
|
||||
#endif
|
||||
|
||||
#if ((__IPHONE_OS_VERSION_MAX_ALLOWED && __IPHONE_OS_VERSION_MAX_ALLOWED < 100000) || (__MAC_OS_VERSION_MAX_ALLOWED && __MAC_OS_VERSION_MAX_ALLOWED < 101200) ||(__WATCH_OS_MAX_VERSION_ALLOWED && __WATCH_OS_MAX_VERSION_ALLOWED < 30000) ||(__TV_OS_MAX_VERSION_ALLOWED && __TV_OS_MAX_VERSION_ALLOWED < 100000))
|
||||
#define AF_CAN_INCLUDE_SESSION_TASK_METRICS 0
|
||||
#else
|
||||
#define AF_CAN_INCLUDE_SESSION_TASK_METRICS 1
|
||||
#endif
|
||||
|
||||
#endif /* AFCompatibilityMacros_h */
|
||||
285
Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.h
generated
Normal file
285
Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.h
generated
Normal file
@@ -0,0 +1,285 @@
|
||||
// AFHTTPSessionManager.h
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#if !TARGET_OS_WATCH
|
||||
#import <SystemConfiguration/SystemConfiguration.h>
|
||||
#endif
|
||||
#import <TargetConditionals.h>
|
||||
|
||||
#import "AFURLSessionManager.h"
|
||||
|
||||
/**
|
||||
`AFHTTPSessionManager` is a subclass of `AFURLSessionManager` with convenience methods for making HTTP requests. When a `baseURL` is provided, requests made with the `GET` / `POST` / et al. convenience methods can be made with relative paths.
|
||||
|
||||
## Subclassing Notes
|
||||
|
||||
Developers targeting iOS 7 or Mac OS X 10.9 or later that deal extensively with a web service are encouraged to subclass `AFHTTPSessionManager`, providing a class method that returns a shared singleton object on which authentication and other configuration can be shared across the application.
|
||||
|
||||
## Methods to Override
|
||||
|
||||
To change the behavior of all data task operation construction, which is also used in the `GET` / `POST` / et al. convenience methods, override `dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:`.
|
||||
|
||||
## Serialization
|
||||
|
||||
Requests created by an HTTP client will contain default headers and encode parameters according to the `requestSerializer` property, which is an object conforming to `<AFURLRequestSerialization>`.
|
||||
|
||||
Responses received from the server are automatically validated and serialized by the `responseSerializers` property, which is an object conforming to `<AFURLResponseSerialization>`
|
||||
|
||||
## URL Construction Using Relative Paths
|
||||
|
||||
For HTTP convenience methods, the request serializer constructs URLs from the path relative to the `-baseURL`, using `NSURL +URLWithString:relativeToURL:`, when provided. If `baseURL` is `nil`, `path` needs to resolve to a valid `NSURL` object using `NSURL +URLWithString:`.
|
||||
|
||||
Below are a few examples of how `baseURL` and relative paths interact:
|
||||
|
||||
NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"];
|
||||
[NSURL URLWithString:@"foo" relativeToURL:baseURL]; // http://example.com/v1/foo
|
||||
[NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL]; // http://example.com/v1/foo?bar=baz
|
||||
[NSURL URLWithString:@"/foo" relativeToURL:baseURL]; // http://example.com/foo
|
||||
[NSURL URLWithString:@"foo/" relativeToURL:baseURL]; // http://example.com/v1/foo
|
||||
[NSURL URLWithString:@"/foo/" relativeToURL:baseURL]; // http://example.com/foo/
|
||||
[NSURL URLWithString:@"http://example2.com/" relativeToURL:baseURL]; // http://example2.com/
|
||||
|
||||
Also important to note is that a trailing slash will be added to any `baseURL` without one. This would otherwise cause unexpected behavior when constructing URLs using paths without a leading slash.
|
||||
|
||||
@warning Managers for background sessions must be owned for the duration of their use. This can be accomplished by creating an application-wide or shared singleton instance.
|
||||
*/
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface AFHTTPSessionManager : AFURLSessionManager <NSSecureCoding, NSCopying>
|
||||
|
||||
/**
|
||||
The URL used to construct requests from relative paths in methods like `requestWithMethod:URLString:parameters:`, and the `GET` / `POST` / et al. convenience methods.
|
||||
*/
|
||||
@property (readonly, nonatomic, strong, nullable) NSURL *baseURL;
|
||||
|
||||
/**
|
||||
Requests created with `requestWithMethod:URLString:parameters:` & `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:` are constructed with a set of default headers using a parameter serialization specified by this property. By default, this is set to an instance of `AFHTTPRequestSerializer`, which serializes query string parameters for `GET`, `HEAD`, and `DELETE` requests, or otherwise URL-form-encodes HTTP message bodies.
|
||||
|
||||
@warning `requestSerializer` must not be `nil`.
|
||||
*/
|
||||
@property (nonatomic, strong) AFHTTPRequestSerializer <AFURLRequestSerialization> * requestSerializer;
|
||||
|
||||
/**
|
||||
Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to an instance of `AFJSONResponseSerializer`.
|
||||
|
||||
@warning `responseSerializer` must not be `nil`.
|
||||
*/
|
||||
@property (nonatomic, strong) AFHTTPResponseSerializer <AFURLResponseSerialization> * responseSerializer;
|
||||
|
||||
///-------------------------------
|
||||
/// @name Managing Security Policy
|
||||
///-------------------------------
|
||||
|
||||
/**
|
||||
The security policy used by created session to evaluate server trust for secure connections. `AFURLSessionManager` uses the `defaultPolicy` unless otherwise specified. A security policy configured with `AFSSLPinningModePublicKey` or `AFSSLPinningModeCertificate` can only be applied on a session manager initialized with a secure base URL (i.e. https). Applying a security policy with pinning enabled on an insecure session manager throws an `Invalid Security Policy` exception.
|
||||
*/
|
||||
@property (nonatomic, strong) AFSecurityPolicy *securityPolicy;
|
||||
|
||||
///---------------------
|
||||
/// @name Initialization
|
||||
///---------------------
|
||||
|
||||
/**
|
||||
Creates and returns an `AFHTTPSessionManager` object.
|
||||
*/
|
||||
+ (instancetype)manager;
|
||||
|
||||
/**
|
||||
Initializes an `AFHTTPSessionManager` object with the specified base URL.
|
||||
|
||||
@param url The base URL for the HTTP client.
|
||||
|
||||
@return The newly-initialized HTTP client
|
||||
*/
|
||||
- (instancetype)initWithBaseURL:(nullable NSURL *)url;
|
||||
|
||||
/**
|
||||
Initializes an `AFHTTPSessionManager` object with the specified base URL.
|
||||
|
||||
This is the designated initializer.
|
||||
|
||||
@param url The base URL for the HTTP client.
|
||||
@param configuration The configuration used to create the managed session.
|
||||
|
||||
@return The newly-initialized HTTP client
|
||||
*/
|
||||
- (instancetype)initWithBaseURL:(nullable NSURL *)url
|
||||
sessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER;
|
||||
|
||||
///---------------------------
|
||||
/// @name Making HTTP Requests
|
||||
///---------------------------
|
||||
|
||||
/**
|
||||
Creates and runs an `NSURLSessionDataTask` with a `GET` request.
|
||||
|
||||
@param URLString The URL string used to create the request URL.
|
||||
@param parameters The parameters to be encoded according to the client request serializer.
|
||||
@param headers The headers appended to the default headers for this request.
|
||||
@param downloadProgress A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue.
|
||||
@param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
|
||||
@param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
|
||||
|
||||
@see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:
|
||||
*/
|
||||
- (nullable NSURLSessionDataTask *)GET:(NSString *)URLString
|
||||
parameters:(nullable id)parameters
|
||||
headers:(nullable NSDictionary <NSString *, NSString *> *)headers
|
||||
progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgress
|
||||
success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
|
||||
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
|
||||
|
||||
/**
|
||||
Creates and runs an `NSURLSessionDataTask` with a `HEAD` request.
|
||||
|
||||
@param URLString The URL string used to create the request URL.
|
||||
@param parameters The parameters to be encoded according to the client request serializer.
|
||||
@param headers The headers appended to the default headers for this request.
|
||||
@param success A block object to be executed when the task finishes successfully. This block has no return value and takes a single arguments: the data task.
|
||||
@param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
|
||||
|
||||
@see -dataTaskWithRequest:completionHandler:
|
||||
*/
|
||||
- (nullable NSURLSessionDataTask *)HEAD:(NSString *)URLString
|
||||
parameters:(nullable id)parameters
|
||||
headers:(nullable NSDictionary <NSString *, NSString *> *)headers
|
||||
success:(nullable void (^)(NSURLSessionDataTask *task))success
|
||||
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
|
||||
|
||||
/**
|
||||
Creates and runs an `NSURLSessionDataTask` with a `POST` request.
|
||||
|
||||
@param URLString The URL string used to create the request URL.
|
||||
@param parameters The parameters to be encoded according to the client request serializer.
|
||||
@param headers The headers appended to the default headers for this request.
|
||||
@param uploadProgress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.
|
||||
@param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
|
||||
@param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
|
||||
|
||||
@see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:
|
||||
*/
|
||||
- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString
|
||||
parameters:(nullable id)parameters
|
||||
headers:(nullable NSDictionary <NSString *, NSString *> *)headers
|
||||
progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress
|
||||
success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
|
||||
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
|
||||
|
||||
/**
|
||||
Creates and runs an `NSURLSessionDataTask` with a multipart `POST` request.
|
||||
|
||||
@param URLString The URL string used to create the request URL.
|
||||
@param parameters The parameters to be encoded according to the client request serializer.
|
||||
@param headers The headers appended to the default headers for this request.
|
||||
@param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol.
|
||||
@param uploadProgress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.
|
||||
@param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
|
||||
@param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
|
||||
|
||||
@see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:
|
||||
*/
|
||||
- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString
|
||||
parameters:(nullable id)parameters
|
||||
headers:(nullable NSDictionary <NSString *, NSString *> *)headers
|
||||
constructingBodyWithBlock:(nullable void (^)(id <AFMultipartFormData> formData))block
|
||||
progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress
|
||||
success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
|
||||
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
|
||||
|
||||
/**
|
||||
Creates and runs an `NSURLSessionDataTask` with a `PUT` request.
|
||||
|
||||
@param URLString The URL string used to create the request URL.
|
||||
@param parameters The parameters to be encoded according to the client request serializer.
|
||||
@param headers The headers appended to the default headers for this request.
|
||||
@param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
|
||||
@param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
|
||||
|
||||
@see -dataTaskWithRequest:completionHandler:
|
||||
*/
|
||||
- (nullable NSURLSessionDataTask *)PUT:(NSString *)URLString
|
||||
parameters:(nullable id)parameters
|
||||
headers:(nullable NSDictionary <NSString *, NSString *> *)headers
|
||||
success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
|
||||
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
|
||||
|
||||
/**
|
||||
Creates and runs an `NSURLSessionDataTask` with a `PATCH` request.
|
||||
|
||||
@param URLString The URL string used to create the request URL.
|
||||
@param parameters The parameters to be encoded according to the client request serializer.
|
||||
@param headers The headers appended to the default headers for this request.
|
||||
@param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
|
||||
@param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
|
||||
|
||||
@see -dataTaskWithRequest:completionHandler:
|
||||
*/
|
||||
- (nullable NSURLSessionDataTask *)PATCH:(NSString *)URLString
|
||||
parameters:(nullable id)parameters
|
||||
headers:(nullable NSDictionary <NSString *, NSString *> *)headers
|
||||
success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
|
||||
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
|
||||
|
||||
/**
|
||||
Creates and runs an `NSURLSessionDataTask` with a `DELETE` request.
|
||||
|
||||
@param URLString The URL string used to create the request URL.
|
||||
@param parameters The parameters to be encoded according to the client request serializer.
|
||||
@param headers The headers appended to the default headers for this request.
|
||||
@param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
|
||||
@param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
|
||||
|
||||
@see -dataTaskWithRequest:completionHandler:
|
||||
*/
|
||||
- (nullable NSURLSessionDataTask *)DELETE:(NSString *)URLString
|
||||
parameters:(nullable id)parameters
|
||||
headers:(nullable NSDictionary <NSString *, NSString *> *)headers
|
||||
success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
|
||||
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
|
||||
|
||||
/**
|
||||
Creates an `NSURLSessionDataTask` with a custom `HTTPMethod` request.
|
||||
|
||||
@param method The HTTPMethod string used to create the request.
|
||||
@param URLString The URL string used to create the request URL.
|
||||
@param parameters The parameters to be encoded according to the client request serializer.
|
||||
@param headers The headers appended to the default headers for this request.
|
||||
@param uploadProgress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.
|
||||
@param downloadProgress A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue.
|
||||
@param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
|
||||
@param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
|
||||
|
||||
@see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:
|
||||
*/
|
||||
- (nullable NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
|
||||
URLString:(NSString *)URLString
|
||||
parameters:(nullable id)parameters
|
||||
headers:(nullable NSDictionary <NSString *, NSString *> *)headers
|
||||
uploadProgress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress
|
||||
downloadProgress:(nullable void (^)(NSProgress *downloadProgress))downloadProgress
|
||||
success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
|
||||
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
357
Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.m
generated
Normal file
357
Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.m
generated
Normal file
@@ -0,0 +1,357 @@
|
||||
// AFHTTPSessionManager.m
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import "AFHTTPSessionManager.h"
|
||||
|
||||
#import "AFURLRequestSerialization.h"
|
||||
#import "AFURLResponseSerialization.h"
|
||||
|
||||
#import <Availability.h>
|
||||
#import <TargetConditionals.h>
|
||||
#import <Security/Security.h>
|
||||
|
||||
#import <netinet/in.h>
|
||||
#import <netinet6/in6.h>
|
||||
#import <arpa/inet.h>
|
||||
#import <ifaddrs.h>
|
||||
#import <netdb.h>
|
||||
|
||||
#if TARGET_OS_IOS || TARGET_OS_TV
|
||||
#import <UIKit/UIKit.h>
|
||||
#elif TARGET_OS_WATCH
|
||||
#import <WatchKit/WatchKit.h>
|
||||
#endif
|
||||
|
||||
@interface AFHTTPSessionManager ()
|
||||
@property (readwrite, nonatomic, strong) NSURL *baseURL;
|
||||
@end
|
||||
|
||||
@implementation AFHTTPSessionManager
|
||||
@dynamic responseSerializer;
|
||||
|
||||
+ (instancetype)manager {
|
||||
return [[[self class] alloc] initWithBaseURL:nil];
|
||||
}
|
||||
|
||||
- (instancetype)init {
|
||||
return [self initWithBaseURL:nil];
|
||||
}
|
||||
|
||||
- (instancetype)initWithBaseURL:(NSURL *)url {
|
||||
return [self initWithBaseURL:url sessionConfiguration:nil];
|
||||
}
|
||||
|
||||
- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration {
|
||||
return [self initWithBaseURL:nil sessionConfiguration:configuration];
|
||||
}
|
||||
|
||||
- (instancetype)initWithBaseURL:(NSURL *)url
|
||||
sessionConfiguration:(NSURLSessionConfiguration *)configuration
|
||||
{
|
||||
self = [super initWithSessionConfiguration:configuration];
|
||||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
// Ensure terminal slash for baseURL path, so that NSURL +URLWithString:relativeToURL: works as expected
|
||||
if ([[url path] length] > 0 && ![[url absoluteString] hasSuffix:@"/"]) {
|
||||
url = [url URLByAppendingPathComponent:@""];
|
||||
}
|
||||
|
||||
self.baseURL = url;
|
||||
|
||||
self.requestSerializer = [AFHTTPRequestSerializer serializer];
|
||||
self.responseSerializer = [AFJSONResponseSerializer serializer];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (void)setRequestSerializer:(AFHTTPRequestSerializer <AFURLRequestSerialization> *)requestSerializer {
|
||||
NSParameterAssert(requestSerializer);
|
||||
|
||||
_requestSerializer = requestSerializer;
|
||||
}
|
||||
|
||||
- (void)setResponseSerializer:(AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer {
|
||||
NSParameterAssert(responseSerializer);
|
||||
|
||||
[super setResponseSerializer:responseSerializer];
|
||||
}
|
||||
|
||||
@dynamic securityPolicy;
|
||||
|
||||
- (void)setSecurityPolicy:(AFSecurityPolicy *)securityPolicy {
|
||||
if (securityPolicy.SSLPinningMode != AFSSLPinningModeNone && ![self.baseURL.scheme isEqualToString:@"https"]) {
|
||||
NSString *pinningMode = @"Unknown Pinning Mode";
|
||||
switch (securityPolicy.SSLPinningMode) {
|
||||
case AFSSLPinningModeNone: pinningMode = @"AFSSLPinningModeNone"; break;
|
||||
case AFSSLPinningModeCertificate: pinningMode = @"AFSSLPinningModeCertificate"; break;
|
||||
case AFSSLPinningModePublicKey: pinningMode = @"AFSSLPinningModePublicKey"; break;
|
||||
}
|
||||
NSString *reason = [NSString stringWithFormat:@"A security policy configured with `%@` can only be applied on a manager with a secure base URL (i.e. https)", pinningMode];
|
||||
@throw [NSException exceptionWithName:@"Invalid Security Policy" reason:reason userInfo:nil];
|
||||
}
|
||||
|
||||
[super setSecurityPolicy:securityPolicy];
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (NSURLSessionDataTask *)GET:(NSString *)URLString
|
||||
parameters:(nullable id)parameters
|
||||
headers:(nullable NSDictionary <NSString *, NSString *> *)headers
|
||||
progress:(nullable void (^)(NSProgress * _Nonnull))downloadProgress
|
||||
success:(nullable void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
|
||||
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
|
||||
{
|
||||
|
||||
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"GET"
|
||||
URLString:URLString
|
||||
parameters:parameters
|
||||
headers:headers
|
||||
uploadProgress:nil
|
||||
downloadProgress:downloadProgress
|
||||
success:success
|
||||
failure:failure];
|
||||
|
||||
[dataTask resume];
|
||||
|
||||
return dataTask;
|
||||
}
|
||||
|
||||
- (NSURLSessionDataTask *)HEAD:(NSString *)URLString
|
||||
parameters:(nullable id)parameters
|
||||
headers:(nullable NSDictionary<NSString *,NSString *> *)headers
|
||||
success:(nullable void (^)(NSURLSessionDataTask * _Nonnull))success
|
||||
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
|
||||
{
|
||||
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"HEAD" URLString:URLString parameters:parameters headers:headers uploadProgress:nil downloadProgress:nil success:^(NSURLSessionDataTask *task, __unused id responseObject) {
|
||||
if (success) {
|
||||
success(task);
|
||||
}
|
||||
} failure:failure];
|
||||
|
||||
[dataTask resume];
|
||||
|
||||
return dataTask;
|
||||
}
|
||||
|
||||
- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString
|
||||
parameters:(nullable id)parameters
|
||||
headers:(nullable NSDictionary <NSString *, NSString *> *)headers
|
||||
progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress
|
||||
success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
|
||||
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure
|
||||
{
|
||||
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"POST" URLString:URLString parameters:parameters headers:headers uploadProgress:uploadProgress downloadProgress:nil success:success failure:failure];
|
||||
|
||||
[dataTask resume];
|
||||
|
||||
return dataTask;
|
||||
}
|
||||
|
||||
- (NSURLSessionDataTask *)POST:(NSString *)URLString
|
||||
parameters:(nullable id)parameters
|
||||
headers:(nullable NSDictionary<NSString *,NSString *> *)headers
|
||||
constructingBodyWithBlock:(nullable void (^)(id<AFMultipartFormData> _Nonnull))block
|
||||
progress:(nullable void (^)(NSProgress * _Nonnull))uploadProgress
|
||||
success:(nullable void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
|
||||
{
|
||||
NSError *serializationError = nil;
|
||||
NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError];
|
||||
for (NSString *headerField in headers.keyEnumerator) {
|
||||
[request setValue:headers[headerField] forHTTPHeaderField:headerField];
|
||||
}
|
||||
if (serializationError) {
|
||||
if (failure) {
|
||||
dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
|
||||
failure(nil, serializationError);
|
||||
});
|
||||
}
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
__block NSURLSessionDataTask *task = [self uploadTaskWithStreamedRequest:request progress:uploadProgress completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
|
||||
if (error) {
|
||||
if (failure) {
|
||||
failure(task, error);
|
||||
}
|
||||
} else {
|
||||
if (success) {
|
||||
success(task, responseObject);
|
||||
}
|
||||
}
|
||||
}];
|
||||
|
||||
[task resume];
|
||||
|
||||
return task;
|
||||
}
|
||||
|
||||
- (NSURLSessionDataTask *)PUT:(NSString *)URLString
|
||||
parameters:(nullable id)parameters
|
||||
headers:(nullable NSDictionary<NSString *,NSString *> *)headers
|
||||
success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success
|
||||
failure:(nullable void (^)(NSURLSessionDataTask *task, NSError *error))failure
|
||||
{
|
||||
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PUT" URLString:URLString parameters:parameters headers:headers uploadProgress:nil downloadProgress:nil success:success failure:failure];
|
||||
|
||||
[dataTask resume];
|
||||
|
||||
return dataTask;
|
||||
}
|
||||
|
||||
- (NSURLSessionDataTask *)PATCH:(NSString *)URLString
|
||||
parameters:(nullable id)parameters
|
||||
headers:(nullable NSDictionary<NSString *,NSString *> *)headers
|
||||
success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success
|
||||
failure:(nullable void (^)(NSURLSessionDataTask *task, NSError *error))failure
|
||||
{
|
||||
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PATCH" URLString:URLString parameters:parameters headers:headers uploadProgress:nil downloadProgress:nil success:success failure:failure];
|
||||
|
||||
[dataTask resume];
|
||||
|
||||
return dataTask;
|
||||
}
|
||||
|
||||
- (NSURLSessionDataTask *)DELETE:(NSString *)URLString
|
||||
parameters:(nullable id)parameters
|
||||
headers:(nullable NSDictionary<NSString *,NSString *> *)headers
|
||||
success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success
|
||||
failure:(nullable void (^)(NSURLSessionDataTask *task, NSError *error))failure
|
||||
{
|
||||
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"DELETE" URLString:URLString parameters:parameters headers:headers uploadProgress:nil downloadProgress:nil success:success failure:failure];
|
||||
|
||||
[dataTask resume];
|
||||
|
||||
return dataTask;
|
||||
}
|
||||
|
||||
|
||||
- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
|
||||
URLString:(NSString *)URLString
|
||||
parameters:(nullable id)parameters
|
||||
headers:(nullable NSDictionary <NSString *, NSString *> *)headers
|
||||
uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress
|
||||
downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress
|
||||
success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
|
||||
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure
|
||||
{
|
||||
NSError *serializationError = nil;
|
||||
NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError];
|
||||
for (NSString *headerField in headers.keyEnumerator) {
|
||||
[request setValue:headers[headerField] forHTTPHeaderField:headerField];
|
||||
}
|
||||
if (serializationError) {
|
||||
if (failure) {
|
||||
dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
|
||||
failure(nil, serializationError);
|
||||
});
|
||||
}
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
__block NSURLSessionDataTask *dataTask = nil;
|
||||
dataTask = [self dataTaskWithRequest:request
|
||||
uploadProgress:uploadProgress
|
||||
downloadProgress:downloadProgress
|
||||
completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
|
||||
if (error) {
|
||||
if (failure) {
|
||||
failure(dataTask, error);
|
||||
}
|
||||
} else {
|
||||
if (success) {
|
||||
success(dataTask, responseObject);
|
||||
}
|
||||
}
|
||||
}];
|
||||
|
||||
return dataTask;
|
||||
}
|
||||
|
||||
#pragma mark - NSObject
|
||||
|
||||
- (NSString *)description {
|
||||
return [NSString stringWithFormat:@"<%@: %p, baseURL: %@, session: %@, operationQueue: %@>", NSStringFromClass([self class]), self, [self.baseURL absoluteString], self.session, self.operationQueue];
|
||||
}
|
||||
|
||||
#pragma mark - NSSecureCoding
|
||||
|
||||
+ (BOOL)supportsSecureCoding {
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (instancetype)initWithCoder:(NSCoder *)decoder {
|
||||
NSURL *baseURL = [decoder decodeObjectOfClass:[NSURL class] forKey:NSStringFromSelector(@selector(baseURL))];
|
||||
NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"];
|
||||
if (!configuration) {
|
||||
NSString *configurationIdentifier = [decoder decodeObjectOfClass:[NSString class] forKey:@"identifier"];
|
||||
if (configurationIdentifier) {
|
||||
configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:configurationIdentifier];
|
||||
}
|
||||
}
|
||||
|
||||
self = [self initWithBaseURL:baseURL sessionConfiguration:configuration];
|
||||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
self.requestSerializer = [decoder decodeObjectOfClass:[AFHTTPRequestSerializer class] forKey:NSStringFromSelector(@selector(requestSerializer))];
|
||||
self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))];
|
||||
AFSecurityPolicy *decodedPolicy = [decoder decodeObjectOfClass:[AFSecurityPolicy class] forKey:NSStringFromSelector(@selector(securityPolicy))];
|
||||
if (decodedPolicy) {
|
||||
self.securityPolicy = decodedPolicy;
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)encodeWithCoder:(NSCoder *)coder {
|
||||
[super encodeWithCoder:coder];
|
||||
|
||||
[coder encodeObject:self.baseURL forKey:NSStringFromSelector(@selector(baseURL))];
|
||||
if ([self.session.configuration conformsToProtocol:@protocol(NSCoding)]) {
|
||||
[coder encodeObject:self.session.configuration forKey:@"sessionConfiguration"];
|
||||
} else {
|
||||
[coder encodeObject:self.session.configuration.identifier forKey:@"identifier"];
|
||||
}
|
||||
[coder encodeObject:self.requestSerializer forKey:NSStringFromSelector(@selector(requestSerializer))];
|
||||
[coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))];
|
||||
[coder encodeObject:self.securityPolicy forKey:NSStringFromSelector(@selector(securityPolicy))];
|
||||
}
|
||||
|
||||
#pragma mark - NSCopying
|
||||
|
||||
- (instancetype)copyWithZone:(NSZone *)zone {
|
||||
AFHTTPSessionManager *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL sessionConfiguration:self.session.configuration];
|
||||
|
||||
HTTPClient.requestSerializer = [self.requestSerializer copyWithZone:zone];
|
||||
HTTPClient.responseSerializer = [self.responseSerializer copyWithZone:zone];
|
||||
HTTPClient.securityPolicy = [self.securityPolicy copyWithZone:zone];
|
||||
return HTTPClient;
|
||||
}
|
||||
|
||||
@end
|
||||
216
Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.h
generated
Normal file
216
Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.h
generated
Normal file
@@ -0,0 +1,216 @@
|
||||
// AFNetworkReachabilityManager.h
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#if !TARGET_OS_WATCH
|
||||
#import <SystemConfiguration/SystemConfiguration.h>
|
||||
|
||||
typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {
|
||||
AFNetworkReachabilityStatusUnknown = -1,
|
||||
AFNetworkReachabilityStatusNotReachable = 0,
|
||||
AFNetworkReachabilityStatusReachableViaWWAN = 1,
|
||||
AFNetworkReachabilityStatusReachableViaWiFi = 2,
|
||||
};
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/**
|
||||
`AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces.
|
||||
|
||||
Reachability can be used to determine background information about why a network operation failed, or to trigger a network operation retrying when a connection is established. It should not be used to prevent a user from initiating a network request, as it's possible that an initial request may be required to establish reachability.
|
||||
|
||||
See Apple's Reachability Sample Code ( https://developer.apple.com/library/ios/samplecode/reachability/ )
|
||||
|
||||
@warning Instances of `AFNetworkReachabilityManager` must be started with `-startMonitoring` before reachability status can be determined.
|
||||
*/
|
||||
@interface AFNetworkReachabilityManager : NSObject
|
||||
|
||||
/**
|
||||
The current network reachability status.
|
||||
*/
|
||||
@property (readonly, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus;
|
||||
|
||||
/**
|
||||
Whether or not the network is currently reachable.
|
||||
*/
|
||||
@property (readonly, nonatomic, assign, getter = isReachable) BOOL reachable;
|
||||
|
||||
/**
|
||||
Whether or not the network is currently reachable via WWAN.
|
||||
*/
|
||||
@property (readonly, nonatomic, assign, getter = isReachableViaWWAN) BOOL reachableViaWWAN;
|
||||
|
||||
/**
|
||||
Whether or not the network is currently reachable via WiFi.
|
||||
*/
|
||||
@property (readonly, nonatomic, assign, getter = isReachableViaWiFi) BOOL reachableViaWiFi;
|
||||
|
||||
///---------------------
|
||||
/// @name Initialization
|
||||
///---------------------
|
||||
|
||||
/**
|
||||
Returns the shared network reachability manager.
|
||||
*/
|
||||
+ (instancetype)sharedManager;
|
||||
|
||||
/**
|
||||
Creates and returns a network reachability manager with the default socket address.
|
||||
|
||||
@return An initialized network reachability manager, actively monitoring the default socket address.
|
||||
*/
|
||||
+ (instancetype)manager;
|
||||
|
||||
/**
|
||||
Creates and returns a network reachability manager for the specified domain.
|
||||
|
||||
@param domain The domain used to evaluate network reachability.
|
||||
|
||||
@return An initialized network reachability manager, actively monitoring the specified domain.
|
||||
*/
|
||||
+ (instancetype)managerForDomain:(NSString *)domain;
|
||||
|
||||
/**
|
||||
Creates and returns a network reachability manager for the socket address.
|
||||
|
||||
@param address The socket address (`sockaddr_in6`) used to evaluate network reachability.
|
||||
|
||||
@return An initialized network reachability manager, actively monitoring the specified socket address.
|
||||
*/
|
||||
+ (instancetype)managerForAddress:(const void *)address;
|
||||
|
||||
/**
|
||||
Initializes an instance of a network reachability manager from the specified reachability object.
|
||||
|
||||
@param reachability The reachability object to monitor.
|
||||
|
||||
@return An initialized network reachability manager, actively monitoring the specified reachability.
|
||||
*/
|
||||
- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability NS_DESIGNATED_INITIALIZER;
|
||||
|
||||
/**
|
||||
* Unavailable initializer
|
||||
*/
|
||||
+ (instancetype)new NS_UNAVAILABLE;
|
||||
|
||||
/**
|
||||
* Unavailable initializer
|
||||
*/
|
||||
- (instancetype)init NS_UNAVAILABLE;
|
||||
|
||||
///--------------------------------------------------
|
||||
/// @name Starting & Stopping Reachability Monitoring
|
||||
///--------------------------------------------------
|
||||
|
||||
/**
|
||||
Starts monitoring for changes in network reachability status.
|
||||
*/
|
||||
- (void)startMonitoring;
|
||||
|
||||
/**
|
||||
Stops monitoring for changes in network reachability status.
|
||||
*/
|
||||
- (void)stopMonitoring;
|
||||
|
||||
///-------------------------------------------------
|
||||
/// @name Getting Localized Reachability Description
|
||||
///-------------------------------------------------
|
||||
|
||||
/**
|
||||
Returns a localized string representation of the current network reachability status.
|
||||
*/
|
||||
- (NSString *)localizedNetworkReachabilityStatusString;
|
||||
|
||||
///---------------------------------------------------
|
||||
/// @name Setting Network Reachability Change Callback
|
||||
///---------------------------------------------------
|
||||
|
||||
/**
|
||||
Sets a callback to be executed when the network availability of the `baseURL` host changes.
|
||||
|
||||
@param block A block object to be executed when the network availability of the `baseURL` host changes.. This block has no return value and takes a single argument which represents the various reachability states from the device to the `baseURL`.
|
||||
*/
|
||||
- (void)setReachabilityStatusChangeBlock:(nullable void (^)(AFNetworkReachabilityStatus status))block;
|
||||
|
||||
@end
|
||||
|
||||
///----------------
|
||||
/// @name Constants
|
||||
///----------------
|
||||
|
||||
/**
|
||||
## Network Reachability
|
||||
|
||||
The following constants are provided by `AFNetworkReachabilityManager` as possible network reachability statuses.
|
||||
|
||||
enum {
|
||||
AFNetworkReachabilityStatusUnknown,
|
||||
AFNetworkReachabilityStatusNotReachable,
|
||||
AFNetworkReachabilityStatusReachableViaWWAN,
|
||||
AFNetworkReachabilityStatusReachableViaWiFi,
|
||||
}
|
||||
|
||||
`AFNetworkReachabilityStatusUnknown`
|
||||
The `baseURL` host reachability is not known.
|
||||
|
||||
`AFNetworkReachabilityStatusNotReachable`
|
||||
The `baseURL` host cannot be reached.
|
||||
|
||||
`AFNetworkReachabilityStatusReachableViaWWAN`
|
||||
The `baseURL` host can be reached via a cellular connection, such as EDGE or GPRS.
|
||||
|
||||
`AFNetworkReachabilityStatusReachableViaWiFi`
|
||||
The `baseURL` host can be reached via a Wi-Fi connection.
|
||||
|
||||
### Keys for Notification UserInfo Dictionary
|
||||
|
||||
Strings that are used as keys in a `userInfo` dictionary in a network reachability status change notification.
|
||||
|
||||
`AFNetworkingReachabilityNotificationStatusItem`
|
||||
A key in the userInfo dictionary in a `AFNetworkingReachabilityDidChangeNotification` notification.
|
||||
The corresponding value is an `NSNumber` object representing the `AFNetworkReachabilityStatus` value for the current reachability status.
|
||||
*/
|
||||
|
||||
///--------------------
|
||||
/// @name Notifications
|
||||
///--------------------
|
||||
|
||||
/**
|
||||
Posted when network reachability changes.
|
||||
This notification assigns no notification object. The `userInfo` dictionary contains an `NSNumber` object under the `AFNetworkingReachabilityNotificationStatusItem` key, representing the `AFNetworkReachabilityStatus` value for the current network reachability.
|
||||
|
||||
@warning In order for network reachability to be monitored, include the `SystemConfiguration` framework in the active target's "Link Binary With Library" build phase, and add `#import <SystemConfiguration/SystemConfiguration.h>` to the header prefix of the project (`Prefix.pch`).
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityDidChangeNotification;
|
||||
FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityNotificationStatusItem;
|
||||
|
||||
///--------------------
|
||||
/// @name Functions
|
||||
///--------------------
|
||||
|
||||
/**
|
||||
Returns a localized string representation of an `AFNetworkReachabilityStatus` value.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status);
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
#endif
|
||||
269
Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.m
generated
Normal file
269
Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.m
generated
Normal file
@@ -0,0 +1,269 @@
|
||||
// AFNetworkReachabilityManager.m
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import "AFNetworkReachabilityManager.h"
|
||||
#if !TARGET_OS_WATCH
|
||||
|
||||
#import <netinet/in.h>
|
||||
#import <netinet6/in6.h>
|
||||
#import <arpa/inet.h>
|
||||
#import <ifaddrs.h>
|
||||
#import <netdb.h>
|
||||
|
||||
NSString * const AFNetworkingReachabilityDidChangeNotification = @"com.alamofire.networking.reachability.change";
|
||||
NSString * const AFNetworkingReachabilityNotificationStatusItem = @"AFNetworkingReachabilityNotificationStatusItem";
|
||||
|
||||
typedef void (^AFNetworkReachabilityStatusBlock)(AFNetworkReachabilityStatus status);
|
||||
typedef AFNetworkReachabilityManager * (^AFNetworkReachabilityStatusCallback)(AFNetworkReachabilityStatus status);
|
||||
|
||||
NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status) {
|
||||
switch (status) {
|
||||
case AFNetworkReachabilityStatusNotReachable:
|
||||
return NSLocalizedStringFromTable(@"Not Reachable", @"AFNetworking", nil);
|
||||
case AFNetworkReachabilityStatusReachableViaWWAN:
|
||||
return NSLocalizedStringFromTable(@"Reachable via WWAN", @"AFNetworking", nil);
|
||||
case AFNetworkReachabilityStatusReachableViaWiFi:
|
||||
return NSLocalizedStringFromTable(@"Reachable via WiFi", @"AFNetworking", nil);
|
||||
case AFNetworkReachabilityStatusUnknown:
|
||||
default:
|
||||
return NSLocalizedStringFromTable(@"Unknown", @"AFNetworking", nil);
|
||||
}
|
||||
}
|
||||
|
||||
static AFNetworkReachabilityStatus AFNetworkReachabilityStatusForFlags(SCNetworkReachabilityFlags flags) {
|
||||
BOOL isReachable = ((flags & kSCNetworkReachabilityFlagsReachable) != 0);
|
||||
BOOL needsConnection = ((flags & kSCNetworkReachabilityFlagsConnectionRequired) != 0);
|
||||
BOOL canConnectionAutomatically = (((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) || ((flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0));
|
||||
BOOL canConnectWithoutUserInteraction = (canConnectionAutomatically && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0);
|
||||
BOOL isNetworkReachable = (isReachable && (!needsConnection || canConnectWithoutUserInteraction));
|
||||
|
||||
AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusUnknown;
|
||||
if (isNetworkReachable == NO) {
|
||||
status = AFNetworkReachabilityStatusNotReachable;
|
||||
}
|
||||
#if TARGET_OS_IPHONE
|
||||
else if ((flags & kSCNetworkReachabilityFlagsIsWWAN) != 0) {
|
||||
status = AFNetworkReachabilityStatusReachableViaWWAN;
|
||||
}
|
||||
#endif
|
||||
else {
|
||||
status = AFNetworkReachabilityStatusReachableViaWiFi;
|
||||
}
|
||||
|
||||
return status;
|
||||
}
|
||||
|
||||
/**
|
||||
* Queue a status change notification for the main thread.
|
||||
*
|
||||
* This is done to ensure that the notifications are received in the same order
|
||||
* as they are sent. If notifications are sent directly, it is possible that
|
||||
* a queued notification (for an earlier status condition) is processed after
|
||||
* the later update, resulting in the listener being left in the wrong state.
|
||||
*/
|
||||
static void AFPostReachabilityStatusChange(SCNetworkReachabilityFlags flags, AFNetworkReachabilityStatusCallback block) {
|
||||
AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags);
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
AFNetworkReachabilityManager *manager = nil;
|
||||
if (block) {
|
||||
manager = block(status);
|
||||
}
|
||||
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
|
||||
NSDictionary *userInfo = @{ AFNetworkingReachabilityNotificationStatusItem: @(status) };
|
||||
[notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:manager userInfo:userInfo];
|
||||
});
|
||||
}
|
||||
|
||||
static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkReachabilityFlags flags, void *info) {
|
||||
AFPostReachabilityStatusChange(flags, (__bridge AFNetworkReachabilityStatusCallback)info);
|
||||
}
|
||||
|
||||
|
||||
static const void * AFNetworkReachabilityRetainCallback(const void *info) {
|
||||
return Block_copy(info);
|
||||
}
|
||||
|
||||
static void AFNetworkReachabilityReleaseCallback(const void *info) {
|
||||
if (info) {
|
||||
Block_release(info);
|
||||
}
|
||||
}
|
||||
|
||||
@interface AFNetworkReachabilityManager ()
|
||||
@property (readonly, nonatomic, assign) SCNetworkReachabilityRef networkReachability;
|
||||
@property (readwrite, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus;
|
||||
@property (readwrite, nonatomic, copy) AFNetworkReachabilityStatusBlock networkReachabilityStatusBlock;
|
||||
@end
|
||||
|
||||
@implementation AFNetworkReachabilityManager
|
||||
|
||||
+ (instancetype)sharedManager {
|
||||
static AFNetworkReachabilityManager *_sharedManager = nil;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
_sharedManager = [self manager];
|
||||
});
|
||||
|
||||
return _sharedManager;
|
||||
}
|
||||
|
||||
+ (instancetype)managerForDomain:(NSString *)domain {
|
||||
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [domain UTF8String]);
|
||||
|
||||
AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability];
|
||||
|
||||
CFRelease(reachability);
|
||||
|
||||
return manager;
|
||||
}
|
||||
|
||||
+ (instancetype)managerForAddress:(const void *)address {
|
||||
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)address);
|
||||
AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability];
|
||||
|
||||
CFRelease(reachability);
|
||||
|
||||
return manager;
|
||||
}
|
||||
|
||||
+ (instancetype)manager
|
||||
{
|
||||
#if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 90000) || (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101100)
|
||||
struct sockaddr_in6 address;
|
||||
bzero(&address, sizeof(address));
|
||||
address.sin6_len = sizeof(address);
|
||||
address.sin6_family = AF_INET6;
|
||||
#else
|
||||
struct sockaddr_in address;
|
||||
bzero(&address, sizeof(address));
|
||||
address.sin_len = sizeof(address);
|
||||
address.sin_family = AF_INET;
|
||||
#endif
|
||||
return [self managerForAddress:&address];
|
||||
}
|
||||
|
||||
- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability {
|
||||
self = [super init];
|
||||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
_networkReachability = CFRetain(reachability);
|
||||
self.networkReachabilityStatus = AFNetworkReachabilityStatusUnknown;
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (instancetype)init
|
||||
{
|
||||
@throw [NSException exceptionWithName:NSGenericException
|
||||
reason:@"`-init` unavailable. Use `-initWithReachability:` instead"
|
||||
userInfo:nil];
|
||||
return nil;
|
||||
}
|
||||
|
||||
- (void)dealloc {
|
||||
[self stopMonitoring];
|
||||
|
||||
if (_networkReachability != NULL) {
|
||||
CFRelease(_networkReachability);
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (BOOL)isReachable {
|
||||
return [self isReachableViaWWAN] || [self isReachableViaWiFi];
|
||||
}
|
||||
|
||||
- (BOOL)isReachableViaWWAN {
|
||||
return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN;
|
||||
}
|
||||
|
||||
- (BOOL)isReachableViaWiFi {
|
||||
return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi;
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (void)startMonitoring {
|
||||
[self stopMonitoring];
|
||||
|
||||
if (!self.networkReachability) {
|
||||
return;
|
||||
}
|
||||
|
||||
__weak __typeof(self)weakSelf = self;
|
||||
AFNetworkReachabilityStatusCallback callback = ^(AFNetworkReachabilityStatus status) {
|
||||
__strong __typeof(weakSelf)strongSelf = weakSelf;
|
||||
|
||||
strongSelf.networkReachabilityStatus = status;
|
||||
if (strongSelf.networkReachabilityStatusBlock) {
|
||||
strongSelf.networkReachabilityStatusBlock(status);
|
||||
}
|
||||
|
||||
return strongSelf;
|
||||
};
|
||||
|
||||
SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL};
|
||||
SCNetworkReachabilitySetCallback(self.networkReachability, AFNetworkReachabilityCallback, &context);
|
||||
SCNetworkReachabilityScheduleWithRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes);
|
||||
|
||||
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),^{
|
||||
SCNetworkReachabilityFlags flags;
|
||||
if (SCNetworkReachabilityGetFlags(self.networkReachability, &flags)) {
|
||||
AFPostReachabilityStatusChange(flags, callback);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
- (void)stopMonitoring {
|
||||
if (!self.networkReachability) {
|
||||
return;
|
||||
}
|
||||
|
||||
SCNetworkReachabilityUnscheduleFromRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes);
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (NSString *)localizedNetworkReachabilityStatusString {
|
||||
return AFStringFromNetworkReachabilityStatus(self.networkReachabilityStatus);
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block {
|
||||
self.networkReachabilityStatusBlock = block;
|
||||
}
|
||||
|
||||
#pragma mark - NSKeyValueObserving
|
||||
|
||||
+ (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key {
|
||||
if ([key isEqualToString:@"reachable"] || [key isEqualToString:@"reachableViaWWAN"] || [key isEqualToString:@"reachableViaWiFi"]) {
|
||||
return [NSSet setWithObject:@"networkReachabilityStatus"];
|
||||
}
|
||||
|
||||
return [super keyPathsForValuesAffectingValueForKey:key];
|
||||
}
|
||||
|
||||
@end
|
||||
#endif
|
||||
41
Pods/AFNetworking/AFNetworking/AFNetworking.h
generated
Normal file
41
Pods/AFNetworking/AFNetworking/AFNetworking.h
generated
Normal file
@@ -0,0 +1,41 @@
|
||||
// AFNetworking.h
|
||||
//
|
||||
// Copyright (c) 2013 AFNetworking (http://afnetworking.com/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <Availability.h>
|
||||
#import <TargetConditionals.h>
|
||||
|
||||
#ifndef _AFNETWORKING_
|
||||
#define _AFNETWORKING_
|
||||
|
||||
#import "AFURLRequestSerialization.h"
|
||||
#import "AFURLResponseSerialization.h"
|
||||
#import "AFSecurityPolicy.h"
|
||||
|
||||
#if !TARGET_OS_WATCH
|
||||
#import "AFNetworkReachabilityManager.h"
|
||||
#endif
|
||||
|
||||
#import "AFURLSessionManager.h"
|
||||
#import "AFHTTPSessionManager.h"
|
||||
|
||||
#endif /* _AFNETWORKING_ */
|
||||
161
Pods/AFNetworking/AFNetworking/AFSecurityPolicy.h
generated
Normal file
161
Pods/AFNetworking/AFNetworking/AFSecurityPolicy.h
generated
Normal file
@@ -0,0 +1,161 @@
|
||||
// AFSecurityPolicy.h
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <Security/Security.h>
|
||||
|
||||
typedef NS_ENUM(NSUInteger, AFSSLPinningMode) {
|
||||
AFSSLPinningModeNone,
|
||||
AFSSLPinningModePublicKey,
|
||||
AFSSLPinningModeCertificate,
|
||||
};
|
||||
|
||||
/**
|
||||
`AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections.
|
||||
|
||||
Adding pinned SSL certificates to your app helps prevent man-in-the-middle attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with SSL pinning configured and enabled.
|
||||
*/
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface AFSecurityPolicy : NSObject <NSSecureCoding, NSCopying>
|
||||
|
||||
/**
|
||||
The criteria by which server trust should be evaluated against the pinned SSL certificates. Defaults to `AFSSLPinningModeNone`.
|
||||
*/
|
||||
@property (readonly, nonatomic, assign) AFSSLPinningMode SSLPinningMode;
|
||||
|
||||
/**
|
||||
The certificates used to evaluate server trust according to the SSL pinning mode.
|
||||
|
||||
Note that if pinning is enabled, `evaluateServerTrust:forDomain:` will return true if any pinned certificate matches.
|
||||
|
||||
@see policyWithPinningMode:withPinnedCertificates:
|
||||
*/
|
||||
@property (nonatomic, strong, nullable) NSSet <NSData *> *pinnedCertificates;
|
||||
|
||||
/**
|
||||
Whether or not to trust servers with an invalid or expired SSL certificates. Defaults to `NO`.
|
||||
*/
|
||||
@property (nonatomic, assign) BOOL allowInvalidCertificates;
|
||||
|
||||
/**
|
||||
Whether or not to validate the domain name in the certificate's CN field. Defaults to `YES`.
|
||||
*/
|
||||
@property (nonatomic, assign) BOOL validatesDomainName;
|
||||
|
||||
///-----------------------------------------
|
||||
/// @name Getting Certificates from the Bundle
|
||||
///-----------------------------------------
|
||||
|
||||
/**
|
||||
Returns any certificates included in the bundle. If you are using AFNetworking as an embedded framework, you must use this method to find the certificates you have included in your app bundle, and use them when creating your security policy by calling `policyWithPinningMode:withPinnedCertificates`.
|
||||
|
||||
@return The certificates included in the given bundle.
|
||||
*/
|
||||
+ (NSSet <NSData *> *)certificatesInBundle:(NSBundle *)bundle;
|
||||
|
||||
///-----------------------------------------
|
||||
/// @name Getting Specific Security Policies
|
||||
///-----------------------------------------
|
||||
|
||||
/**
|
||||
Returns the shared default security policy, which does not allow invalid certificates, validates domain name, and does not validate against pinned certificates or public keys.
|
||||
|
||||
@return The default security policy.
|
||||
*/
|
||||
+ (instancetype)defaultPolicy;
|
||||
|
||||
///---------------------
|
||||
/// @name Initialization
|
||||
///---------------------
|
||||
|
||||
/**
|
||||
Creates and returns a security policy with the specified pinning mode.
|
||||
|
||||
Certificates with the `.cer` extension found in the main bundle will be pinned. If you want more control over which certificates are pinned, please use `policyWithPinningMode:withPinnedCertificates:` instead.
|
||||
|
||||
@param pinningMode The SSL pinning mode.
|
||||
|
||||
@return A new security policy.
|
||||
|
||||
@see -policyWithPinningMode:withPinnedCertificates:
|
||||
*/
|
||||
+ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode;
|
||||
|
||||
/**
|
||||
Creates and returns a security policy with the specified pinning mode.
|
||||
|
||||
@param pinningMode The SSL pinning mode.
|
||||
@param pinnedCertificates The certificates to pin against.
|
||||
|
||||
@return A new security policy.
|
||||
|
||||
@see +certificatesInBundle:
|
||||
@see -pinnedCertificates
|
||||
*/
|
||||
+ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet <NSData *> *)pinnedCertificates;
|
||||
|
||||
///------------------------------
|
||||
/// @name Evaluating Server Trust
|
||||
///------------------------------
|
||||
|
||||
/**
|
||||
Whether or not the specified server trust should be accepted, based on the security policy.
|
||||
|
||||
This method should be used when responding to an authentication challenge from a server.
|
||||
|
||||
@param serverTrust The X.509 certificate trust of the server.
|
||||
@param domain The domain of serverTrust. If `nil`, the domain will not be validated.
|
||||
|
||||
@return Whether or not to trust the server.
|
||||
*/
|
||||
- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust
|
||||
forDomain:(nullable NSString *)domain;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
///----------------
|
||||
/// @name Constants
|
||||
///----------------
|
||||
|
||||
/**
|
||||
## SSL Pinning Modes
|
||||
|
||||
The following constants are provided by `AFSSLPinningMode` as possible SSL pinning modes.
|
||||
|
||||
enum {
|
||||
AFSSLPinningModeNone,
|
||||
AFSSLPinningModePublicKey,
|
||||
AFSSLPinningModeCertificate,
|
||||
}
|
||||
|
||||
`AFSSLPinningModeNone`
|
||||
Do not used pinned certificates to validate servers.
|
||||
|
||||
`AFSSLPinningModePublicKey`
|
||||
Validate host certificates against public keys of pinned certificates.
|
||||
|
||||
`AFSSLPinningModeCertificate`
|
||||
Validate host certificates against pinned certificates.
|
||||
*/
|
||||
341
Pods/AFNetworking/AFNetworking/AFSecurityPolicy.m
generated
Normal file
341
Pods/AFNetworking/AFNetworking/AFSecurityPolicy.m
generated
Normal file
@@ -0,0 +1,341 @@
|
||||
// AFSecurityPolicy.m
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import "AFSecurityPolicy.h"
|
||||
|
||||
#import <AssertMacros.h>
|
||||
|
||||
#if !TARGET_OS_IOS && !TARGET_OS_WATCH && !TARGET_OS_TV
|
||||
static NSData * AFSecKeyGetData(SecKeyRef key) {
|
||||
CFDataRef data = NULL;
|
||||
|
||||
__Require_noErr_Quiet(SecItemExport(key, kSecFormatUnknown, kSecItemPemArmour, NULL, &data), _out);
|
||||
|
||||
return (__bridge_transfer NSData *)data;
|
||||
|
||||
_out:
|
||||
if (data) {
|
||||
CFRelease(data);
|
||||
}
|
||||
|
||||
return nil;
|
||||
}
|
||||
#endif
|
||||
|
||||
static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
|
||||
#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV
|
||||
return [(__bridge id)key1 isEqual:(__bridge id)key2];
|
||||
#else
|
||||
return [AFSecKeyGetData(key1) isEqual:AFSecKeyGetData(key2)];
|
||||
#endif
|
||||
}
|
||||
|
||||
static id AFPublicKeyForCertificate(NSData *certificate) {
|
||||
id allowedPublicKey = nil;
|
||||
SecCertificateRef allowedCertificate;
|
||||
SecPolicyRef policy = nil;
|
||||
SecTrustRef allowedTrust = nil;
|
||||
SecTrustResultType result;
|
||||
|
||||
allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificate);
|
||||
__Require_Quiet(allowedCertificate != NULL, _out);
|
||||
|
||||
policy = SecPolicyCreateBasicX509();
|
||||
__Require_noErr_Quiet(SecTrustCreateWithCertificates(allowedCertificate, policy, &allowedTrust), _out);
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
|
||||
__Require_noErr_Quiet(SecTrustEvaluate(allowedTrust, &result), _out);
|
||||
#pragma clang diagnostic pop
|
||||
|
||||
allowedPublicKey = (__bridge_transfer id)SecTrustCopyPublicKey(allowedTrust);
|
||||
|
||||
_out:
|
||||
if (allowedTrust) {
|
||||
CFRelease(allowedTrust);
|
||||
}
|
||||
|
||||
if (policy) {
|
||||
CFRelease(policy);
|
||||
}
|
||||
|
||||
if (allowedCertificate) {
|
||||
CFRelease(allowedCertificate);
|
||||
}
|
||||
|
||||
return allowedPublicKey;
|
||||
}
|
||||
|
||||
static BOOL AFServerTrustIsValid(SecTrustRef serverTrust) {
|
||||
BOOL isValid = NO;
|
||||
SecTrustResultType result;
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
|
||||
__Require_noErr_Quiet(SecTrustEvaluate(serverTrust, &result), _out);
|
||||
#pragma clang diagnostic pop
|
||||
|
||||
isValid = (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed);
|
||||
|
||||
_out:
|
||||
return isValid;
|
||||
}
|
||||
|
||||
static NSArray * AFCertificateTrustChainForServerTrust(SecTrustRef serverTrust) {
|
||||
CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust);
|
||||
NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount];
|
||||
|
||||
for (CFIndex i = 0; i < certificateCount; i++) {
|
||||
SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i);
|
||||
[trustChain addObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)];
|
||||
}
|
||||
|
||||
return [NSArray arrayWithArray:trustChain];
|
||||
}
|
||||
|
||||
static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) {
|
||||
SecPolicyRef policy = SecPolicyCreateBasicX509();
|
||||
CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust);
|
||||
NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount];
|
||||
for (CFIndex i = 0; i < certificateCount; i++) {
|
||||
SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i);
|
||||
|
||||
SecCertificateRef someCertificates[] = {certificate};
|
||||
CFArrayRef certificates = CFArrayCreate(NULL, (const void **)someCertificates, 1, NULL);
|
||||
|
||||
SecTrustRef trust;
|
||||
__Require_noErr_Quiet(SecTrustCreateWithCertificates(certificates, policy, &trust), _out);
|
||||
SecTrustResultType result;
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
|
||||
__Require_noErr_Quiet(SecTrustEvaluate(trust, &result), _out);
|
||||
#pragma clang diagnostic pop
|
||||
[trustChain addObject:(__bridge_transfer id)SecTrustCopyPublicKey(trust)];
|
||||
|
||||
_out:
|
||||
if (trust) {
|
||||
CFRelease(trust);
|
||||
}
|
||||
|
||||
if (certificates) {
|
||||
CFRelease(certificates);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
CFRelease(policy);
|
||||
|
||||
return [NSArray arrayWithArray:trustChain];
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@interface AFSecurityPolicy()
|
||||
@property (readwrite, nonatomic, assign) AFSSLPinningMode SSLPinningMode;
|
||||
@property (readwrite, nonatomic, strong) NSSet *pinnedPublicKeys;
|
||||
@end
|
||||
|
||||
@implementation AFSecurityPolicy
|
||||
|
||||
+ (NSSet *)certificatesInBundle:(NSBundle *)bundle {
|
||||
NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."];
|
||||
|
||||
NSMutableSet *certificates = [NSMutableSet setWithCapacity:[paths count]];
|
||||
for (NSString *path in paths) {
|
||||
NSData *certificateData = [NSData dataWithContentsOfFile:path];
|
||||
[certificates addObject:certificateData];
|
||||
}
|
||||
|
||||
return [NSSet setWithSet:certificates];
|
||||
}
|
||||
|
||||
+ (instancetype)defaultPolicy {
|
||||
AFSecurityPolicy *securityPolicy = [[self alloc] init];
|
||||
securityPolicy.SSLPinningMode = AFSSLPinningModeNone;
|
||||
|
||||
return securityPolicy;
|
||||
}
|
||||
|
||||
+ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode {
|
||||
NSSet <NSData *> *defaultPinnedCertificates = [self certificatesInBundle:[NSBundle mainBundle]];
|
||||
return [self policyWithPinningMode:pinningMode withPinnedCertificates:defaultPinnedCertificates];
|
||||
}
|
||||
|
||||
+ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet *)pinnedCertificates {
|
||||
AFSecurityPolicy *securityPolicy = [[self alloc] init];
|
||||
securityPolicy.SSLPinningMode = pinningMode;
|
||||
|
||||
[securityPolicy setPinnedCertificates:pinnedCertificates];
|
||||
|
||||
return securityPolicy;
|
||||
}
|
||||
|
||||
- (instancetype)init {
|
||||
self = [super init];
|
||||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
self.validatesDomainName = YES;
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)setPinnedCertificates:(NSSet *)pinnedCertificates {
|
||||
_pinnedCertificates = pinnedCertificates;
|
||||
|
||||
if (self.pinnedCertificates) {
|
||||
NSMutableSet *mutablePinnedPublicKeys = [NSMutableSet setWithCapacity:[self.pinnedCertificates count]];
|
||||
for (NSData *certificate in self.pinnedCertificates) {
|
||||
id publicKey = AFPublicKeyForCertificate(certificate);
|
||||
if (!publicKey) {
|
||||
continue;
|
||||
}
|
||||
[mutablePinnedPublicKeys addObject:publicKey];
|
||||
}
|
||||
self.pinnedPublicKeys = [NSSet setWithSet:mutablePinnedPublicKeys];
|
||||
} else {
|
||||
self.pinnedPublicKeys = nil;
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust
|
||||
forDomain:(NSString *)domain
|
||||
{
|
||||
if (domain && self.allowInvalidCertificates && self.validatesDomainName && (self.SSLPinningMode == AFSSLPinningModeNone || [self.pinnedCertificates count] == 0)) {
|
||||
// https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/NetworkingTopics/Articles/OverridingSSLChainValidationCorrectly.html
|
||||
// According to the docs, you should only trust your provided certs for evaluation.
|
||||
// Pinned certificates are added to the trust. Without pinned certificates,
|
||||
// there is nothing to evaluate against.
|
||||
//
|
||||
// From Apple Docs:
|
||||
// "Do not implicitly trust self-signed certificates as anchors (kSecTrustOptionImplicitAnchors).
|
||||
// Instead, add your own (self-signed) CA certificate to the list of trusted anchors."
|
||||
NSLog(@"In order to validate a domain name for self signed certificates, you MUST use pinning.");
|
||||
return NO;
|
||||
}
|
||||
|
||||
NSMutableArray *policies = [NSMutableArray array];
|
||||
if (self.validatesDomainName) {
|
||||
[policies addObject:(__bridge_transfer id)SecPolicyCreateSSL(true, (__bridge CFStringRef)domain)];
|
||||
} else {
|
||||
[policies addObject:(__bridge_transfer id)SecPolicyCreateBasicX509()];
|
||||
}
|
||||
|
||||
SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)policies);
|
||||
|
||||
if (self.SSLPinningMode == AFSSLPinningModeNone) {
|
||||
return self.allowInvalidCertificates || AFServerTrustIsValid(serverTrust);
|
||||
} else if (!self.allowInvalidCertificates && !AFServerTrustIsValid(serverTrust)) {
|
||||
return NO;
|
||||
}
|
||||
|
||||
switch (self.SSLPinningMode) {
|
||||
case AFSSLPinningModeCertificate: {
|
||||
NSMutableArray *pinnedCertificates = [NSMutableArray array];
|
||||
for (NSData *certificateData in self.pinnedCertificates) {
|
||||
[pinnedCertificates addObject:(__bridge_transfer id)SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificateData)];
|
||||
}
|
||||
SecTrustSetAnchorCertificates(serverTrust, (__bridge CFArrayRef)pinnedCertificates);
|
||||
|
||||
if (!AFServerTrustIsValid(serverTrust)) {
|
||||
return NO;
|
||||
}
|
||||
|
||||
// obtain the chain after being validated, which *should* contain the pinned certificate in the last position (if it's the Root CA)
|
||||
NSArray *serverCertificates = AFCertificateTrustChainForServerTrust(serverTrust);
|
||||
|
||||
for (NSData *trustChainCertificate in [serverCertificates reverseObjectEnumerator]) {
|
||||
if ([self.pinnedCertificates containsObject:trustChainCertificate]) {
|
||||
return YES;
|
||||
}
|
||||
}
|
||||
|
||||
return NO;
|
||||
}
|
||||
case AFSSLPinningModePublicKey: {
|
||||
NSUInteger trustedPublicKeyCount = 0;
|
||||
NSArray *publicKeys = AFPublicKeyTrustChainForServerTrust(serverTrust);
|
||||
|
||||
for (id trustChainPublicKey in publicKeys) {
|
||||
for (id pinnedPublicKey in self.pinnedPublicKeys) {
|
||||
if (AFSecKeyIsEqualToKey((__bridge SecKeyRef)trustChainPublicKey, (__bridge SecKeyRef)pinnedPublicKey)) {
|
||||
trustedPublicKeyCount += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return trustedPublicKeyCount > 0;
|
||||
}
|
||||
|
||||
default:
|
||||
return NO;
|
||||
}
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
#pragma mark - NSKeyValueObserving
|
||||
|
||||
+ (NSSet *)keyPathsForValuesAffectingPinnedPublicKeys {
|
||||
return [NSSet setWithObject:@"pinnedCertificates"];
|
||||
}
|
||||
|
||||
#pragma mark - NSSecureCoding
|
||||
|
||||
+ (BOOL)supportsSecureCoding {
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (instancetype)initWithCoder:(NSCoder *)decoder {
|
||||
|
||||
self = [self init];
|
||||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
self.SSLPinningMode = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(SSLPinningMode))] unsignedIntegerValue];
|
||||
self.allowInvalidCertificates = [decoder decodeBoolForKey:NSStringFromSelector(@selector(allowInvalidCertificates))];
|
||||
self.validatesDomainName = [decoder decodeBoolForKey:NSStringFromSelector(@selector(validatesDomainName))];
|
||||
self.pinnedCertificates = [decoder decodeObjectOfClass:[NSSet class] forKey:NSStringFromSelector(@selector(pinnedCertificates))];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)encodeWithCoder:(NSCoder *)coder {
|
||||
[coder encodeObject:[NSNumber numberWithUnsignedInteger:self.SSLPinningMode] forKey:NSStringFromSelector(@selector(SSLPinningMode))];
|
||||
[coder encodeBool:self.allowInvalidCertificates forKey:NSStringFromSelector(@selector(allowInvalidCertificates))];
|
||||
[coder encodeBool:self.validatesDomainName forKey:NSStringFromSelector(@selector(validatesDomainName))];
|
||||
[coder encodeObject:self.pinnedCertificates forKey:NSStringFromSelector(@selector(pinnedCertificates))];
|
||||
}
|
||||
|
||||
#pragma mark - NSCopying
|
||||
|
||||
- (instancetype)copyWithZone:(NSZone *)zone {
|
||||
AFSecurityPolicy *securityPolicy = [[[self class] allocWithZone:zone] init];
|
||||
securityPolicy.SSLPinningMode = self.SSLPinningMode;
|
||||
securityPolicy.allowInvalidCertificates = self.allowInvalidCertificates;
|
||||
securityPolicy.validatesDomainName = self.validatesDomainName;
|
||||
securityPolicy.pinnedCertificates = [self.pinnedCertificates copyWithZone:zone];
|
||||
|
||||
return securityPolicy;
|
||||
}
|
||||
|
||||
@end
|
||||
479
Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.h
generated
Normal file
479
Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.h
generated
Normal file
@@ -0,0 +1,479 @@
|
||||
// AFURLRequestSerialization.h
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <TargetConditionals.h>
|
||||
|
||||
#if TARGET_OS_IOS || TARGET_OS_TV
|
||||
#import <UIKit/UIKit.h>
|
||||
#elif TARGET_OS_WATCH
|
||||
#import <WatchKit/WatchKit.h>
|
||||
#endif
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/**
|
||||
Returns a percent-escaped string following RFC 3986 for a query string key or value.
|
||||
RFC 3986 states that the following characters are "reserved" characters.
|
||||
- General Delimiters: ":", "#", "[", "]", "@", "?", "/"
|
||||
- Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
|
||||
|
||||
In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
|
||||
query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
|
||||
should be percent-escaped in the query string.
|
||||
|
||||
@param string The string to be percent-escaped.
|
||||
|
||||
@return The percent-escaped string.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * AFPercentEscapedStringFromString(NSString *string);
|
||||
|
||||
/**
|
||||
A helper method to generate encoded url query parameters for appending to the end of a URL.
|
||||
|
||||
@param parameters A dictionary of key/values to be encoded.
|
||||
|
||||
@return A url encoded query string
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * AFQueryStringFromParameters(NSDictionary *parameters);
|
||||
|
||||
/**
|
||||
The `AFURLRequestSerialization` protocol is adopted by an object that encodes parameters for a specified HTTP requests. Request serializers may encode parameters as query strings, HTTP bodies, setting the appropriate HTTP header fields as necessary.
|
||||
|
||||
For example, a JSON request serializer may set the HTTP body of the request to a JSON representation, and set the `Content-Type` HTTP header field value to `application/json`.
|
||||
*/
|
||||
@protocol AFURLRequestSerialization <NSObject, NSSecureCoding, NSCopying>
|
||||
|
||||
/**
|
||||
Returns a request with the specified parameters encoded into a copy of the original request.
|
||||
|
||||
@param request The original request.
|
||||
@param parameters The parameters to be encoded.
|
||||
@param error The error that occurred while attempting to encode the request parameters.
|
||||
|
||||
@return A serialized request.
|
||||
*/
|
||||
- (nullable NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
|
||||
withParameters:(nullable id)parameters
|
||||
error:(NSError * _Nullable __autoreleasing *)error NS_SWIFT_NOTHROW;
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
/**
|
||||
|
||||
*/
|
||||
typedef NS_ENUM(NSUInteger, AFHTTPRequestQueryStringSerializationStyle) {
|
||||
AFHTTPRequestQueryStringDefaultStyle = 0,
|
||||
};
|
||||
|
||||
@protocol AFMultipartFormData;
|
||||
|
||||
/**
|
||||
`AFHTTPRequestSerializer` conforms to the `AFURLRequestSerialization` & `AFURLResponseSerialization` protocols, offering a concrete base implementation of query string / URL form-encoded parameter serialization and default request headers, as well as response status code and content type validation.
|
||||
|
||||
Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPRequestSerializer` in order to ensure consistent default behavior.
|
||||
*/
|
||||
@interface AFHTTPRequestSerializer : NSObject <AFURLRequestSerialization>
|
||||
|
||||
/**
|
||||
The string encoding used to serialize parameters. `NSUTF8StringEncoding` by default.
|
||||
*/
|
||||
@property (nonatomic, assign) NSStringEncoding stringEncoding;
|
||||
|
||||
/**
|
||||
Whether created requests can use the device’s cellular radio (if present). `YES` by default.
|
||||
|
||||
@see NSMutableURLRequest -setAllowsCellularAccess:
|
||||
*/
|
||||
@property (nonatomic, assign) BOOL allowsCellularAccess;
|
||||
|
||||
/**
|
||||
The cache policy of created requests. `NSURLRequestUseProtocolCachePolicy` by default.
|
||||
|
||||
@see NSMutableURLRequest -setCachePolicy:
|
||||
*/
|
||||
@property (nonatomic, assign) NSURLRequestCachePolicy cachePolicy;
|
||||
|
||||
/**
|
||||
Whether created requests should use the default cookie handling. `YES` by default.
|
||||
|
||||
@see NSMutableURLRequest -setHTTPShouldHandleCookies:
|
||||
*/
|
||||
@property (nonatomic, assign) BOOL HTTPShouldHandleCookies;
|
||||
|
||||
/**
|
||||
Whether created requests can continue transmitting data before receiving a response from an earlier transmission. `NO` by default
|
||||
|
||||
@see NSMutableURLRequest -setHTTPShouldUsePipelining:
|
||||
*/
|
||||
@property (nonatomic, assign) BOOL HTTPShouldUsePipelining;
|
||||
|
||||
/**
|
||||
The network service type for created requests. `NSURLNetworkServiceTypeDefault` by default.
|
||||
|
||||
@see NSMutableURLRequest -setNetworkServiceType:
|
||||
*/
|
||||
@property (nonatomic, assign) NSURLRequestNetworkServiceType networkServiceType;
|
||||
|
||||
/**
|
||||
The timeout interval, in seconds, for created requests. The default timeout interval is 60 seconds.
|
||||
|
||||
@see NSMutableURLRequest -setTimeoutInterval:
|
||||
*/
|
||||
@property (nonatomic, assign) NSTimeInterval timeoutInterval;
|
||||
|
||||
///---------------------------------------
|
||||
/// @name Configuring HTTP Request Headers
|
||||
///---------------------------------------
|
||||
|
||||
/**
|
||||
Default HTTP header field values to be applied to serialized requests. By default, these include the following:
|
||||
|
||||
- `Accept-Language` with the contents of `NSLocale +preferredLanguages`
|
||||
- `User-Agent` with the contents of various bundle identifiers and OS designations
|
||||
|
||||
@discussion To add or remove default request headers, use `setValue:forHTTPHeaderField:`.
|
||||
*/
|
||||
@property (readonly, nonatomic, strong) NSDictionary <NSString *, NSString *> *HTTPRequestHeaders;
|
||||
|
||||
/**
|
||||
Creates and returns a serializer with default configuration.
|
||||
*/
|
||||
+ (instancetype)serializer;
|
||||
|
||||
/**
|
||||
Sets the value for the HTTP headers set in request objects made by the HTTP client. If `nil`, removes the existing value for that header.
|
||||
|
||||
@param field The HTTP header to set a default value for
|
||||
@param value The value set as default for the specified header, or `nil`
|
||||
*/
|
||||
- (void)setValue:(nullable NSString *)value
|
||||
forHTTPHeaderField:(NSString *)field;
|
||||
|
||||
/**
|
||||
Returns the value for the HTTP headers set in the request serializer.
|
||||
|
||||
@param field The HTTP header to retrieve the default value for
|
||||
|
||||
@return The value set as default for the specified header, or `nil`
|
||||
*/
|
||||
- (nullable NSString *)valueForHTTPHeaderField:(NSString *)field;
|
||||
|
||||
/**
|
||||
Sets the "Authorization" HTTP header set in request objects made by the HTTP client to a basic authentication value with Base64-encoded username and password. This overwrites any existing value for this header.
|
||||
|
||||
@param username The HTTP basic auth username
|
||||
@param password The HTTP basic auth password
|
||||
*/
|
||||
- (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username
|
||||
password:(NSString *)password;
|
||||
|
||||
/**
|
||||
Clears any existing value for the "Authorization" HTTP header.
|
||||
*/
|
||||
- (void)clearAuthorizationHeader;
|
||||
|
||||
///-------------------------------------------------------
|
||||
/// @name Configuring Query String Parameter Serialization
|
||||
///-------------------------------------------------------
|
||||
|
||||
/**
|
||||
HTTP methods for which serialized requests will encode parameters as a query string. `GET`, `HEAD`, and `DELETE` by default.
|
||||
*/
|
||||
@property (nonatomic, strong) NSSet <NSString *> *HTTPMethodsEncodingParametersInURI;
|
||||
|
||||
/**
|
||||
Set the method of query string serialization according to one of the pre-defined styles.
|
||||
|
||||
@param style The serialization style.
|
||||
|
||||
@see AFHTTPRequestQueryStringSerializationStyle
|
||||
*/
|
||||
- (void)setQueryStringSerializationWithStyle:(AFHTTPRequestQueryStringSerializationStyle)style;
|
||||
|
||||
/**
|
||||
Set the a custom method of query string serialization according to the specified block.
|
||||
|
||||
@param block A block that defines a process of encoding parameters into a query string. This block returns the query string and takes three arguments: the request, the parameters to encode, and the error that occurred when attempting to encode parameters for the given request.
|
||||
*/
|
||||
- (void)setQueryStringSerializationWithBlock:(nullable NSString * _Nullable (^)(NSURLRequest *request, id parameters, NSError * __autoreleasing *error))block;
|
||||
|
||||
///-------------------------------
|
||||
/// @name Creating Request Objects
|
||||
///-------------------------------
|
||||
|
||||
/**
|
||||
Creates an `NSMutableURLRequest` object with the specified HTTP method and URL string.
|
||||
|
||||
If the HTTP method is `GET`, `HEAD`, or `DELETE`, the parameters will be used to construct a url-encoded query string that is appended to the request's URL. Otherwise, the parameters will be encoded according to the value of the `parameterEncoding` property, and set as the request body.
|
||||
|
||||
@param method The HTTP method for the request, such as `GET`, `POST`, `PUT`, or `DELETE`. This parameter must not be `nil`.
|
||||
@param URLString The URL string used to create the request URL.
|
||||
@param parameters The parameters to be either set as a query string for `GET` requests, or the request HTTP body.
|
||||
@param error The error that occurred while constructing the request.
|
||||
|
||||
@return An `NSMutableURLRequest` object.
|
||||
*/
|
||||
- (nullable NSMutableURLRequest *)requestWithMethod:(NSString *)method
|
||||
URLString:(NSString *)URLString
|
||||
parameters:(nullable id)parameters
|
||||
error:(NSError * _Nullable __autoreleasing *)error;
|
||||
|
||||
/**
|
||||
Creates an `NSMutableURLRequest` object with the specified HTTP method and URLString, and constructs a `multipart/form-data` HTTP body, using the specified parameters and multipart form data block. See http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.2
|
||||
|
||||
Multipart form requests are automatically streamed, reading files directly from disk along with in-memory data in a single HTTP body. The resulting `NSMutableURLRequest` object has an `HTTPBodyStream` property, so refrain from setting `HTTPBodyStream` or `HTTPBody` on this request object, as it will clear out the multipart form body stream.
|
||||
|
||||
@param method The HTTP method for the request. This parameter must not be `GET` or `HEAD`, or `nil`.
|
||||
@param URLString The URL string used to create the request URL.
|
||||
@param parameters The parameters to be encoded and set in the request HTTP body.
|
||||
@param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol.
|
||||
@param error The error that occurred while constructing the request.
|
||||
|
||||
@return An `NSMutableURLRequest` object
|
||||
*/
|
||||
- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
|
||||
URLString:(NSString *)URLString
|
||||
parameters:(nullable NSDictionary <NSString *, id> *)parameters
|
||||
constructingBodyWithBlock:(nullable void (^)(id <AFMultipartFormData> formData))block
|
||||
error:(NSError * _Nullable __autoreleasing *)error;
|
||||
|
||||
/**
|
||||
Creates an `NSMutableURLRequest` by removing the `HTTPBodyStream` from a request, and asynchronously writing its contents into the specified file, invoking the completion handler when finished.
|
||||
|
||||
@param request The multipart form request. The `HTTPBodyStream` property of `request` must not be `nil`.
|
||||
@param fileURL The file URL to write multipart form contents to.
|
||||
@param handler A handler block to execute.
|
||||
|
||||
@discussion There is a bug in `NSURLSessionTask` that causes requests to not send a `Content-Length` header when streaming contents from an HTTP body, which is notably problematic when interacting with the Amazon S3 webservice. As a workaround, this method takes a request constructed with `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:error:`, or any other request with an `HTTPBodyStream`, writes the contents to the specified file and returns a copy of the original request with the `HTTPBodyStream` property set to `nil`. From here, the file can either be passed to `AFURLSessionManager -uploadTaskWithRequest:fromFile:progress:completionHandler:`, or have its contents read into an `NSData` that's assigned to the `HTTPBody` property of the request.
|
||||
|
||||
@see https://github.com/AFNetworking/AFNetworking/issues/1398
|
||||
*/
|
||||
- (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request
|
||||
writingStreamContentsToFile:(NSURL *)fileURL
|
||||
completionHandler:(nullable void (^)(NSError * _Nullable error))handler;
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
/**
|
||||
The `AFMultipartFormData` protocol defines the methods supported by the parameter in the block argument of `AFHTTPRequestSerializer -multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:`.
|
||||
*/
|
||||
@protocol AFMultipartFormData
|
||||
|
||||
/**
|
||||
Appends the HTTP header `Content-Disposition: file; filename=#{generated filename}; name=#{name}"` and `Content-Type: #{generated mimeType}`, followed by the encoded file data and the multipart form boundary.
|
||||
|
||||
The filename and MIME type for this data in the form will be automatically generated, using the last path component of the `fileURL` and system associated MIME type for the `fileURL` extension, respectively.
|
||||
|
||||
@param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`.
|
||||
@param name The name to be associated with the specified data. This parameter must not be `nil`.
|
||||
@param error If an error occurs, upon return contains an `NSError` object that describes the problem.
|
||||
|
||||
@return `YES` if the file data was successfully appended, otherwise `NO`.
|
||||
*/
|
||||
- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
|
||||
name:(NSString *)name
|
||||
error:(NSError * _Nullable __autoreleasing *)error;
|
||||
|
||||
/**
|
||||
Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary.
|
||||
|
||||
@param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`.
|
||||
@param name The name to be associated with the specified data. This parameter must not be `nil`.
|
||||
@param fileName The file name to be used in the `Content-Disposition` header. This parameter must not be `nil`.
|
||||
@param mimeType The declared MIME type of the file data. This parameter must not be `nil`.
|
||||
@param error If an error occurs, upon return contains an `NSError` object that describes the problem.
|
||||
|
||||
@return `YES` if the file data was successfully appended otherwise `NO`.
|
||||
*/
|
||||
- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
|
||||
name:(NSString *)name
|
||||
fileName:(NSString *)fileName
|
||||
mimeType:(NSString *)mimeType
|
||||
error:(NSError * _Nullable __autoreleasing *)error;
|
||||
|
||||
/**
|
||||
Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the data from the input stream and the multipart form boundary.
|
||||
|
||||
@param inputStream The input stream to be appended to the form data
|
||||
@param name The name to be associated with the specified input stream. This parameter must not be `nil`.
|
||||
@param fileName The filename to be associated with the specified input stream. This parameter must not be `nil`.
|
||||
@param length The length of the specified input stream in bytes.
|
||||
@param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`.
|
||||
*/
|
||||
- (void)appendPartWithInputStream:(nullable NSInputStream *)inputStream
|
||||
name:(NSString *)name
|
||||
fileName:(NSString *)fileName
|
||||
length:(int64_t)length
|
||||
mimeType:(NSString *)mimeType;
|
||||
|
||||
/**
|
||||
Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary.
|
||||
|
||||
@param data The data to be encoded and appended to the form data.
|
||||
@param name The name to be associated with the specified data. This parameter must not be `nil`.
|
||||
@param fileName The filename to be associated with the specified data. This parameter must not be `nil`.
|
||||
@param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`.
|
||||
*/
|
||||
- (void)appendPartWithFileData:(NSData *)data
|
||||
name:(NSString *)name
|
||||
fileName:(NSString *)fileName
|
||||
mimeType:(NSString *)mimeType;
|
||||
|
||||
/**
|
||||
Appends the HTTP headers `Content-Disposition: form-data; name=#{name}"`, followed by the encoded data and the multipart form boundary.
|
||||
|
||||
@param data The data to be encoded and appended to the form data.
|
||||
@param name The name to be associated with the specified data. This parameter must not be `nil`.
|
||||
*/
|
||||
|
||||
- (void)appendPartWithFormData:(NSData *)data
|
||||
name:(NSString *)name;
|
||||
|
||||
|
||||
/**
|
||||
Appends HTTP headers, followed by the encoded data and the multipart form boundary.
|
||||
|
||||
@param headers The HTTP headers to be appended to the form data.
|
||||
@param body The data to be encoded and appended to the form data. This parameter must not be `nil`.
|
||||
*/
|
||||
- (void)appendPartWithHeaders:(nullable NSDictionary <NSString *, NSString *> *)headers
|
||||
body:(NSData *)body;
|
||||
|
||||
/**
|
||||
Throttles request bandwidth by limiting the packet size and adding a delay for each chunk read from the upload stream.
|
||||
|
||||
When uploading over a 3G or EDGE connection, requests may fail with "request body stream exhausted". Setting a maximum packet size and delay according to the recommended values (`kAFUploadStream3GSuggestedPacketSize` and `kAFUploadStream3GSuggestedDelay`) lowers the risk of the input stream exceeding its allocated bandwidth. Unfortunately, there is no definite way to distinguish between a 3G, EDGE, or LTE connection over `NSURLConnection`. As such, it is not recommended that you throttle bandwidth based solely on network reachability. Instead, you should consider checking for the "request body stream exhausted" in a failure block, and then retrying the request with throttled bandwidth.
|
||||
|
||||
@param numberOfBytes Maximum packet size, in number of bytes. The default packet size for an input stream is 16kb.
|
||||
@param delay Duration of delay each time a packet is read. By default, no delay is set.
|
||||
*/
|
||||
- (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes
|
||||
delay:(NSTimeInterval)delay;
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
/**
|
||||
`AFJSONRequestSerializer` is a subclass of `AFHTTPRequestSerializer` that encodes parameters as JSON using `NSJSONSerialization`, setting the `Content-Type` of the encoded request to `application/json`.
|
||||
*/
|
||||
@interface AFJSONRequestSerializer : AFHTTPRequestSerializer
|
||||
|
||||
/**
|
||||
Options for writing the request JSON data from Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONWritingOptions". `0` by default.
|
||||
*/
|
||||
@property (nonatomic, assign) NSJSONWritingOptions writingOptions;
|
||||
|
||||
/**
|
||||
Creates and returns a JSON serializer with specified reading and writing options.
|
||||
|
||||
@param writingOptions The specified JSON writing options.
|
||||
*/
|
||||
+ (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions;
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
/**
|
||||
`AFPropertyListRequestSerializer` is a subclass of `AFHTTPRequestSerializer` that encodes parameters as JSON using `NSPropertyListSerializer`, setting the `Content-Type` of the encoded request to `application/x-plist`.
|
||||
*/
|
||||
@interface AFPropertyListRequestSerializer : AFHTTPRequestSerializer
|
||||
|
||||
/**
|
||||
The property list format. Possible values are described in "NSPropertyListFormat".
|
||||
*/
|
||||
@property (nonatomic, assign) NSPropertyListFormat format;
|
||||
|
||||
/**
|
||||
@warning The `writeOptions` property is currently unused.
|
||||
*/
|
||||
@property (nonatomic, assign) NSPropertyListWriteOptions writeOptions;
|
||||
|
||||
/**
|
||||
Creates and returns a property list serializer with a specified format, read options, and write options.
|
||||
|
||||
@param format The property list format.
|
||||
@param writeOptions The property list write options.
|
||||
|
||||
@warning The `writeOptions` property is currently unused.
|
||||
*/
|
||||
+ (instancetype)serializerWithFormat:(NSPropertyListFormat)format
|
||||
writeOptions:(NSPropertyListWriteOptions)writeOptions;
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
///----------------
|
||||
/// @name Constants
|
||||
///----------------
|
||||
|
||||
/**
|
||||
## Error Domains
|
||||
|
||||
The following error domain is predefined.
|
||||
|
||||
- `NSString * const AFURLRequestSerializationErrorDomain`
|
||||
|
||||
### Constants
|
||||
|
||||
`AFURLRequestSerializationErrorDomain`
|
||||
AFURLRequestSerializer errors. Error codes for `AFURLRequestSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFURLRequestSerializationErrorDomain;
|
||||
|
||||
/**
|
||||
## User info dictionary keys
|
||||
|
||||
These keys may exist in the user info dictionary, in addition to those defined for NSError.
|
||||
|
||||
- `NSString * const AFNetworkingOperationFailingURLRequestErrorKey`
|
||||
|
||||
### Constants
|
||||
|
||||
`AFNetworkingOperationFailingURLRequestErrorKey`
|
||||
The corresponding value is an `NSURLRequest` containing the request of the operation associated with an error. This key is only present in the `AFURLRequestSerializationErrorDomain`.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLRequestErrorKey;
|
||||
|
||||
/**
|
||||
## Throttling Bandwidth for HTTP Request Input Streams
|
||||
|
||||
@see -throttleBandwidthWithPacketSize:delay:
|
||||
|
||||
### Constants
|
||||
|
||||
`kAFUploadStream3GSuggestedPacketSize`
|
||||
Maximum packet size, in number of bytes. Equal to 16kb.
|
||||
|
||||
`kAFUploadStream3GSuggestedDelay`
|
||||
Duration of delay each time a packet is read. Equal to 0.2 seconds.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSUInteger const kAFUploadStream3GSuggestedPacketSize;
|
||||
FOUNDATION_EXPORT NSTimeInterval const kAFUploadStream3GSuggestedDelay;
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
1399
Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.m
generated
Normal file
1399
Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.m
generated
Normal file
File diff suppressed because it is too large
Load Diff
313
Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.h
generated
Normal file
313
Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.h
generated
Normal file
@@ -0,0 +1,313 @@
|
||||
// AFURLResponseSerialization.h
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <CoreGraphics/CoreGraphics.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/**
|
||||
Recursively removes `NSNull` values from a JSON object.
|
||||
*/
|
||||
FOUNDATION_EXPORT id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingOptions readingOptions);
|
||||
|
||||
/**
|
||||
The `AFURLResponseSerialization` protocol is adopted by an object that decodes data into a more useful object representation, according to details in the server response. Response serializers may additionally perform validation on the incoming response and data.
|
||||
|
||||
For example, a JSON response serializer may check for an acceptable status code (`2XX` range) and content type (`application/json`), decoding a valid JSON response into an object.
|
||||
*/
|
||||
@protocol AFURLResponseSerialization <NSObject, NSSecureCoding, NSCopying>
|
||||
|
||||
/**
|
||||
The response object decoded from the data associated with a specified response.
|
||||
|
||||
@param response The response to be processed.
|
||||
@param data The response data to be decoded.
|
||||
@param error The error that occurred while attempting to decode the response data.
|
||||
|
||||
@return The object decoded from the specified response data.
|
||||
*/
|
||||
- (nullable id)responseObjectForResponse:(nullable NSURLResponse *)response
|
||||
data:(nullable NSData *)data
|
||||
error:(NSError * _Nullable __autoreleasing *)error NS_SWIFT_NOTHROW;
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
/**
|
||||
`AFHTTPResponseSerializer` conforms to the `AFURLRequestSerialization` & `AFURLResponseSerialization` protocols, offering a concrete base implementation of query string / URL form-encoded parameter serialization and default request headers, as well as response status code and content type validation.
|
||||
|
||||
Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPResponseSerializer` in order to ensure consistent default behavior.
|
||||
*/
|
||||
@interface AFHTTPResponseSerializer : NSObject <AFURLResponseSerialization>
|
||||
|
||||
- (instancetype)init;
|
||||
|
||||
/**
|
||||
Creates and returns a serializer with default configuration.
|
||||
*/
|
||||
+ (instancetype)serializer;
|
||||
|
||||
///-----------------------------------------
|
||||
/// @name Configuring Response Serialization
|
||||
///-----------------------------------------
|
||||
|
||||
/**
|
||||
The acceptable HTTP status codes for responses. When non-`nil`, responses with status codes not contained by the set will result in an error during validation.
|
||||
|
||||
See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
|
||||
*/
|
||||
@property (nonatomic, copy, nullable) NSIndexSet *acceptableStatusCodes;
|
||||
|
||||
/**
|
||||
The acceptable MIME types for responses. When non-`nil`, responses with a `Content-Type` with MIME types that do not intersect with the set will result in an error during validation.
|
||||
*/
|
||||
@property (nonatomic, copy, nullable) NSSet <NSString *> *acceptableContentTypes;
|
||||
|
||||
/**
|
||||
Validates the specified response and data.
|
||||
|
||||
In its base implementation, this method checks for an acceptable status code and content type. Subclasses may wish to add other domain-specific checks.
|
||||
|
||||
@param response The response to be validated.
|
||||
@param data The data associated with the response.
|
||||
@param error The error that occurred while attempting to validate the response.
|
||||
|
||||
@return `YES` if the response is valid, otherwise `NO`.
|
||||
*/
|
||||
- (BOOL)validateResponse:(nullable NSHTTPURLResponse *)response
|
||||
data:(nullable NSData *)data
|
||||
error:(NSError * _Nullable __autoreleasing *)error;
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
|
||||
/**
|
||||
`AFJSONResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes JSON responses.
|
||||
|
||||
By default, `AFJSONResponseSerializer` accepts the following MIME types, which includes the official standard, `application/json`, as well as other commonly-used types:
|
||||
|
||||
- `application/json`
|
||||
- `text/json`
|
||||
- `text/javascript`
|
||||
|
||||
In RFC 7159 - Section 8.1, it states that JSON text is required to be encoded in UTF-8, UTF-16, or UTF-32, and the default encoding is UTF-8. NSJSONSerialization provides support for all the encodings listed in the specification, and recommends UTF-8 for efficiency. Using an unsupported encoding will result in serialization error. See the `NSJSONSerialization` documentation for more details.
|
||||
*/
|
||||
@interface AFJSONResponseSerializer : AFHTTPResponseSerializer
|
||||
|
||||
- (instancetype)init;
|
||||
|
||||
/**
|
||||
Options for reading the response JSON data and creating the Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default.
|
||||
*/
|
||||
@property (nonatomic, assign) NSJSONReadingOptions readingOptions;
|
||||
|
||||
/**
|
||||
Whether to remove keys with `NSNull` values from response JSON. Defaults to `NO`.
|
||||
*/
|
||||
@property (nonatomic, assign) BOOL removesKeysWithNullValues;
|
||||
|
||||
/**
|
||||
Creates and returns a JSON serializer with specified reading and writing options.
|
||||
|
||||
@param readingOptions The specified JSON reading options.
|
||||
*/
|
||||
+ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions;
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
/**
|
||||
`AFXMLParserResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLParser` objects.
|
||||
|
||||
By default, `AFXMLParserResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types:
|
||||
|
||||
- `application/xml`
|
||||
- `text/xml`
|
||||
*/
|
||||
@interface AFXMLParserResponseSerializer : AFHTTPResponseSerializer
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
|
||||
|
||||
/**
|
||||
`AFXMLDocumentResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects.
|
||||
|
||||
By default, `AFXMLDocumentResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types:
|
||||
|
||||
- `application/xml`
|
||||
- `text/xml`
|
||||
*/
|
||||
@interface AFXMLDocumentResponseSerializer : AFHTTPResponseSerializer
|
||||
|
||||
- (instancetype)init;
|
||||
|
||||
/**
|
||||
Input and output options specifically intended for `NSXMLDocument` objects. For possible values, see the `NSXMLDocument` documentation section "Input and Output Options". `0` by default.
|
||||
*/
|
||||
@property (nonatomic, assign) NSUInteger options;
|
||||
|
||||
/**
|
||||
Creates and returns an XML document serializer with the specified options.
|
||||
|
||||
@param mask The XML document options.
|
||||
*/
|
||||
+ (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask;
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
|
||||
#pragma mark -
|
||||
|
||||
/**
|
||||
`AFPropertyListResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects.
|
||||
|
||||
By default, `AFPropertyListResponseSerializer` accepts the following MIME types:
|
||||
|
||||
- `application/x-plist`
|
||||
*/
|
||||
@interface AFPropertyListResponseSerializer : AFHTTPResponseSerializer
|
||||
|
||||
- (instancetype)init;
|
||||
|
||||
/**
|
||||
The property list format. Possible values are described in "NSPropertyListFormat".
|
||||
*/
|
||||
@property (nonatomic, assign) NSPropertyListFormat format;
|
||||
|
||||
/**
|
||||
The property list reading options. Possible values are described in "NSPropertyListMutabilityOptions."
|
||||
*/
|
||||
@property (nonatomic, assign) NSPropertyListReadOptions readOptions;
|
||||
|
||||
/**
|
||||
Creates and returns a property list serializer with a specified format, read options, and write options.
|
||||
|
||||
@param format The property list format.
|
||||
@param readOptions The property list reading options.
|
||||
*/
|
||||
+ (instancetype)serializerWithFormat:(NSPropertyListFormat)format
|
||||
readOptions:(NSPropertyListReadOptions)readOptions;
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
/**
|
||||
`AFImageResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes image responses.
|
||||
|
||||
By default, `AFImageResponseSerializer` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage:
|
||||
|
||||
- `image/tiff`
|
||||
- `image/jpeg`
|
||||
- `image/gif`
|
||||
- `image/png`
|
||||
- `image/ico`
|
||||
- `image/x-icon`
|
||||
- `image/bmp`
|
||||
- `image/x-bmp`
|
||||
- `image/x-xbitmap`
|
||||
- `image/x-win-bitmap`
|
||||
*/
|
||||
@interface AFImageResponseSerializer : AFHTTPResponseSerializer
|
||||
|
||||
#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
|
||||
/**
|
||||
The scale factor used when interpreting the image data to construct `responseImage`. Specifying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the size property. This is set to the value of scale of the main screen by default, which automatically scales images for retina displays, for instance.
|
||||
*/
|
||||
@property (nonatomic, assign) CGFloat imageScale;
|
||||
|
||||
/**
|
||||
Whether to automatically inflate response image data for compressed formats (such as PNG or JPEG). Enabling this can significantly improve drawing performance on iOS when used with `setCompletionBlockWithSuccess:failure:`, as it allows a bitmap representation to be constructed in the background rather than on the main thread. `YES` by default.
|
||||
*/
|
||||
@property (nonatomic, assign) BOOL automaticallyInflatesResponseImage;
|
||||
#endif
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
/**
|
||||
`AFCompoundSerializer` is a subclass of `AFHTTPResponseSerializer` that delegates the response serialization to the first `AFHTTPResponseSerializer` object that returns an object for `responseObjectForResponse:data:error:`, falling back on the default behavior of `AFHTTPResponseSerializer`. This is useful for supporting multiple potential types and structures of server responses with a single serializer.
|
||||
*/
|
||||
@interface AFCompoundResponseSerializer : AFHTTPResponseSerializer
|
||||
|
||||
/**
|
||||
The component response serializers.
|
||||
*/
|
||||
@property (readonly, nonatomic, copy) NSArray <id<AFURLResponseSerialization>> *responseSerializers;
|
||||
|
||||
/**
|
||||
Creates and returns a compound serializer comprised of the specified response serializers.
|
||||
|
||||
@warning Each response serializer specified must be a subclass of `AFHTTPResponseSerializer`, and response to `-validateResponse:data:error:`.
|
||||
*/
|
||||
+ (instancetype)compoundSerializerWithResponseSerializers:(NSArray <id<AFURLResponseSerialization>> *)responseSerializers;
|
||||
|
||||
@end
|
||||
|
||||
///----------------
|
||||
/// @name Constants
|
||||
///----------------
|
||||
|
||||
/**
|
||||
## Error Domains
|
||||
|
||||
The following error domain is predefined.
|
||||
|
||||
- `NSString * const AFURLResponseSerializationErrorDomain`
|
||||
|
||||
### Constants
|
||||
|
||||
`AFURLResponseSerializationErrorDomain`
|
||||
AFURLResponseSerializer errors. Error codes for `AFURLResponseSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFURLResponseSerializationErrorDomain;
|
||||
|
||||
/**
|
||||
## User info dictionary keys
|
||||
|
||||
These keys may exist in the user info dictionary, in addition to those defined for NSError.
|
||||
|
||||
- `NSString * const AFNetworkingOperationFailingURLResponseErrorKey`
|
||||
- `NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey`
|
||||
|
||||
### Constants
|
||||
|
||||
`AFNetworkingOperationFailingURLResponseErrorKey`
|
||||
The corresponding value is an `NSURLResponse` containing the response of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`.
|
||||
|
||||
`AFNetworkingOperationFailingURLResponseDataErrorKey`
|
||||
The corresponding value is an `NSData` containing the original data of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseErrorKey;
|
||||
|
||||
FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey;
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
836
Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.m
generated
Executable file
836
Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.m
generated
Executable file
@@ -0,0 +1,836 @@
|
||||
// AFURLResponseSerialization.m
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import "AFURLResponseSerialization.h"
|
||||
|
||||
#import <TargetConditionals.h>
|
||||
|
||||
#if TARGET_OS_IOS
|
||||
#import <UIKit/UIKit.h>
|
||||
#elif TARGET_OS_WATCH
|
||||
#import <WatchKit/WatchKit.h>
|
||||
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#endif
|
||||
|
||||
NSString * const AFURLResponseSerializationErrorDomain = @"com.alamofire.error.serialization.response";
|
||||
NSString * const AFNetworkingOperationFailingURLResponseErrorKey = @"com.alamofire.serialization.response.error.response";
|
||||
NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey = @"com.alamofire.serialization.response.error.data";
|
||||
|
||||
static NSError * AFErrorWithUnderlyingError(NSError *error, NSError *underlyingError) {
|
||||
if (!error) {
|
||||
return underlyingError;
|
||||
}
|
||||
|
||||
if (!underlyingError || error.userInfo[NSUnderlyingErrorKey]) {
|
||||
return error;
|
||||
}
|
||||
|
||||
NSMutableDictionary *mutableUserInfo = [error.userInfo mutableCopy];
|
||||
mutableUserInfo[NSUnderlyingErrorKey] = underlyingError;
|
||||
|
||||
return [[NSError alloc] initWithDomain:error.domain code:error.code userInfo:mutableUserInfo];
|
||||
}
|
||||
|
||||
static BOOL AFErrorOrUnderlyingErrorHasCodeInDomain(NSError *error, NSInteger code, NSString *domain) {
|
||||
if ([error.domain isEqualToString:domain] && error.code == code) {
|
||||
return YES;
|
||||
} else if (error.userInfo[NSUnderlyingErrorKey]) {
|
||||
return AFErrorOrUnderlyingErrorHasCodeInDomain(error.userInfo[NSUnderlyingErrorKey], code, domain);
|
||||
}
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingOptions readingOptions) {
|
||||
if ([JSONObject isKindOfClass:[NSArray class]]) {
|
||||
NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:[(NSArray *)JSONObject count]];
|
||||
for (id value in (NSArray *)JSONObject) {
|
||||
if (![value isEqual:[NSNull null]]) {
|
||||
[mutableArray addObject:AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions)];
|
||||
}
|
||||
}
|
||||
|
||||
return (readingOptions & NSJSONReadingMutableContainers) ? mutableArray : [NSArray arrayWithArray:mutableArray];
|
||||
} else if ([JSONObject isKindOfClass:[NSDictionary class]]) {
|
||||
NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary:JSONObject];
|
||||
for (id <NSCopying> key in [(NSDictionary *)JSONObject allKeys]) {
|
||||
id value = (NSDictionary *)JSONObject[key];
|
||||
if (!value || [value isEqual:[NSNull null]]) {
|
||||
[mutableDictionary removeObjectForKey:key];
|
||||
} else if ([value isKindOfClass:[NSArray class]] || [value isKindOfClass:[NSDictionary class]]) {
|
||||
mutableDictionary[key] = AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions);
|
||||
}
|
||||
}
|
||||
|
||||
return (readingOptions & NSJSONReadingMutableContainers) ? mutableDictionary : [NSDictionary dictionaryWithDictionary:mutableDictionary];
|
||||
}
|
||||
|
||||
return JSONObject;
|
||||
}
|
||||
|
||||
@implementation AFHTTPResponseSerializer
|
||||
|
||||
+ (instancetype)serializer {
|
||||
return [[self alloc] init];
|
||||
}
|
||||
|
||||
- (instancetype)init {
|
||||
self = [super init];
|
||||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
self.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)];
|
||||
self.acceptableContentTypes = nil;
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (BOOL)validateResponse:(NSHTTPURLResponse *)response
|
||||
data:(NSData *)data
|
||||
error:(NSError * __autoreleasing *)error
|
||||
{
|
||||
BOOL responseIsValid = YES;
|
||||
NSError *validationError = nil;
|
||||
|
||||
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
|
||||
if (self.acceptableContentTypes && ![self.acceptableContentTypes containsObject:[response MIMEType]] &&
|
||||
!([response MIMEType] == nil && [data length] == 0)) {
|
||||
|
||||
if ([data length] > 0 && [response URL]) {
|
||||
NSMutableDictionary *mutableUserInfo = [@{
|
||||
NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: unacceptable content-type: %@", @"AFNetworking", nil), [response MIMEType]],
|
||||
NSURLErrorFailingURLErrorKey:[response URL],
|
||||
AFNetworkingOperationFailingURLResponseErrorKey: response,
|
||||
} mutableCopy];
|
||||
if (data) {
|
||||
mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data;
|
||||
}
|
||||
|
||||
validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:mutableUserInfo], validationError);
|
||||
}
|
||||
|
||||
responseIsValid = NO;
|
||||
}
|
||||
|
||||
if (self.acceptableStatusCodes && ![self.acceptableStatusCodes containsIndex:(NSUInteger)response.statusCode] && [response URL]) {
|
||||
NSMutableDictionary *mutableUserInfo = [@{
|
||||
NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: %@ (%ld)", @"AFNetworking", nil), [NSHTTPURLResponse localizedStringForStatusCode:response.statusCode], (long)response.statusCode],
|
||||
NSURLErrorFailingURLErrorKey:[response URL],
|
||||
AFNetworkingOperationFailingURLResponseErrorKey: response,
|
||||
} mutableCopy];
|
||||
|
||||
if (data) {
|
||||
mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data;
|
||||
}
|
||||
|
||||
validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorBadServerResponse userInfo:mutableUserInfo], validationError);
|
||||
|
||||
responseIsValid = NO;
|
||||
}
|
||||
}
|
||||
|
||||
if (error && !responseIsValid) {
|
||||
*error = validationError;
|
||||
}
|
||||
|
||||
return responseIsValid;
|
||||
}
|
||||
|
||||
#pragma mark - AFURLResponseSerialization
|
||||
|
||||
- (id)responseObjectForResponse:(NSURLResponse *)response
|
||||
data:(NSData *)data
|
||||
error:(NSError *__autoreleasing *)error
|
||||
{
|
||||
[self validateResponse:(NSHTTPURLResponse *)response data:data error:error];
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
#pragma mark - NSSecureCoding
|
||||
|
||||
+ (BOOL)supportsSecureCoding {
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (instancetype)initWithCoder:(NSCoder *)decoder {
|
||||
self = [self init];
|
||||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
self.acceptableStatusCodes = [decoder decodeObjectOfClass:[NSIndexSet class] forKey:NSStringFromSelector(@selector(acceptableStatusCodes))];
|
||||
self.acceptableContentTypes = [decoder decodeObjectOfClass:[NSSet class] forKey:NSStringFromSelector(@selector(acceptableContentTypes))];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)encodeWithCoder:(NSCoder *)coder {
|
||||
[coder encodeObject:self.acceptableStatusCodes forKey:NSStringFromSelector(@selector(acceptableStatusCodes))];
|
||||
[coder encodeObject:self.acceptableContentTypes forKey:NSStringFromSelector(@selector(acceptableContentTypes))];
|
||||
}
|
||||
|
||||
#pragma mark - NSCopying
|
||||
|
||||
- (instancetype)copyWithZone:(NSZone *)zone {
|
||||
AFHTTPResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
|
||||
serializer.acceptableStatusCodes = [self.acceptableStatusCodes copyWithZone:zone];
|
||||
serializer.acceptableContentTypes = [self.acceptableContentTypes copyWithZone:zone];
|
||||
|
||||
return serializer;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@implementation AFJSONResponseSerializer
|
||||
|
||||
+ (instancetype)serializer {
|
||||
return [self serializerWithReadingOptions:(NSJSONReadingOptions)0];
|
||||
}
|
||||
|
||||
+ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions {
|
||||
AFJSONResponseSerializer *serializer = [[self alloc] init];
|
||||
serializer.readingOptions = readingOptions;
|
||||
|
||||
return serializer;
|
||||
}
|
||||
|
||||
- (instancetype)init {
|
||||
self = [super init];
|
||||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
#pragma mark - AFURLResponseSerialization
|
||||
|
||||
- (id)responseObjectForResponse:(NSURLResponse *)response
|
||||
data:(NSData *)data
|
||||
error:(NSError *__autoreleasing *)error
|
||||
{
|
||||
if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
|
||||
if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
|
||||
return nil;
|
||||
}
|
||||
}
|
||||
|
||||
// Workaround for behavior of Rails to return a single space for `head :ok` (a workaround for a bug in Safari), which is not interpreted as valid input by NSJSONSerialization.
|
||||
// See https://github.com/rails/rails/issues/1742
|
||||
BOOL isSpace = [data isEqualToData:[NSData dataWithBytes:" " length:1]];
|
||||
|
||||
if (data.length == 0 || isSpace) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSError *serializationError = nil;
|
||||
|
||||
id responseObject = [NSJSONSerialization JSONObjectWithData:data options:self.readingOptions error:&serializationError];
|
||||
|
||||
if (!responseObject)
|
||||
{
|
||||
if (error) {
|
||||
*error = AFErrorWithUnderlyingError(serializationError, *error);
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
if (self.removesKeysWithNullValues) {
|
||||
return AFJSONObjectByRemovingKeysWithNullValues(responseObject, self.readingOptions);
|
||||
}
|
||||
|
||||
return responseObject;
|
||||
}
|
||||
|
||||
#pragma mark - NSSecureCoding
|
||||
|
||||
+ (BOOL)supportsSecureCoding {
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (instancetype)initWithCoder:(NSCoder *)decoder {
|
||||
self = [super initWithCoder:decoder];
|
||||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
self.readingOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readingOptions))] unsignedIntegerValue];
|
||||
self.removesKeysWithNullValues = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(removesKeysWithNullValues))] boolValue];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)encodeWithCoder:(NSCoder *)coder {
|
||||
[super encodeWithCoder:coder];
|
||||
|
||||
[coder encodeObject:@(self.readingOptions) forKey:NSStringFromSelector(@selector(readingOptions))];
|
||||
[coder encodeObject:@(self.removesKeysWithNullValues) forKey:NSStringFromSelector(@selector(removesKeysWithNullValues))];
|
||||
}
|
||||
|
||||
#pragma mark - NSCopying
|
||||
|
||||
- (instancetype)copyWithZone:(NSZone *)zone {
|
||||
AFJSONResponseSerializer *serializer = [super copyWithZone:zone];
|
||||
serializer.readingOptions = self.readingOptions;
|
||||
serializer.removesKeysWithNullValues = self.removesKeysWithNullValues;
|
||||
|
||||
return serializer;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@implementation AFXMLParserResponseSerializer
|
||||
|
||||
+ (instancetype)serializer {
|
||||
AFXMLParserResponseSerializer *serializer = [[self alloc] init];
|
||||
|
||||
return serializer;
|
||||
}
|
||||
|
||||
- (instancetype)init {
|
||||
self = [super init];
|
||||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
#pragma mark - AFURLResponseSerialization
|
||||
|
||||
- (id)responseObjectForResponse:(NSHTTPURLResponse *)response
|
||||
data:(NSData *)data
|
||||
error:(NSError *__autoreleasing *)error
|
||||
{
|
||||
if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
|
||||
if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
|
||||
return nil;
|
||||
}
|
||||
}
|
||||
|
||||
return [[NSXMLParser alloc] initWithData:data];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
|
||||
|
||||
@implementation AFXMLDocumentResponseSerializer
|
||||
|
||||
+ (instancetype)serializer {
|
||||
return [self serializerWithXMLDocumentOptions:0];
|
||||
}
|
||||
|
||||
+ (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask {
|
||||
AFXMLDocumentResponseSerializer *serializer = [[self alloc] init];
|
||||
serializer.options = mask;
|
||||
|
||||
return serializer;
|
||||
}
|
||||
|
||||
- (instancetype)init {
|
||||
self = [super init];
|
||||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
#pragma mark - AFURLResponseSerialization
|
||||
|
||||
- (id)responseObjectForResponse:(NSURLResponse *)response
|
||||
data:(NSData *)data
|
||||
error:(NSError *__autoreleasing *)error
|
||||
{
|
||||
if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
|
||||
if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
|
||||
return nil;
|
||||
}
|
||||
}
|
||||
|
||||
NSError *serializationError = nil;
|
||||
NSXMLDocument *document = [[NSXMLDocument alloc] initWithData:data options:self.options error:&serializationError];
|
||||
|
||||
if (!document)
|
||||
{
|
||||
if (error) {
|
||||
*error = AFErrorWithUnderlyingError(serializationError, *error);
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
return document;
|
||||
}
|
||||
|
||||
#pragma mark - NSSecureCoding
|
||||
|
||||
- (instancetype)initWithCoder:(NSCoder *)decoder {
|
||||
self = [super initWithCoder:decoder];
|
||||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
self.options = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(options))] unsignedIntegerValue];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)encodeWithCoder:(NSCoder *)coder {
|
||||
[super encodeWithCoder:coder];
|
||||
|
||||
[coder encodeObject:@(self.options) forKey:NSStringFromSelector(@selector(options))];
|
||||
}
|
||||
|
||||
#pragma mark - NSCopying
|
||||
|
||||
- (instancetype)copyWithZone:(NSZone *)zone {
|
||||
AFXMLDocumentResponseSerializer *serializer = [super copyWithZone:zone];
|
||||
serializer.options = self.options;
|
||||
|
||||
return serializer;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@implementation AFPropertyListResponseSerializer
|
||||
|
||||
+ (instancetype)serializer {
|
||||
return [self serializerWithFormat:NSPropertyListXMLFormat_v1_0 readOptions:0];
|
||||
}
|
||||
|
||||
+ (instancetype)serializerWithFormat:(NSPropertyListFormat)format
|
||||
readOptions:(NSPropertyListReadOptions)readOptions
|
||||
{
|
||||
AFPropertyListResponseSerializer *serializer = [[self alloc] init];
|
||||
serializer.format = format;
|
||||
serializer.readOptions = readOptions;
|
||||
|
||||
return serializer;
|
||||
}
|
||||
|
||||
- (instancetype)init {
|
||||
self = [super init];
|
||||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/x-plist", nil];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
#pragma mark - AFURLResponseSerialization
|
||||
|
||||
- (id)responseObjectForResponse:(NSURLResponse *)response
|
||||
data:(NSData *)data
|
||||
error:(NSError *__autoreleasing *)error
|
||||
{
|
||||
if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
|
||||
if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
|
||||
return nil;
|
||||
}
|
||||
}
|
||||
|
||||
if (!data) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSError *serializationError = nil;
|
||||
|
||||
id responseObject = [NSPropertyListSerialization propertyListWithData:data options:self.readOptions format:NULL error:&serializationError];
|
||||
|
||||
if (!responseObject)
|
||||
{
|
||||
if (error) {
|
||||
*error = AFErrorWithUnderlyingError(serializationError, *error);
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
return responseObject;
|
||||
}
|
||||
|
||||
#pragma mark - NSSecureCoding
|
||||
|
||||
+ (BOOL)supportsSecureCoding {
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (instancetype)initWithCoder:(NSCoder *)decoder {
|
||||
self = [super initWithCoder:decoder];
|
||||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
self.format = (NSPropertyListFormat)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue];
|
||||
self.readOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readOptions))] unsignedIntegerValue];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)encodeWithCoder:(NSCoder *)coder {
|
||||
[super encodeWithCoder:coder];
|
||||
|
||||
[coder encodeObject:@(self.format) forKey:NSStringFromSelector(@selector(format))];
|
||||
[coder encodeObject:@(self.readOptions) forKey:NSStringFromSelector(@selector(readOptions))];
|
||||
}
|
||||
|
||||
#pragma mark - NSCopying
|
||||
|
||||
- (instancetype)copyWithZone:(NSZone *)zone {
|
||||
AFPropertyListResponseSerializer *serializer = [super copyWithZone:zone];
|
||||
serializer.format = self.format;
|
||||
serializer.readOptions = self.readOptions;
|
||||
|
||||
return serializer;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
|
||||
#import <CoreGraphics/CoreGraphics.h>
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
@interface UIImage (AFNetworkingSafeImageLoading)
|
||||
+ (UIImage *)af_safeImageWithData:(NSData *)data;
|
||||
@end
|
||||
|
||||
static NSLock* imageLock = nil;
|
||||
|
||||
@implementation UIImage (AFNetworkingSafeImageLoading)
|
||||
|
||||
+ (UIImage *)af_safeImageWithData:(NSData *)data {
|
||||
UIImage* image = nil;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
imageLock = [[NSLock alloc] init];
|
||||
});
|
||||
|
||||
[imageLock lock];
|
||||
image = [UIImage imageWithData:data];
|
||||
[imageLock unlock];
|
||||
return image;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
static UIImage * AFImageWithDataAtScale(NSData *data, CGFloat scale) {
|
||||
UIImage *image = [UIImage af_safeImageWithData:data];
|
||||
if (image.images) {
|
||||
return image;
|
||||
}
|
||||
|
||||
return [[UIImage alloc] initWithCGImage:[image CGImage] scale:scale orientation:image.imageOrientation];
|
||||
}
|
||||
|
||||
static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *response, NSData *data, CGFloat scale) {
|
||||
if (!data || [data length] == 0) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
CGImageRef imageRef = NULL;
|
||||
CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data);
|
||||
|
||||
if ([response.MIMEType isEqualToString:@"image/png"]) {
|
||||
imageRef = CGImageCreateWithPNGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault);
|
||||
} else if ([response.MIMEType isEqualToString:@"image/jpeg"]) {
|
||||
imageRef = CGImageCreateWithJPEGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault);
|
||||
|
||||
if (imageRef) {
|
||||
CGColorSpaceRef imageColorSpace = CGImageGetColorSpace(imageRef);
|
||||
CGColorSpaceModel imageColorSpaceModel = CGColorSpaceGetModel(imageColorSpace);
|
||||
|
||||
// CGImageCreateWithJPEGDataProvider does not properly handle CMKY, so fall back to AFImageWithDataAtScale
|
||||
if (imageColorSpaceModel == kCGColorSpaceModelCMYK) {
|
||||
CGImageRelease(imageRef);
|
||||
imageRef = NULL;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
CGDataProviderRelease(dataProvider);
|
||||
|
||||
UIImage *image = AFImageWithDataAtScale(data, scale);
|
||||
if (!imageRef) {
|
||||
if (image.images || !image) {
|
||||
return image;
|
||||
}
|
||||
|
||||
imageRef = CGImageCreateCopy([image CGImage]);
|
||||
if (!imageRef) {
|
||||
return nil;
|
||||
}
|
||||
}
|
||||
|
||||
size_t width = CGImageGetWidth(imageRef);
|
||||
size_t height = CGImageGetHeight(imageRef);
|
||||
size_t bitsPerComponent = CGImageGetBitsPerComponent(imageRef);
|
||||
|
||||
if (width * height > 1024 * 1024 || bitsPerComponent > 8) {
|
||||
CGImageRelease(imageRef);
|
||||
|
||||
return image;
|
||||
}
|
||||
|
||||
// CGImageGetBytesPerRow() calculates incorrectly in iOS 5.0, so defer to CGBitmapContextCreate
|
||||
size_t bytesPerRow = 0;
|
||||
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
|
||||
CGColorSpaceModel colorSpaceModel = CGColorSpaceGetModel(colorSpace);
|
||||
CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);
|
||||
|
||||
if (colorSpaceModel == kCGColorSpaceModelRGB) {
|
||||
uint32_t alpha = (bitmapInfo & kCGBitmapAlphaInfoMask);
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wassign-enum"
|
||||
if (alpha == kCGImageAlphaNone) {
|
||||
bitmapInfo &= ~kCGBitmapAlphaInfoMask;
|
||||
bitmapInfo |= kCGImageAlphaNoneSkipFirst;
|
||||
} else if (!(alpha == kCGImageAlphaNoneSkipFirst || alpha == kCGImageAlphaNoneSkipLast)) {
|
||||
bitmapInfo &= ~kCGBitmapAlphaInfoMask;
|
||||
bitmapInfo |= kCGImageAlphaPremultipliedFirst;
|
||||
}
|
||||
#pragma clang diagnostic pop
|
||||
}
|
||||
|
||||
CGContextRef context = CGBitmapContextCreate(NULL, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo);
|
||||
|
||||
CGColorSpaceRelease(colorSpace);
|
||||
|
||||
if (!context) {
|
||||
CGImageRelease(imageRef);
|
||||
|
||||
return image;
|
||||
}
|
||||
|
||||
CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, width, height), imageRef);
|
||||
CGImageRef inflatedImageRef = CGBitmapContextCreateImage(context);
|
||||
|
||||
CGContextRelease(context);
|
||||
|
||||
UIImage *inflatedImage = [[UIImage alloc] initWithCGImage:inflatedImageRef scale:scale orientation:image.imageOrientation];
|
||||
|
||||
CGImageRelease(inflatedImageRef);
|
||||
CGImageRelease(imageRef);
|
||||
|
||||
return inflatedImage;
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
@implementation AFImageResponseSerializer
|
||||
|
||||
- (instancetype)init {
|
||||
self = [super init];
|
||||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon", @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap", nil];
|
||||
|
||||
#if TARGET_OS_IOS || TARGET_OS_TV
|
||||
self.imageScale = [[UIScreen mainScreen] scale];
|
||||
self.automaticallyInflatesResponseImage = YES;
|
||||
#elif TARGET_OS_WATCH
|
||||
self.imageScale = [[WKInterfaceDevice currentDevice] screenScale];
|
||||
self.automaticallyInflatesResponseImage = YES;
|
||||
#endif
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
#pragma mark - AFURLResponseSerializer
|
||||
|
||||
- (id)responseObjectForResponse:(NSURLResponse *)response
|
||||
data:(NSData *)data
|
||||
error:(NSError *__autoreleasing *)error
|
||||
{
|
||||
if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
|
||||
if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
|
||||
return nil;
|
||||
}
|
||||
}
|
||||
|
||||
#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
|
||||
if (self.automaticallyInflatesResponseImage) {
|
||||
return AFInflatedImageFromResponseWithDataAtScale((NSHTTPURLResponse *)response, data, self.imageScale);
|
||||
} else {
|
||||
return AFImageWithDataAtScale(data, self.imageScale);
|
||||
}
|
||||
#else
|
||||
// Ensure that the image is set to it's correct pixel width and height
|
||||
NSBitmapImageRep *bitimage = [[NSBitmapImageRep alloc] initWithData:data];
|
||||
NSImage *image = [[NSImage alloc] initWithSize:NSMakeSize([bitimage pixelsWide], [bitimage pixelsHigh])];
|
||||
[image addRepresentation:bitimage];
|
||||
|
||||
return image;
|
||||
#endif
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
#pragma mark - NSSecureCoding
|
||||
|
||||
+ (BOOL)supportsSecureCoding {
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (instancetype)initWithCoder:(NSCoder *)decoder {
|
||||
self = [super initWithCoder:decoder];
|
||||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
|
||||
NSNumber *imageScale = [decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(imageScale))];
|
||||
#if CGFLOAT_IS_DOUBLE
|
||||
self.imageScale = [imageScale doubleValue];
|
||||
#else
|
||||
self.imageScale = [imageScale floatValue];
|
||||
#endif
|
||||
|
||||
self.automaticallyInflatesResponseImage = [decoder decodeBoolForKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))];
|
||||
#endif
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)encodeWithCoder:(NSCoder *)coder {
|
||||
[super encodeWithCoder:coder];
|
||||
|
||||
#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
|
||||
[coder encodeObject:@(self.imageScale) forKey:NSStringFromSelector(@selector(imageScale))];
|
||||
[coder encodeBool:self.automaticallyInflatesResponseImage forKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))];
|
||||
#endif
|
||||
}
|
||||
|
||||
#pragma mark - NSCopying
|
||||
|
||||
- (instancetype)copyWithZone:(NSZone *)zone {
|
||||
AFImageResponseSerializer *serializer = [super copyWithZone:zone];
|
||||
|
||||
#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
|
||||
serializer.imageScale = self.imageScale;
|
||||
serializer.automaticallyInflatesResponseImage = self.automaticallyInflatesResponseImage;
|
||||
#endif
|
||||
|
||||
return serializer;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@interface AFCompoundResponseSerializer ()
|
||||
@property (readwrite, nonatomic, copy) NSArray *responseSerializers;
|
||||
@end
|
||||
|
||||
@implementation AFCompoundResponseSerializer
|
||||
|
||||
+ (instancetype)compoundSerializerWithResponseSerializers:(NSArray *)responseSerializers {
|
||||
AFCompoundResponseSerializer *serializer = [[self alloc] init];
|
||||
serializer.responseSerializers = responseSerializers;
|
||||
|
||||
return serializer;
|
||||
}
|
||||
|
||||
#pragma mark - AFURLResponseSerialization
|
||||
|
||||
- (id)responseObjectForResponse:(NSURLResponse *)response
|
||||
data:(NSData *)data
|
||||
error:(NSError *__autoreleasing *)error
|
||||
{
|
||||
for (id <AFURLResponseSerialization> serializer in self.responseSerializers) {
|
||||
if (![serializer isKindOfClass:[AFHTTPResponseSerializer class]]) {
|
||||
continue;
|
||||
}
|
||||
|
||||
NSError *serializerError = nil;
|
||||
id responseObject = [serializer responseObjectForResponse:response data:data error:&serializerError];
|
||||
if (responseObject) {
|
||||
if (error) {
|
||||
*error = AFErrorWithUnderlyingError(serializerError, *error);
|
||||
}
|
||||
|
||||
return responseObject;
|
||||
}
|
||||
}
|
||||
|
||||
return [super responseObjectForResponse:response data:data error:error];
|
||||
}
|
||||
|
||||
#pragma mark - NSSecureCoding
|
||||
|
||||
+ (BOOL)supportsSecureCoding {
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (instancetype)initWithCoder:(NSCoder *)decoder {
|
||||
self = [super initWithCoder:decoder];
|
||||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSSet *classes = [NSSet setWithArray:@[[NSArray class], [AFHTTPResponseSerializer <AFURLResponseSerialization> class]]];
|
||||
self.responseSerializers = [decoder decodeObjectOfClasses:classes forKey:NSStringFromSelector(@selector(responseSerializers))];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)encodeWithCoder:(NSCoder *)coder {
|
||||
[super encodeWithCoder:coder];
|
||||
|
||||
[coder encodeObject:self.responseSerializers forKey:NSStringFromSelector(@selector(responseSerializers))];
|
||||
}
|
||||
|
||||
#pragma mark - NSCopying
|
||||
|
||||
- (instancetype)copyWithZone:(NSZone *)zone {
|
||||
AFCompoundResponseSerializer *serializer = [super copyWithZone:zone];
|
||||
serializer.responseSerializers = self.responseSerializers;
|
||||
|
||||
return serializer;
|
||||
}
|
||||
|
||||
@end
|
||||
516
Pods/AFNetworking/AFNetworking/AFURLSessionManager.h
generated
Normal file
516
Pods/AFNetworking/AFNetworking/AFURLSessionManager.h
generated
Normal file
@@ -0,0 +1,516 @@
|
||||
// AFURLSessionManager.h
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#import "AFURLResponseSerialization.h"
|
||||
#import "AFURLRequestSerialization.h"
|
||||
#import "AFSecurityPolicy.h"
|
||||
#import "AFCompatibilityMacros.h"
|
||||
#if !TARGET_OS_WATCH
|
||||
#import "AFNetworkReachabilityManager.h"
|
||||
#endif
|
||||
|
||||
/**
|
||||
`AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to `<NSURLSessionTaskDelegate>`, `<NSURLSessionDataDelegate>`, `<NSURLSessionDownloadDelegate>`, and `<NSURLSessionDelegate>`.
|
||||
|
||||
## Subclassing Notes
|
||||
|
||||
This is the base class for `AFHTTPSessionManager`, which adds functionality specific to making HTTP requests. If you are looking to extend `AFURLSessionManager` specifically for HTTP, consider subclassing `AFHTTPSessionManager` instead.
|
||||
|
||||
## NSURLSession & NSURLSessionTask Delegate Methods
|
||||
|
||||
`AFURLSessionManager` implements the following delegate methods:
|
||||
|
||||
### `NSURLSessionDelegate`
|
||||
|
||||
- `URLSession:didBecomeInvalidWithError:`
|
||||
- `URLSession:didReceiveChallenge:completionHandler:`
|
||||
- `URLSessionDidFinishEventsForBackgroundURLSession:`
|
||||
|
||||
### `NSURLSessionTaskDelegate`
|
||||
|
||||
- `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:`
|
||||
- `URLSession:task:didReceiveChallenge:completionHandler:`
|
||||
- `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`
|
||||
- `URLSession:task:needNewBodyStream:`
|
||||
- `URLSession:task:didCompleteWithError:`
|
||||
|
||||
### `NSURLSessionDataDelegate`
|
||||
|
||||
- `URLSession:dataTask:didReceiveResponse:completionHandler:`
|
||||
- `URLSession:dataTask:didBecomeDownloadTask:`
|
||||
- `URLSession:dataTask:didReceiveData:`
|
||||
- `URLSession:dataTask:willCacheResponse:completionHandler:`
|
||||
|
||||
### `NSURLSessionDownloadDelegate`
|
||||
|
||||
- `URLSession:downloadTask:didFinishDownloadingToURL:`
|
||||
- `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:`
|
||||
- `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`
|
||||
|
||||
If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first.
|
||||
|
||||
## Network Reachability Monitoring
|
||||
|
||||
Network reachability status and change monitoring is available through the `reachabilityManager` property. Applications may choose to monitor network reachability conditions in order to prevent or suspend any outbound requests. See `AFNetworkReachabilityManager` for more details.
|
||||
|
||||
## NSCoding Caveats
|
||||
|
||||
- Encoded managers do not include any block properties. Be sure to set delegate callback blocks when using `-initWithCoder:` or `NSKeyedUnarchiver`.
|
||||
|
||||
## NSCopying Caveats
|
||||
|
||||
- `-copy` and `-copyWithZone:` return a new manager with a new `NSURLSession` created from the configuration of the original.
|
||||
- Operation copies do not include any delegate callback blocks, as they often strongly captures a reference to `self`, which would otherwise have the unintuitive side-effect of pointing to the _original_ session manager when copied.
|
||||
|
||||
@warning Managers for background sessions must be owned for the duration of their use. This can be accomplished by creating an application-wide or shared singleton instance.
|
||||
*/
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface AFURLSessionManager : NSObject <NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate, NSSecureCoding, NSCopying>
|
||||
|
||||
/**
|
||||
The managed session.
|
||||
*/
|
||||
@property (readonly, nonatomic, strong) NSURLSession *session;
|
||||
|
||||
/**
|
||||
The operation queue on which delegate callbacks are run.
|
||||
*/
|
||||
@property (readonly, nonatomic, strong) NSOperationQueue *operationQueue;
|
||||
|
||||
/**
|
||||
Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to an instance of `AFJSONResponseSerializer`.
|
||||
|
||||
@warning `responseSerializer` must not be `nil`.
|
||||
*/
|
||||
@property (nonatomic, strong) id <AFURLResponseSerialization> responseSerializer;
|
||||
|
||||
///-------------------------------
|
||||
/// @name Managing Security Policy
|
||||
///-------------------------------
|
||||
|
||||
/**
|
||||
The security policy used by created session to evaluate server trust for secure connections. `AFURLSessionManager` uses the `defaultPolicy` unless otherwise specified.
|
||||
*/
|
||||
@property (nonatomic, strong) AFSecurityPolicy *securityPolicy;
|
||||
|
||||
#if !TARGET_OS_WATCH
|
||||
///--------------------------------------
|
||||
/// @name Monitoring Network Reachability
|
||||
///--------------------------------------
|
||||
|
||||
/**
|
||||
The network reachability manager. `AFURLSessionManager` uses the `sharedManager` by default.
|
||||
*/
|
||||
@property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager;
|
||||
#endif
|
||||
|
||||
///----------------------------
|
||||
/// @name Getting Session Tasks
|
||||
///----------------------------
|
||||
|
||||
/**
|
||||
The data, upload, and download tasks currently run by the managed session.
|
||||
*/
|
||||
@property (readonly, nonatomic, strong) NSArray <NSURLSessionTask *> *tasks;
|
||||
|
||||
/**
|
||||
The data tasks currently run by the managed session.
|
||||
*/
|
||||
@property (readonly, nonatomic, strong) NSArray <NSURLSessionDataTask *> *dataTasks;
|
||||
|
||||
/**
|
||||
The upload tasks currently run by the managed session.
|
||||
*/
|
||||
@property (readonly, nonatomic, strong) NSArray <NSURLSessionUploadTask *> *uploadTasks;
|
||||
|
||||
/**
|
||||
The download tasks currently run by the managed session.
|
||||
*/
|
||||
@property (readonly, nonatomic, strong) NSArray <NSURLSessionDownloadTask *> *downloadTasks;
|
||||
|
||||
///-------------------------------
|
||||
/// @name Managing Callback Queues
|
||||
///-------------------------------
|
||||
|
||||
/**
|
||||
The dispatch queue for `completionBlock`. If `NULL` (default), the main queue is used.
|
||||
*/
|
||||
@property (nonatomic, strong, nullable) dispatch_queue_t completionQueue;
|
||||
|
||||
/**
|
||||
The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used.
|
||||
*/
|
||||
@property (nonatomic, strong, nullable) dispatch_group_t completionGroup;
|
||||
|
||||
///---------------------
|
||||
/// @name Initialization
|
||||
///---------------------
|
||||
|
||||
/**
|
||||
Creates and returns a manager for a session created with the specified configuration. This is the designated initializer.
|
||||
|
||||
@param configuration The configuration used to create the managed session.
|
||||
|
||||
@return A manager for a newly-created session.
|
||||
*/
|
||||
- (instancetype)initWithSessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER;
|
||||
|
||||
/**
|
||||
Invalidates the managed session, optionally canceling pending tasks and optionally resets given session.
|
||||
|
||||
@param cancelPendingTasks Whether or not to cancel pending tasks.
|
||||
@param resetSession Whether or not to reset the session of the manager.
|
||||
*/
|
||||
- (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks resetSession:(BOOL)resetSession;
|
||||
|
||||
///-------------------------
|
||||
/// @name Running Data Tasks
|
||||
///-------------------------
|
||||
|
||||
/**
|
||||
Creates an `NSURLSessionDataTask` with the specified request.
|
||||
|
||||
@param request The HTTP request for the request.
|
||||
@param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.
|
||||
@param downloadProgressBlock A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue.
|
||||
@param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any.
|
||||
*/
|
||||
- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
|
||||
uploadProgress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock
|
||||
downloadProgress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock
|
||||
completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler;
|
||||
|
||||
///---------------------------
|
||||
/// @name Running Upload Tasks
|
||||
///---------------------------
|
||||
|
||||
/**
|
||||
Creates an `NSURLSessionUploadTask` with the specified request for a local file.
|
||||
|
||||
@param request The HTTP request for the request.
|
||||
@param fileURL A URL to the local file to be uploaded.
|
||||
@param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.
|
||||
@param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any.
|
||||
|
||||
@see `attemptsToRecreateUploadTasksForBackgroundSessions`
|
||||
*/
|
||||
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
|
||||
fromFile:(NSURL *)fileURL
|
||||
progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock
|
||||
completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler;
|
||||
|
||||
/**
|
||||
Creates an `NSURLSessionUploadTask` with the specified request for an HTTP body.
|
||||
|
||||
@param request The HTTP request for the request.
|
||||
@param bodyData A data object containing the HTTP body to be uploaded.
|
||||
@param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.
|
||||
@param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any.
|
||||
*/
|
||||
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
|
||||
fromData:(nullable NSData *)bodyData
|
||||
progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock
|
||||
completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler;
|
||||
|
||||
/**
|
||||
Creates an `NSURLSessionUploadTask` with the specified streaming request.
|
||||
|
||||
@param request The HTTP request for the request.
|
||||
@param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.
|
||||
@param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any.
|
||||
*/
|
||||
- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request
|
||||
progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock
|
||||
completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler;
|
||||
|
||||
///-----------------------------
|
||||
/// @name Running Download Tasks
|
||||
///-----------------------------
|
||||
|
||||
/**
|
||||
Creates an `NSURLSessionDownloadTask` with the specified request.
|
||||
|
||||
@param request The HTTP request for the request.
|
||||
@param downloadProgressBlock A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue.
|
||||
@param destination A block object to be executed in order to determine the destination of the downloaded file. This block takes two arguments, the target path & the server response, and returns the desired file URL of the resulting download. The temporary file used during the download will be automatically deleted after being moved to the returned URL.
|
||||
@param completionHandler A block to be executed when a task finishes. This block has no return value and takes three arguments: the server response, the path of the downloaded file, and the error describing the network or parsing error that occurred, if any.
|
||||
|
||||
@warning If using a background `NSURLSessionConfiguration` on iOS, these blocks will be lost when the app is terminated. Background sessions may prefer to use `-setDownloadTaskDidFinishDownloadingBlock:` to specify the URL for saving the downloaded file, rather than the destination block of this method.
|
||||
*/
|
||||
- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request
|
||||
progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock
|
||||
destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
|
||||
completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * _Nullable filePath, NSError * _Nullable error))completionHandler;
|
||||
|
||||
/**
|
||||
Creates an `NSURLSessionDownloadTask` with the specified resume data.
|
||||
|
||||
@param resumeData The data used to resume downloading.
|
||||
@param downloadProgressBlock A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue.
|
||||
@param destination A block object to be executed in order to determine the destination of the downloaded file. This block takes two arguments, the target path & the server response, and returns the desired file URL of the resulting download. The temporary file used during the download will be automatically deleted after being moved to the returned URL.
|
||||
@param completionHandler A block to be executed when a task finishes. This block has no return value and takes three arguments: the server response, the path of the downloaded file, and the error describing the network or parsing error that occurred, if any.
|
||||
*/
|
||||
- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData
|
||||
progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock
|
||||
destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
|
||||
completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * _Nullable filePath, NSError * _Nullable error))completionHandler;
|
||||
|
||||
///---------------------------------
|
||||
/// @name Getting Progress for Tasks
|
||||
///---------------------------------
|
||||
|
||||
/**
|
||||
Returns the upload progress of the specified task.
|
||||
|
||||
@param task The session task. Must not be `nil`.
|
||||
|
||||
@return An `NSProgress` object reporting the upload progress of a task, or `nil` if the progress is unavailable.
|
||||
*/
|
||||
- (nullable NSProgress *)uploadProgressForTask:(NSURLSessionTask *)task;
|
||||
|
||||
/**
|
||||
Returns the download progress of the specified task.
|
||||
|
||||
@param task The session task. Must not be `nil`.
|
||||
|
||||
@return An `NSProgress` object reporting the download progress of a task, or `nil` if the progress is unavailable.
|
||||
*/
|
||||
- (nullable NSProgress *)downloadProgressForTask:(NSURLSessionTask *)task;
|
||||
|
||||
///-----------------------------------------
|
||||
/// @name Setting Session Delegate Callbacks
|
||||
///-----------------------------------------
|
||||
|
||||
/**
|
||||
Sets a block to be executed when the managed session becomes invalid, as handled by the `NSURLSessionDelegate` method `URLSession:didBecomeInvalidWithError:`.
|
||||
|
||||
@param block A block object to be executed when the managed session becomes invalid. The block has no return value, and takes two arguments: the session, and the error related to the cause of invalidation.
|
||||
*/
|
||||
- (void)setSessionDidBecomeInvalidBlock:(nullable void (^)(NSURLSession *session, NSError *error))block;
|
||||
|
||||
/**
|
||||
Sets a block to be executed when a connection level authentication challenge has occurred, as handled by the `NSURLSessionDelegate` method `URLSession:didReceiveChallenge:completionHandler:`.
|
||||
|
||||
@param block A block object to be executed when a connection level authentication challenge has occurred. The block returns the disposition of the authentication challenge, and takes three arguments: the session, the authentication challenge, and a pointer to the credential that should be used to resolve the challenge.
|
||||
|
||||
@warning Implementing a session authentication challenge handler yourself totally bypasses AFNetworking's security policy defined in `AFSecurityPolicy`. Make sure you fully understand the implications before implementing a custom session authentication challenge handler. If you do not want to bypass AFNetworking's security policy, use `setTaskDidReceiveAuthenticationChallengeBlock:` instead.
|
||||
|
||||
@see -securityPolicy
|
||||
@see -setTaskDidReceiveAuthenticationChallengeBlock:
|
||||
*/
|
||||
- (void)setSessionDidReceiveAuthenticationChallengeBlock:(nullable NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * _Nullable __autoreleasing * _Nullable credential))block;
|
||||
|
||||
///--------------------------------------
|
||||
/// @name Setting Task Delegate Callbacks
|
||||
///--------------------------------------
|
||||
|
||||
/**
|
||||
Sets a block to be executed when a task requires a new request body stream to send to the remote server, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:needNewBodyStream:`.
|
||||
|
||||
@param block A block object to be executed when a task requires a new request body stream.
|
||||
*/
|
||||
- (void)setTaskNeedNewBodyStreamBlock:(nullable NSInputStream * (^)(NSURLSession *session, NSURLSessionTask *task))block;
|
||||
|
||||
/**
|
||||
Sets a block to be executed when an HTTP request is attempting to perform a redirection to a different URL, as handled by the `NSURLSessionTaskDelegate` method `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:`.
|
||||
|
||||
@param block A block object to be executed when an HTTP request is attempting to perform a redirection to a different URL. The block returns the request to be made for the redirection, and takes four arguments: the session, the task, the redirection response, and the request corresponding to the redirection response.
|
||||
*/
|
||||
- (void)setTaskWillPerformHTTPRedirectionBlock:(nullable NSURLRequest * _Nullable (^)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request))block;
|
||||
|
||||
/**
|
||||
Sets a block to be executed when a session task has received a request specific authentication challenge, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didReceiveChallenge:completionHandler:`.
|
||||
|
||||
@param authenticationChallengeHandler A block object to be executed when a session task has received a request specific authentication challenge.
|
||||
|
||||
When implementing an authentication challenge handler, you should check the authentication method first (`challenge.protectionSpace.authenticationMethod `) to decide if you want to handle the authentication challenge yourself or if you want AFNetworking to handle it. If you want AFNetworking to handle the authentication challenge, just return `@(NSURLSessionAuthChallengePerformDefaultHandling)`. For example, you certainly want AFNetworking to handle certificate validation (i.e. authentication method == `NSURLAuthenticationMethodServerTrust`) as defined by the security policy. If you want to handle the challenge yourself, you have four options:
|
||||
|
||||
1. Return `nil` from the authentication challenge handler. You **MUST** call the completion handler with a disposition and credentials yourself. Use this if you need to present a user interface to let the user enter their credentials.
|
||||
2. Return an `NSError` object from the authentication challenge handler. You **MUST NOT** call the completion handler when returning an `NSError `. The returned error will be reported in the completion handler of the task. Use this if you need to abort an authentication challenge with a specific error.
|
||||
3. Return an `NSURLCredential` object from the authentication challenge handler. You **MUST NOT** call the completion handler when returning an `NSURLCredential`. The returned credentials will be used to fulfil the challenge. Use this when you can get credentials without presenting a user interface.
|
||||
4. Return an `NSNumber` object wrapping an `NSURLSessionAuthChallengeDisposition`. Supported values are `@(NSURLSessionAuthChallengePerformDefaultHandling)`, `@(NSURLSessionAuthChallengeCancelAuthenticationChallenge)` and `@(NSURLSessionAuthChallengeRejectProtectionSpace)`. You **MUST NOT** call the completion handler when returning an `NSNumber`.
|
||||
|
||||
If you return anything else from the authentication challenge handler, an exception will be thrown.
|
||||
|
||||
For more information about how URL sessions handle the different types of authentication challenges, see [NSURLSession](https://developer.apple.com/reference/foundation/nsurlsession?language=objc) and [URL Session Programming Guide](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html).
|
||||
|
||||
@see -securityPolicy
|
||||
*/
|
||||
- (void)setAuthenticationChallengeHandler:(id (^)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, void (^completionHandler)(NSURLSessionAuthChallengeDisposition , NSURLCredential * _Nullable)))authenticationChallengeHandler;
|
||||
|
||||
/**
|
||||
Sets a block to be executed periodically to track upload progress, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`.
|
||||
|
||||
@param block A block object to be called when an undetermined number of bytes have been uploaded to the server. This block has no return value and takes five arguments: the session, the task, the number of bytes written since the last time the upload progress block was called, the total bytes written, and the total bytes expected to be written during the request, as initially determined by the length of the HTTP body. This block may be called multiple times, and will execute on the main thread.
|
||||
*/
|
||||
- (void)setTaskDidSendBodyDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))block;
|
||||
|
||||
/**
|
||||
Sets a block to be executed as the last message related to a specific task, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didCompleteWithError:`.
|
||||
|
||||
@param block A block object to be executed when a session task is completed. The block has no return value, and takes three arguments: the session, the task, and any error that occurred in the process of executing the task.
|
||||
*/
|
||||
- (void)setTaskDidCompleteBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, NSError * _Nullable error))block;
|
||||
|
||||
/**
|
||||
Sets a block to be executed when metrics are finalized related to a specific task, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didFinishCollectingMetrics:`.
|
||||
|
||||
@param block A block object to be executed when a session task is completed. The block has no return value, and takes three arguments: the session, the task, and any metrics that were collected in the process of executing the task.
|
||||
*/
|
||||
#if AF_CAN_INCLUDE_SESSION_TASK_METRICS
|
||||
- (void)setTaskDidFinishCollectingMetricsBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, NSURLSessionTaskMetrics * _Nullable metrics))block AF_API_AVAILABLE(ios(10), macosx(10.12), watchos(3), tvos(10));
|
||||
#endif
|
||||
///-------------------------------------------
|
||||
/// @name Setting Data Task Delegate Callbacks
|
||||
///-------------------------------------------
|
||||
|
||||
/**
|
||||
Sets a block to be executed when a data task has received a response, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveResponse:completionHandler:`.
|
||||
|
||||
@param block A block object to be executed when a data task has received a response. The block returns the disposition of the session response, and takes three arguments: the session, the data task, and the received response.
|
||||
*/
|
||||
- (void)setDataTaskDidReceiveResponseBlock:(nullable NSURLSessionResponseDisposition (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response))block;
|
||||
|
||||
/**
|
||||
Sets a block to be executed when a data task has become a download task, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didBecomeDownloadTask:`.
|
||||
|
||||
@param block A block object to be executed when a data task has become a download task. The block has no return value, and takes three arguments: the session, the data task, and the download task it has become.
|
||||
*/
|
||||
- (void)setDataTaskDidBecomeDownloadTaskBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask))block;
|
||||
|
||||
/**
|
||||
Sets a block to be executed when a data task receives data, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveData:`.
|
||||
|
||||
@param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes three arguments: the session, the data task, and the data received. This block may be called multiple times, and will execute on the session manager operation queue.
|
||||
*/
|
||||
- (void)setDataTaskDidReceiveDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data))block;
|
||||
|
||||
/**
|
||||
Sets a block to be executed to determine the caching behavior of a data task, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:willCacheResponse:completionHandler:`.
|
||||
|
||||
@param block A block object to be executed to determine the caching behavior of a data task. The block returns the response to cache, and takes three arguments: the session, the data task, and the proposed cached URL response.
|
||||
*/
|
||||
- (void)setDataTaskWillCacheResponseBlock:(nullable NSCachedURLResponse * (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse))block;
|
||||
|
||||
/**
|
||||
Sets a block to be executed once all messages enqueued for a session have been delivered, as handled by the `NSURLSessionDataDelegate` method `URLSessionDidFinishEventsForBackgroundURLSession:`.
|
||||
|
||||
@param block A block object to be executed once all messages enqueued for a session have been delivered. The block has no return value and takes a single argument: the session.
|
||||
*/
|
||||
- (void)setDidFinishEventsForBackgroundURLSessionBlock:(nullable void (^)(NSURLSession *session))block AF_API_UNAVAILABLE(macos);
|
||||
|
||||
///-----------------------------------------------
|
||||
/// @name Setting Download Task Delegate Callbacks
|
||||
///-----------------------------------------------
|
||||
|
||||
/**
|
||||
Sets a block to be executed when a download task has completed a download, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didFinishDownloadingToURL:`.
|
||||
|
||||
@param block A block object to be executed when a download task has completed. The block returns the URL the download should be moved to, and takes three arguments: the session, the download task, and the temporary location of the downloaded file. If the file manager encounters an error while attempting to move the temporary file to the destination, an `AFURLSessionDownloadTaskDidFailToMoveFileNotification` will be posted, with the download task as its object, and the user info of the error.
|
||||
*/
|
||||
- (void)setDownloadTaskDidFinishDownloadingBlock:(nullable NSURL * _Nullable (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block;
|
||||
|
||||
/**
|
||||
Sets a block to be executed periodically to track download progress, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:`.
|
||||
|
||||
@param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes five arguments: the session, the download task, the number of bytes read since the last time the download progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times, and will execute on the session manager operation queue.
|
||||
*/
|
||||
- (void)setDownloadTaskDidWriteDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite))block;
|
||||
|
||||
/**
|
||||
Sets a block to be executed when a download task has been resumed, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`.
|
||||
|
||||
@param block A block object to be executed when a download task has been resumed. The block has no return value and takes four arguments: the session, the download task, the file offset of the resumed download, and the total number of bytes expected to be downloaded.
|
||||
*/
|
||||
- (void)setDownloadTaskDidResumeBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes))block;
|
||||
|
||||
@end
|
||||
|
||||
///--------------------
|
||||
/// @name Notifications
|
||||
///--------------------
|
||||
|
||||
/**
|
||||
Posted when a task resumes.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidResumeNotification;
|
||||
|
||||
/**
|
||||
Posted when a task finishes executing. Includes a userInfo dictionary with additional information about the task.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteNotification;
|
||||
|
||||
/**
|
||||
Posted when a task suspends its execution.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidSuspendNotification;
|
||||
|
||||
/**
|
||||
Posted when a session is invalidated.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFURLSessionDidInvalidateNotification;
|
||||
|
||||
/**
|
||||
Posted when a session download task finished moving the temporary download file to a specified destination successfully.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFURLSessionDownloadTaskDidMoveFileSuccessfullyNotification;
|
||||
|
||||
/**
|
||||
Posted when a session download task encountered an error when moving the temporary download file to a specified destination.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification;
|
||||
|
||||
/**
|
||||
The raw response data of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if response data exists for the task.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteResponseDataKey;
|
||||
|
||||
/**
|
||||
The serialized response object of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if the response was serialized.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey;
|
||||
|
||||
/**
|
||||
The response serializer used to serialize the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if the task has an associated response serializer.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey;
|
||||
|
||||
/**
|
||||
The file path associated with the download task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if an the response data has been stored directly to disk.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteAssetPathKey;
|
||||
|
||||
/**
|
||||
Any error associated with the task, or the serialization of the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if an error exists.
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteErrorKey;
|
||||
|
||||
/**
|
||||
The session task metrics taken from the download task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteSessionTaskMetrics`
|
||||
*/
|
||||
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteSessionTaskMetrics;
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
1274
Pods/AFNetworking/AFNetworking/AFURLSessionManager.m
generated
Normal file
1274
Pods/AFNetworking/AFNetworking/AFURLSessionManager.m
generated
Normal file
File diff suppressed because it is too large
Load Diff
19
Pods/AFNetworking/LICENSE
generated
Normal file
19
Pods/AFNetworking/LICENSE
generated
Normal file
@@ -0,0 +1,19 @@
|
||||
Copyright (c) 2011-2020 Alamofire Software Foundation (http://alamofire.org/)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
298
Pods/AFNetworking/README.md
generated
Normal file
298
Pods/AFNetworking/README.md
generated
Normal file
@@ -0,0 +1,298 @@
|
||||
<p align="center" >
|
||||
<img src="https://raw.github.com/AFNetworking/AFNetworking/assets/afnetworking-logo.png" alt="AFNetworking" title="AFNetworking">
|
||||
</p>
|
||||
|
||||
[](https://github.com/AFNetworking/AFNetworking/actions)
|
||||
[](https://img.shields.io/cocoapods/v/AFNetworking.svg)
|
||||
[](https://github.com/Carthage/Carthage)
|
||||
[](http://cocoadocs.org/docsets/AFNetworking)
|
||||
[](http://twitter.com/AFNetworking)
|
||||
|
||||
AFNetworking is a delightful networking library for iOS, macOS, watchOS, and tvOS. It's built on top of the [Foundation URL Loading System](https://developer.apple.com/documentation/foundation/url_loading_system), extending the powerful high-level networking abstractions built into Cocoa. It has a modular architecture with well-designed, feature-rich APIs that are a joy to use.
|
||||
|
||||
Perhaps the most important feature of all, however, is the amazing community of developers who use and contribute to AFNetworking every day. AFNetworking powers some of the most popular and critically-acclaimed apps on the iPhone, iPad, and Mac.
|
||||
|
||||
## How To Get Started
|
||||
|
||||
- [Download AFNetworking](https://github.com/AFNetworking/AFNetworking/archive/master.zip) and try out the included Mac and iPhone example apps
|
||||
- Read the ["Getting Started" guide](https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking), [FAQ](https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ), or [other articles on the Wiki](https://github.com/AFNetworking/AFNetworking/wiki)
|
||||
|
||||
## Communication
|
||||
|
||||
- If you **need help**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/afnetworking). (Tag 'afnetworking')
|
||||
- If you'd like to **ask a general question**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/afnetworking).
|
||||
- If you **found a bug**, _and can provide steps to reliably reproduce it_, open an issue.
|
||||
- If you **have a feature request**, open an issue.
|
||||
- If you **want to contribute**, submit a pull request.
|
||||
|
||||
## Installation
|
||||
AFNetworking supports multiple methods for installing the library in a project.
|
||||
|
||||
## Installation with CocoaPods
|
||||
|
||||
To integrate AFNetworking into your Xcode project using CocoaPods, specify it in your `Podfile`:
|
||||
|
||||
```ruby
|
||||
pod 'AFNetworking', '~> 4.0'
|
||||
```
|
||||
|
||||
### Installation with Swift Package Manager
|
||||
|
||||
Once you have your Swift package set up, adding AFNetworking as a dependency is as easy as adding it to the `dependencies` value of your `Package.swift`.
|
||||
|
||||
```swift
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/AFNetworking/AFNetworking.git", .upToNextMajor(from: "4.0.0"))
|
||||
]
|
||||
```
|
||||
|
||||
> Note: AFNetworking's Swift package does not include it's UIKit extensions.
|
||||
|
||||
### Installation with Carthage
|
||||
|
||||
[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. To integrate AFNetworking, add the following to your `Cartfile`.
|
||||
|
||||
```ogdl
|
||||
github "AFNetworking/AFNetworking" ~> 4.0
|
||||
```
|
||||
|
||||
## Requirements
|
||||
|
||||
| AFNetworking Version | Minimum iOS Target | Minimum macOS Target | Minimum watchOS Target | Minimum tvOS Target | Notes |
|
||||
|:--------------------:|:---------------------------:|:----------------------------:|:----------------------------:|:----------------------------:|:-------------------------------------------------------------------------:|
|
||||
| 4.x | iOS 9 | macOS 10.10 | watchOS 2.0 | tvOS 9.0 | Xcode 11+ is required. |
|
||||
| 3.x | iOS 7 | OS X 10.9 | watchOS 2.0 | tvOS 9.0 | Xcode 7+ is required. `NSURLConnectionOperation` support has been removed. |
|
||||
| 2.6 -> 2.6.3 | iOS 7 | OS X 10.9 | watchOS 2.0 | n/a | Xcode 7+ is required. |
|
||||
| 2.0 -> 2.5.4 | iOS 6 | OS X 10.8 | n/a | n/a | Xcode 5+ is required. `NSURLSession` subspec requires iOS 7 or OS X 10.9. |
|
||||
| 1.x | iOS 5 | Mac OS X 10.7 | n/a | n/a |
|
||||
| 0.10.x | iOS 4 | Mac OS X 10.6 | n/a | n/a |
|
||||
|
||||
(macOS projects must support [64-bit with modern Cocoa runtime](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtVersionsPlatforms.html)).
|
||||
|
||||
> Programming in Swift? Try [Alamofire](https://github.com/Alamofire/Alamofire) for a more conventional set of APIs.
|
||||
|
||||
## Architecture
|
||||
|
||||
### NSURLSession
|
||||
|
||||
- `AFURLSessionManager`
|
||||
- `AFHTTPSessionManager`
|
||||
|
||||
### Serialization
|
||||
|
||||
* `<AFURLRequestSerialization>`
|
||||
- `AFHTTPRequestSerializer`
|
||||
- `AFJSONRequestSerializer`
|
||||
- `AFPropertyListRequestSerializer`
|
||||
* `<AFURLResponseSerialization>`
|
||||
- `AFHTTPResponseSerializer`
|
||||
- `AFJSONResponseSerializer`
|
||||
- `AFXMLParserResponseSerializer`
|
||||
- `AFXMLDocumentResponseSerializer` _(macOS)_
|
||||
- `AFPropertyListResponseSerializer`
|
||||
- `AFImageResponseSerializer`
|
||||
- `AFCompoundResponseSerializer`
|
||||
|
||||
### Additional Functionality
|
||||
|
||||
- `AFSecurityPolicy`
|
||||
- `AFNetworkReachabilityManager`
|
||||
|
||||
## Usage
|
||||
|
||||
### AFURLSessionManager
|
||||
|
||||
`AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to `<NSURLSessionTaskDelegate>`, `<NSURLSessionDataDelegate>`, `<NSURLSessionDownloadDelegate>`, and `<NSURLSessionDelegate>`.
|
||||
|
||||
#### Creating a Download Task
|
||||
|
||||
```objective-c
|
||||
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
|
||||
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
|
||||
|
||||
NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"];
|
||||
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
|
||||
|
||||
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
|
||||
NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
|
||||
return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
|
||||
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
|
||||
NSLog(@"File downloaded to: %@", filePath);
|
||||
}];
|
||||
[downloadTask resume];
|
||||
```
|
||||
|
||||
#### Creating an Upload Task
|
||||
|
||||
```objective-c
|
||||
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
|
||||
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
|
||||
|
||||
NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
|
||||
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
|
||||
|
||||
NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
|
||||
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
|
||||
if (error) {
|
||||
NSLog(@"Error: %@", error);
|
||||
} else {
|
||||
NSLog(@"Success: %@ %@", response, responseObject);
|
||||
}
|
||||
}];
|
||||
[uploadTask resume];
|
||||
```
|
||||
|
||||
#### Creating an Upload Task for a Multi-Part Request, with Progress
|
||||
|
||||
```objective-c
|
||||
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
|
||||
[formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
|
||||
} error:nil];
|
||||
|
||||
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
|
||||
|
||||
NSURLSessionUploadTask *uploadTask;
|
||||
uploadTask = [manager
|
||||
uploadTaskWithStreamedRequest:request
|
||||
progress:^(NSProgress * _Nonnull uploadProgress) {
|
||||
// This is not called back on the main queue.
|
||||
// You are responsible for dispatching to the main queue for UI updates
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
//Update the progress view
|
||||
[progressView setProgress:uploadProgress.fractionCompleted];
|
||||
});
|
||||
}
|
||||
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
|
||||
if (error) {
|
||||
NSLog(@"Error: %@", error);
|
||||
} else {
|
||||
NSLog(@"%@ %@", response, responseObject);
|
||||
}
|
||||
}];
|
||||
|
||||
[uploadTask resume];
|
||||
```
|
||||
|
||||
#### Creating a Data Task
|
||||
|
||||
```objective-c
|
||||
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
|
||||
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
|
||||
|
||||
NSURL *URL = [NSURL URLWithString:@"http://httpbin.org/get"];
|
||||
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
|
||||
|
||||
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
|
||||
if (error) {
|
||||
NSLog(@"Error: %@", error);
|
||||
} else {
|
||||
NSLog(@"%@ %@", response, responseObject);
|
||||
}
|
||||
}];
|
||||
[dataTask resume];
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Request Serialization
|
||||
|
||||
Request serializers create requests from URL strings, encoding parameters as either a query string or HTTP body.
|
||||
|
||||
```objective-c
|
||||
NSString *URLString = @"http://example.com";
|
||||
NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]};
|
||||
```
|
||||
|
||||
#### Query String Parameter Encoding
|
||||
|
||||
```objective-c
|
||||
[[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil];
|
||||
```
|
||||
|
||||
GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3
|
||||
|
||||
#### URL Form Parameter Encoding
|
||||
|
||||
```objective-c
|
||||
[[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil];
|
||||
```
|
||||
|
||||
POST http://example.com/
|
||||
Content-Type: application/x-www-form-urlencoded
|
||||
|
||||
foo=bar&baz[]=1&baz[]=2&baz[]=3
|
||||
|
||||
#### JSON Parameter Encoding
|
||||
|
||||
```objective-c
|
||||
[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil];
|
||||
```
|
||||
|
||||
POST http://example.com/
|
||||
Content-Type: application/json
|
||||
|
||||
{"foo": "bar", "baz": [1,2,3]}
|
||||
|
||||
---
|
||||
|
||||
### Network Reachability Manager
|
||||
|
||||
`AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces.
|
||||
|
||||
* Do not use Reachability to determine if the original request should be sent.
|
||||
* You should try to send it.
|
||||
* You can use Reachability to determine when a request should be automatically retried.
|
||||
* Although it may still fail, a Reachability notification that the connectivity is available is a good time to retry something.
|
||||
* Network reachability is a useful tool for determining why a request might have failed.
|
||||
* After a network request has failed, telling the user they're offline is better than giving them a more technical but accurate error, such as "request timed out."
|
||||
|
||||
See also [WWDC 2012 session 706, "Networking Best Practices."](https://developer.apple.com/videos/play/wwdc2012-706/).
|
||||
|
||||
#### Shared Network Reachability
|
||||
|
||||
```objective-c
|
||||
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
|
||||
NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
|
||||
}];
|
||||
|
||||
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Security Policy
|
||||
|
||||
`AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections.
|
||||
|
||||
Adding pinned SSL certificates to your app helps prevent man-in-the-middle attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with SSL pinning configured and enabled.
|
||||
|
||||
#### Allowing Invalid SSL Certificates
|
||||
|
||||
```objective-c
|
||||
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
|
||||
manager.securityPolicy.allowInvalidCertificates = YES; // not recommended for production
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Unit Tests
|
||||
|
||||
AFNetworking includes a suite of unit tests within the Tests subdirectory. These tests can be run simply be executed the test action on the platform framework you would like to test.
|
||||
|
||||
## Credits
|
||||
|
||||
AFNetworking is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org).
|
||||
|
||||
AFNetworking was originally created by [Scott Raymond](https://github.com/sco/) and [Mattt Thompson](https://github.com/mattt/) in the development of [Gowalla for iPhone](http://en.wikipedia.org/wiki/Gowalla).
|
||||
|
||||
AFNetworking's logo was designed by [Alan Defibaugh](http://www.alandefibaugh.com/).
|
||||
|
||||
And most of all, thanks to AFNetworking's [growing list of contributors](https://github.com/AFNetworking/AFNetworking/contributors).
|
||||
|
||||
### Security Disclosure
|
||||
|
||||
If you believe you have identified a security vulnerability with AFNetworking, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker.
|
||||
|
||||
## License
|
||||
|
||||
AFNetworking is released under the MIT license. See [LICENSE](https://github.com/AFNetworking/AFNetworking/blob/master/LICENSE) for details.
|
||||
160
Pods/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.h
generated
Normal file
160
Pods/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.h
generated
Normal file
@@ -0,0 +1,160 @@
|
||||
// AFAutoPurgingImageCache.h
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import <TargetConditionals.h>
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#if TARGET_OS_IOS || TARGET_OS_TV
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/**
|
||||
The `AFImageCache` protocol defines a set of APIs for adding, removing and fetching images from a cache synchronously.
|
||||
*/
|
||||
@protocol AFImageCache <NSObject>
|
||||
|
||||
/**
|
||||
Adds the image to the cache with the given identifier.
|
||||
|
||||
@param image The image to cache.
|
||||
@param identifier The unique identifier for the image in the cache.
|
||||
*/
|
||||
- (void)addImage:(UIImage *)image withIdentifier:(NSString *)identifier;
|
||||
|
||||
/**
|
||||
Removes the image from the cache matching the given identifier.
|
||||
|
||||
@param identifier The unique identifier for the image in the cache.
|
||||
|
||||
@return A BOOL indicating whether or not the image was removed from the cache.
|
||||
*/
|
||||
- (BOOL)removeImageWithIdentifier:(NSString *)identifier;
|
||||
|
||||
/**
|
||||
Removes all images from the cache.
|
||||
|
||||
@return A BOOL indicating whether or not all images were removed from the cache.
|
||||
*/
|
||||
- (BOOL)removeAllImages;
|
||||
|
||||
/**
|
||||
Returns the image in the cache associated with the given identifier.
|
||||
|
||||
@param identifier The unique identifier for the image in the cache.
|
||||
|
||||
@return An image for the matching identifier, or nil.
|
||||
*/
|
||||
- (nullable UIImage *)imageWithIdentifier:(NSString *)identifier;
|
||||
@end
|
||||
|
||||
|
||||
/**
|
||||
The `ImageRequestCache` protocol extends the `ImageCache` protocol by adding methods for adding, removing and fetching images from a cache given an `NSURLRequest` and additional identifier.
|
||||
*/
|
||||
@protocol AFImageRequestCache <AFImageCache>
|
||||
|
||||
/**
|
||||
Asks if the image should be cached using an identifier created from the request and additional identifier.
|
||||
|
||||
@param image The image to be cached.
|
||||
@param request The unique URL request identifing the image asset.
|
||||
@param identifier The additional identifier to apply to the URL request to identify the image.
|
||||
|
||||
@return A BOOL indicating whether or not the image should be added to the cache. YES will cache, NO will prevent caching.
|
||||
*/
|
||||
- (BOOL)shouldCacheImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier;
|
||||
|
||||
/**
|
||||
Adds the image to the cache using an identifier created from the request and additional identifier.
|
||||
|
||||
@param image The image to cache.
|
||||
@param request The unique URL request identifing the image asset.
|
||||
@param identifier The additional identifier to apply to the URL request to identify the image.
|
||||
*/
|
||||
- (void)addImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier;
|
||||
|
||||
/**
|
||||
Removes the image from the cache using an identifier created from the request and additional identifier.
|
||||
|
||||
@param request The unique URL request identifing the image asset.
|
||||
@param identifier The additional identifier to apply to the URL request to identify the image.
|
||||
|
||||
@return A BOOL indicating whether or not all images were removed from the cache.
|
||||
*/
|
||||
- (BOOL)removeImageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier;
|
||||
|
||||
/**
|
||||
Returns the image from the cache associated with an identifier created from the request and additional identifier.
|
||||
|
||||
@param request The unique URL request identifing the image asset.
|
||||
@param identifier The additional identifier to apply to the URL request to identify the image.
|
||||
|
||||
@return An image for the matching request and identifier, or nil.
|
||||
*/
|
||||
- (nullable UIImage *)imageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier;
|
||||
|
||||
@end
|
||||
|
||||
/**
|
||||
The `AutoPurgingImageCache` in an in-memory image cache used to store images up to a given memory capacity. When the memory capacity is reached, the image cache is sorted by last access date, then the oldest image is continuously purged until the preferred memory usage after purge is met. Each time an image is accessed through the cache, the internal access date of the image is updated.
|
||||
*/
|
||||
@interface AFAutoPurgingImageCache : NSObject <AFImageRequestCache>
|
||||
|
||||
/**
|
||||
The total memory capacity of the cache in bytes.
|
||||
*/
|
||||
@property (nonatomic, assign) UInt64 memoryCapacity;
|
||||
|
||||
/**
|
||||
The preferred memory usage after purge in bytes. During a purge, images will be purged until the memory capacity drops below this limit.
|
||||
*/
|
||||
@property (nonatomic, assign) UInt64 preferredMemoryUsageAfterPurge;
|
||||
|
||||
/**
|
||||
The current total memory usage in bytes of all images stored within the cache.
|
||||
*/
|
||||
@property (nonatomic, assign, readonly) UInt64 memoryUsage;
|
||||
|
||||
/**
|
||||
Initialies the `AutoPurgingImageCache` instance with default values for memory capacity and preferred memory usage after purge limit. `memoryCapcity` defaults to `100 MB`. `preferredMemoryUsageAfterPurge` defaults to `60 MB`.
|
||||
|
||||
@return The new `AutoPurgingImageCache` instance.
|
||||
*/
|
||||
- (instancetype)init;
|
||||
|
||||
/**
|
||||
Initialies the `AutoPurgingImageCache` instance with the given memory capacity and preferred memory usage
|
||||
after purge limit.
|
||||
|
||||
@param memoryCapacity The total memory capacity of the cache in bytes.
|
||||
@param preferredMemoryCapacity The preferred memory usage after purge in bytes.
|
||||
|
||||
@return The new `AutoPurgingImageCache` instance.
|
||||
*/
|
||||
- (instancetype)initWithMemoryCapacity:(UInt64)memoryCapacity preferredMemoryCapacity:(UInt64)preferredMemoryCapacity;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
#endif
|
||||
|
||||
205
Pods/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.m
generated
Normal file
205
Pods/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.m
generated
Normal file
@@ -0,0 +1,205 @@
|
||||
// AFAutoPurgingImageCache.m
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import <TargetConditionals.h>
|
||||
|
||||
#if TARGET_OS_IOS || TARGET_OS_TV
|
||||
|
||||
#import "AFAutoPurgingImageCache.h"
|
||||
|
||||
@interface AFCachedImage : NSObject
|
||||
|
||||
@property (nonatomic, strong) UIImage *image;
|
||||
@property (nonatomic, copy) NSString *identifier;
|
||||
@property (nonatomic, assign) UInt64 totalBytes;
|
||||
@property (nonatomic, strong) NSDate *lastAccessDate;
|
||||
@property (nonatomic, assign) UInt64 currentMemoryUsage;
|
||||
|
||||
@end
|
||||
|
||||
@implementation AFCachedImage
|
||||
|
||||
- (instancetype)initWithImage:(UIImage *)image identifier:(NSString *)identifier {
|
||||
if (self = [self init]) {
|
||||
self.image = image;
|
||||
self.identifier = identifier;
|
||||
|
||||
CGSize imageSize = CGSizeMake(image.size.width * image.scale, image.size.height * image.scale);
|
||||
CGFloat bytesPerPixel = 4.0;
|
||||
CGFloat bytesPerSize = imageSize.width * imageSize.height;
|
||||
self.totalBytes = (UInt64)bytesPerPixel * (UInt64)bytesPerSize;
|
||||
self.lastAccessDate = [NSDate date];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (UIImage *)accessImage {
|
||||
self.lastAccessDate = [NSDate date];
|
||||
return self.image;
|
||||
}
|
||||
|
||||
- (NSString *)description {
|
||||
NSString *descriptionString = [NSString stringWithFormat:@"Idenfitier: %@ lastAccessDate: %@ ", self.identifier, self.lastAccessDate];
|
||||
return descriptionString;
|
||||
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@interface AFAutoPurgingImageCache ()
|
||||
@property (nonatomic, strong) NSMutableDictionary <NSString* , AFCachedImage*> *cachedImages;
|
||||
@property (nonatomic, assign) UInt64 currentMemoryUsage;
|
||||
@property (nonatomic, strong) dispatch_queue_t synchronizationQueue;
|
||||
@end
|
||||
|
||||
@implementation AFAutoPurgingImageCache
|
||||
|
||||
- (instancetype)init {
|
||||
return [self initWithMemoryCapacity:100 * 1024 * 1024 preferredMemoryCapacity:60 * 1024 * 1024];
|
||||
}
|
||||
|
||||
- (instancetype)initWithMemoryCapacity:(UInt64)memoryCapacity preferredMemoryCapacity:(UInt64)preferredMemoryCapacity {
|
||||
if (self = [super init]) {
|
||||
self.memoryCapacity = memoryCapacity;
|
||||
self.preferredMemoryUsageAfterPurge = preferredMemoryCapacity;
|
||||
self.cachedImages = [[NSMutableDictionary alloc] init];
|
||||
|
||||
NSString *queueName = [NSString stringWithFormat:@"com.alamofire.autopurgingimagecache-%@", [[NSUUID UUID] UUIDString]];
|
||||
self.synchronizationQueue = dispatch_queue_create([queueName cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_CONCURRENT);
|
||||
|
||||
[[NSNotificationCenter defaultCenter]
|
||||
addObserver:self
|
||||
selector:@selector(removeAllImages)
|
||||
name:UIApplicationDidReceiveMemoryWarningNotification
|
||||
object:nil];
|
||||
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)dealloc {
|
||||
[[NSNotificationCenter defaultCenter] removeObserver:self];
|
||||
}
|
||||
|
||||
- (UInt64)memoryUsage {
|
||||
__block UInt64 result = 0;
|
||||
dispatch_sync(self.synchronizationQueue, ^{
|
||||
result = self.currentMemoryUsage;
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
- (void)addImage:(UIImage *)image withIdentifier:(NSString *)identifier {
|
||||
dispatch_barrier_async(self.synchronizationQueue, ^{
|
||||
AFCachedImage *cacheImage = [[AFCachedImage alloc] initWithImage:image identifier:identifier];
|
||||
|
||||
AFCachedImage *previousCachedImage = self.cachedImages[identifier];
|
||||
if (previousCachedImage != nil) {
|
||||
self.currentMemoryUsage -= previousCachedImage.totalBytes;
|
||||
}
|
||||
|
||||
self.cachedImages[identifier] = cacheImage;
|
||||
self.currentMemoryUsage += cacheImage.totalBytes;
|
||||
});
|
||||
|
||||
dispatch_barrier_async(self.synchronizationQueue, ^{
|
||||
if (self.currentMemoryUsage > self.memoryCapacity) {
|
||||
UInt64 bytesToPurge = self.currentMemoryUsage - self.preferredMemoryUsageAfterPurge;
|
||||
NSMutableArray <AFCachedImage*> *sortedImages = [NSMutableArray arrayWithArray:self.cachedImages.allValues];
|
||||
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"lastAccessDate"
|
||||
ascending:YES];
|
||||
[sortedImages sortUsingDescriptors:@[sortDescriptor]];
|
||||
|
||||
UInt64 bytesPurged = 0;
|
||||
|
||||
for (AFCachedImage *cachedImage in sortedImages) {
|
||||
[self.cachedImages removeObjectForKey:cachedImage.identifier];
|
||||
bytesPurged += cachedImage.totalBytes;
|
||||
if (bytesPurged >= bytesToPurge) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
self.currentMemoryUsage -= bytesPurged;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
- (BOOL)removeImageWithIdentifier:(NSString *)identifier {
|
||||
__block BOOL removed = NO;
|
||||
dispatch_barrier_sync(self.synchronizationQueue, ^{
|
||||
AFCachedImage *cachedImage = self.cachedImages[identifier];
|
||||
if (cachedImage != nil) {
|
||||
[self.cachedImages removeObjectForKey:identifier];
|
||||
self.currentMemoryUsage -= cachedImage.totalBytes;
|
||||
removed = YES;
|
||||
}
|
||||
});
|
||||
return removed;
|
||||
}
|
||||
|
||||
- (BOOL)removeAllImages {
|
||||
__block BOOL removed = NO;
|
||||
dispatch_barrier_sync(self.synchronizationQueue, ^{
|
||||
if (self.cachedImages.count > 0) {
|
||||
[self.cachedImages removeAllObjects];
|
||||
self.currentMemoryUsage = 0;
|
||||
removed = YES;
|
||||
}
|
||||
});
|
||||
return removed;
|
||||
}
|
||||
|
||||
- (nullable UIImage *)imageWithIdentifier:(NSString *)identifier {
|
||||
__block UIImage *image = nil;
|
||||
dispatch_sync(self.synchronizationQueue, ^{
|
||||
AFCachedImage *cachedImage = self.cachedImages[identifier];
|
||||
image = [cachedImage accessImage];
|
||||
});
|
||||
return image;
|
||||
}
|
||||
|
||||
- (void)addImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier {
|
||||
[self addImage:image withIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]];
|
||||
}
|
||||
|
||||
- (BOOL)removeImageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier {
|
||||
return [self removeImageWithIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]];
|
||||
}
|
||||
|
||||
- (nullable UIImage *)imageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier {
|
||||
return [self imageWithIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]];
|
||||
}
|
||||
|
||||
- (NSString *)imageCacheKeyFromURLRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)additionalIdentifier {
|
||||
NSString *key = request.URL.absoluteString;
|
||||
if (additionalIdentifier != nil) {
|
||||
key = [key stringByAppendingString:additionalIdentifier];
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
- (BOOL)shouldCacheImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier {
|
||||
return YES;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
171
Pods/AFNetworking/UIKit+AFNetworking/AFImageDownloader.h
generated
Normal file
171
Pods/AFNetworking/UIKit+AFNetworking/AFImageDownloader.h
generated
Normal file
@@ -0,0 +1,171 @@
|
||||
// AFImageDownloader.h
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import <TargetConditionals.h>
|
||||
|
||||
#if TARGET_OS_IOS || TARGET_OS_TV
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "AFAutoPurgingImageCache.h"
|
||||
#import "AFHTTPSessionManager.h"
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
typedef NS_ENUM(NSInteger, AFImageDownloadPrioritization) {
|
||||
AFImageDownloadPrioritizationFIFO,
|
||||
AFImageDownloadPrioritizationLIFO
|
||||
};
|
||||
|
||||
/**
|
||||
The `AFImageDownloadReceipt` is an object vended by the `AFImageDownloader` when starting a data task. It can be used to cancel active tasks running on the `AFImageDownloader` session. As a general rule, image data tasks should be cancelled using the `AFImageDownloadReceipt` instead of calling `cancel` directly on the `task` itself. The `AFImageDownloader` is optimized to handle duplicate task scenarios as well as pending versus active downloads.
|
||||
*/
|
||||
@interface AFImageDownloadReceipt : NSObject
|
||||
|
||||
/**
|
||||
The data task created by the `AFImageDownloader`.
|
||||
*/
|
||||
@property (nonatomic, strong) NSURLSessionDataTask *task;
|
||||
|
||||
/**
|
||||
The unique identifier for the success and failure blocks when duplicate requests are made.
|
||||
*/
|
||||
@property (nonatomic, strong) NSUUID *receiptID;
|
||||
@end
|
||||
|
||||
/** The `AFImageDownloader` class is responsible for downloading images in parallel on a prioritized queue. Incoming downloads are added to the front or back of the queue depending on the download prioritization. Each downloaded image is cached in the underlying `NSURLCache` as well as the in-memory image cache. By default, any download request with a cached image equivalent in the image cache will automatically be served the cached image representation.
|
||||
*/
|
||||
@interface AFImageDownloader : NSObject
|
||||
|
||||
/**
|
||||
The image cache used to store all downloaded images in. `AFAutoPurgingImageCache` by default.
|
||||
*/
|
||||
@property (nonatomic, strong, nullable) id <AFImageRequestCache> imageCache;
|
||||
|
||||
/**
|
||||
The `AFHTTPSessionManager` used to download images. By default, this is configured with an `AFImageResponseSerializer`, and a shared `NSURLCache` for all image downloads.
|
||||
*/
|
||||
@property (nonatomic, strong) AFHTTPSessionManager *sessionManager;
|
||||
|
||||
/**
|
||||
Defines the order prioritization of incoming download requests being inserted into the queue. `AFImageDownloadPrioritizationFIFO` by default.
|
||||
*/
|
||||
@property (nonatomic, assign) AFImageDownloadPrioritization downloadPrioritization;
|
||||
|
||||
/**
|
||||
The shared default instance of `AFImageDownloader` initialized with default values.
|
||||
*/
|
||||
+ (instancetype)defaultInstance;
|
||||
|
||||
/**
|
||||
Creates a default `NSURLCache` with common usage parameter values.
|
||||
|
||||
@returns The default `NSURLCache` instance.
|
||||
*/
|
||||
+ (NSURLCache *)defaultURLCache;
|
||||
|
||||
/**
|
||||
The default `NSURLSessionConfiguration` with common usage parameter values.
|
||||
*/
|
||||
+ (NSURLSessionConfiguration *)defaultURLSessionConfiguration;
|
||||
|
||||
/**
|
||||
Default initializer
|
||||
|
||||
@return An instance of `AFImageDownloader` initialized with default values.
|
||||
*/
|
||||
- (instancetype)init;
|
||||
|
||||
/**
|
||||
Initializer with specific `URLSessionConfiguration`
|
||||
|
||||
@param configuration The `NSURLSessionConfiguration` to be be used
|
||||
|
||||
@return An instance of `AFImageDownloader` initialized with default values and custom `NSURLSessionConfiguration`
|
||||
*/
|
||||
- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration;
|
||||
|
||||
/**
|
||||
Initializes the `AFImageDownloader` instance with the given session manager, download prioritization, maximum active download count and image cache.
|
||||
|
||||
@param sessionManager The session manager to use to download images.
|
||||
@param downloadPrioritization The download prioritization of the download queue.
|
||||
@param maximumActiveDownloads The maximum number of active downloads allowed at any given time. Recommend `4`.
|
||||
@param imageCache The image cache used to store all downloaded images in.
|
||||
|
||||
@return The new `AFImageDownloader` instance.
|
||||
*/
|
||||
- (instancetype)initWithSessionManager:(AFHTTPSessionManager *)sessionManager
|
||||
downloadPrioritization:(AFImageDownloadPrioritization)downloadPrioritization
|
||||
maximumActiveDownloads:(NSInteger)maximumActiveDownloads
|
||||
imageCache:(nullable id <AFImageRequestCache>)imageCache;
|
||||
|
||||
/**
|
||||
Creates a data task using the `sessionManager` instance for the specified URL request.
|
||||
|
||||
If the same data task is already in the queue or currently being downloaded, the success and failure blocks are
|
||||
appended to the already existing task. Once the task completes, all success or failure blocks attached to the
|
||||
task are executed in the order they were added.
|
||||
|
||||
@param request The URL request.
|
||||
@param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`.
|
||||
@param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred.
|
||||
|
||||
@return The image download receipt for the data task if available. `nil` if the image is stored in the cache.
|
||||
cache and the URL request cache policy allows the cache to be used.
|
||||
*/
|
||||
- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request
|
||||
success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success
|
||||
failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure;
|
||||
|
||||
/**
|
||||
Creates a data task using the `sessionManager` instance for the specified URL request.
|
||||
|
||||
If the same data task is already in the queue or currently being downloaded, the success and failure blocks are
|
||||
appended to the already existing task. Once the task completes, all success or failure blocks attached to the
|
||||
task are executed in the order they were added.
|
||||
|
||||
@param request The URL request.
|
||||
@param receiptID The identifier to use for the download receipt that will be created for this request. This must be a unique identifier that does not represent any other request.
|
||||
@param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`.
|
||||
@param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred.
|
||||
|
||||
@return The image download receipt for the data task if available. `nil` if the image is stored in the cache.
|
||||
cache and the URL request cache policy allows the cache to be used.
|
||||
*/
|
||||
- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request
|
||||
withReceiptID:(NSUUID *)receiptID
|
||||
success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success
|
||||
failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure;
|
||||
|
||||
/**
|
||||
Cancels the data task in the receipt by removing the corresponding success and failure blocks and cancelling the data task if necessary.
|
||||
|
||||
If the data task is pending in the queue, it will be cancelled if no other success and failure blocks are registered with the data task. If the data task is currently executing or is already completed, the success and failure blocks are removed and will not be called when the task finishes.
|
||||
|
||||
@param imageDownloadReceipt The image download receipt to cancel.
|
||||
*/
|
||||
- (void)cancelTaskForImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt;
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
421
Pods/AFNetworking/UIKit+AFNetworking/AFImageDownloader.m
generated
Normal file
421
Pods/AFNetworking/UIKit+AFNetworking/AFImageDownloader.m
generated
Normal file
@@ -0,0 +1,421 @@
|
||||
// AFImageDownloader.m
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import <TargetConditionals.h>
|
||||
|
||||
#if TARGET_OS_IOS || TARGET_OS_TV
|
||||
|
||||
#import "AFImageDownloader.h"
|
||||
#import "AFHTTPSessionManager.h"
|
||||
|
||||
@interface AFImageDownloaderResponseHandler : NSObject
|
||||
@property (nonatomic, strong) NSUUID *uuid;
|
||||
@property (nonatomic, copy) void (^successBlock)(NSURLRequest *, NSHTTPURLResponse *, UIImage *);
|
||||
@property (nonatomic, copy) void (^failureBlock)(NSURLRequest *, NSHTTPURLResponse *, NSError *);
|
||||
@end
|
||||
|
||||
@implementation AFImageDownloaderResponseHandler
|
||||
|
||||
- (instancetype)initWithUUID:(NSUUID *)uuid
|
||||
success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success
|
||||
failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure {
|
||||
if (self = [self init]) {
|
||||
self.uuid = uuid;
|
||||
self.successBlock = success;
|
||||
self.failureBlock = failure;
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (NSString *)description {
|
||||
return [NSString stringWithFormat: @"<AFImageDownloaderResponseHandler>UUID: %@", [self.uuid UUIDString]];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@interface AFImageDownloaderMergedTask : NSObject
|
||||
@property (nonatomic, strong) NSString *URLIdentifier;
|
||||
@property (nonatomic, strong) NSUUID *identifier;
|
||||
@property (nonatomic, strong) NSURLSessionDataTask *task;
|
||||
@property (nonatomic, strong) NSMutableArray <AFImageDownloaderResponseHandler*> *responseHandlers;
|
||||
|
||||
@end
|
||||
|
||||
@implementation AFImageDownloaderMergedTask
|
||||
|
||||
- (instancetype)initWithURLIdentifier:(NSString *)URLIdentifier identifier:(NSUUID *)identifier task:(NSURLSessionDataTask *)task {
|
||||
if (self = [self init]) {
|
||||
self.URLIdentifier = URLIdentifier;
|
||||
self.task = task;
|
||||
self.identifier = identifier;
|
||||
self.responseHandlers = [[NSMutableArray alloc] init];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)addResponseHandler:(AFImageDownloaderResponseHandler *)handler {
|
||||
[self.responseHandlers addObject:handler];
|
||||
}
|
||||
|
||||
- (void)removeResponseHandler:(AFImageDownloaderResponseHandler *)handler {
|
||||
[self.responseHandlers removeObject:handler];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation AFImageDownloadReceipt
|
||||
|
||||
- (instancetype)initWithReceiptID:(NSUUID *)receiptID task:(NSURLSessionDataTask *)task {
|
||||
if (self = [self init]) {
|
||||
self.receiptID = receiptID;
|
||||
self.task = task;
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@interface AFImageDownloader ()
|
||||
|
||||
@property (nonatomic, strong) dispatch_queue_t synchronizationQueue;
|
||||
@property (nonatomic, strong) dispatch_queue_t responseQueue;
|
||||
|
||||
@property (nonatomic, assign) NSInteger maximumActiveDownloads;
|
||||
@property (nonatomic, assign) NSInteger activeRequestCount;
|
||||
|
||||
@property (nonatomic, strong) NSMutableArray *queuedMergedTasks;
|
||||
@property (nonatomic, strong) NSMutableDictionary *mergedTasks;
|
||||
|
||||
@end
|
||||
|
||||
@implementation AFImageDownloader
|
||||
|
||||
+ (NSURLCache *)defaultURLCache {
|
||||
NSUInteger memoryCapacity = 20 * 1024 * 1024; // 20MB
|
||||
NSUInteger diskCapacity = 150 * 1024 * 1024; // 150MB
|
||||
NSURL *cacheURL = [[[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory
|
||||
inDomain:NSUserDomainMask
|
||||
appropriateForURL:nil
|
||||
create:YES
|
||||
error:nil]
|
||||
URLByAppendingPathComponent:@"com.alamofire.imagedownloader"];
|
||||
|
||||
#if TARGET_OS_MACCATALYST
|
||||
return [[NSURLCache alloc] initWithMemoryCapacity:memoryCapacity
|
||||
diskCapacity:diskCapacity
|
||||
directoryURL:cacheURL];
|
||||
#else
|
||||
return [[NSURLCache alloc] initWithMemoryCapacity:memoryCapacity
|
||||
diskCapacity:diskCapacity
|
||||
diskPath:[cacheURL path]];
|
||||
#endif
|
||||
}
|
||||
|
||||
+ (NSURLSessionConfiguration *)defaultURLSessionConfiguration {
|
||||
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
|
||||
|
||||
//TODO set the default HTTP headers
|
||||
|
||||
configuration.HTTPShouldSetCookies = YES;
|
||||
configuration.HTTPShouldUsePipelining = NO;
|
||||
|
||||
configuration.requestCachePolicy = NSURLRequestUseProtocolCachePolicy;
|
||||
configuration.allowsCellularAccess = YES;
|
||||
configuration.timeoutIntervalForRequest = 60.0;
|
||||
configuration.URLCache = [AFImageDownloader defaultURLCache];
|
||||
|
||||
return configuration;
|
||||
}
|
||||
|
||||
- (instancetype)init {
|
||||
NSURLSessionConfiguration *defaultConfiguration = [self.class defaultURLSessionConfiguration];
|
||||
return [self initWithSessionConfiguration:defaultConfiguration];
|
||||
}
|
||||
|
||||
- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration {
|
||||
AFHTTPSessionManager *sessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration];
|
||||
sessionManager.responseSerializer = [AFImageResponseSerializer serializer];
|
||||
|
||||
return [self initWithSessionManager:sessionManager
|
||||
downloadPrioritization:AFImageDownloadPrioritizationFIFO
|
||||
maximumActiveDownloads:4
|
||||
imageCache:[[AFAutoPurgingImageCache alloc] init]];
|
||||
}
|
||||
|
||||
- (instancetype)initWithSessionManager:(AFHTTPSessionManager *)sessionManager
|
||||
downloadPrioritization:(AFImageDownloadPrioritization)downloadPrioritization
|
||||
maximumActiveDownloads:(NSInteger)maximumActiveDownloads
|
||||
imageCache:(id <AFImageRequestCache>)imageCache {
|
||||
if (self = [super init]) {
|
||||
self.sessionManager = sessionManager;
|
||||
|
||||
self.downloadPrioritization = downloadPrioritization;
|
||||
self.maximumActiveDownloads = maximumActiveDownloads;
|
||||
self.imageCache = imageCache;
|
||||
|
||||
self.queuedMergedTasks = [[NSMutableArray alloc] init];
|
||||
self.mergedTasks = [[NSMutableDictionary alloc] init];
|
||||
self.activeRequestCount = 0;
|
||||
|
||||
NSString *name = [NSString stringWithFormat:@"com.alamofire.imagedownloader.synchronizationqueue-%@", [[NSUUID UUID] UUIDString]];
|
||||
self.synchronizationQueue = dispatch_queue_create([name cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_SERIAL);
|
||||
|
||||
name = [NSString stringWithFormat:@"com.alamofire.imagedownloader.responsequeue-%@", [[NSUUID UUID] UUIDString]];
|
||||
self.responseQueue = dispatch_queue_create([name cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_CONCURRENT);
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
+ (instancetype)defaultInstance {
|
||||
static AFImageDownloader *sharedInstance = nil;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
sharedInstance = [[self alloc] init];
|
||||
});
|
||||
return sharedInstance;
|
||||
}
|
||||
|
||||
- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request
|
||||
success:(void (^)(NSURLRequest * _Nonnull, NSHTTPURLResponse * _Nullable, UIImage * _Nonnull))success
|
||||
failure:(void (^)(NSURLRequest * _Nonnull, NSHTTPURLResponse * _Nullable, NSError * _Nonnull))failure {
|
||||
return [self downloadImageForURLRequest:request withReceiptID:[NSUUID UUID] success:success failure:failure];
|
||||
}
|
||||
|
||||
- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request
|
||||
withReceiptID:(nonnull NSUUID *)receiptID
|
||||
success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success
|
||||
failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure {
|
||||
__block NSURLSessionDataTask *task = nil;
|
||||
dispatch_sync(self.synchronizationQueue, ^{
|
||||
NSString *URLIdentifier = request.URL.absoluteString;
|
||||
if (URLIdentifier == nil) {
|
||||
if (failure) {
|
||||
NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorBadURL userInfo:nil];
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
failure(request, nil, error);
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// 1) Append the success and failure blocks to a pre-existing request if it already exists
|
||||
AFImageDownloaderMergedTask *existingMergedTask = self.mergedTasks[URLIdentifier];
|
||||
if (existingMergedTask != nil) {
|
||||
AFImageDownloaderResponseHandler *handler = [[AFImageDownloaderResponseHandler alloc] initWithUUID:receiptID success:success failure:failure];
|
||||
[existingMergedTask addResponseHandler:handler];
|
||||
task = existingMergedTask.task;
|
||||
return;
|
||||
}
|
||||
|
||||
// 2) Attempt to load the image from the image cache if the cache policy allows it
|
||||
switch (request.cachePolicy) {
|
||||
case NSURLRequestUseProtocolCachePolicy:
|
||||
case NSURLRequestReturnCacheDataElseLoad:
|
||||
case NSURLRequestReturnCacheDataDontLoad: {
|
||||
UIImage *cachedImage = [self.imageCache imageforRequest:request withAdditionalIdentifier:nil];
|
||||
if (cachedImage != nil) {
|
||||
if (success) {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
success(request, nil, cachedImage);
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
// 3) Create the request and set up authentication, validation and response serialization
|
||||
NSUUID *mergedTaskIdentifier = [NSUUID UUID];
|
||||
NSURLSessionDataTask *createdTask;
|
||||
__weak __typeof__(self) weakSelf = self;
|
||||
|
||||
createdTask = [self.sessionManager
|
||||
dataTaskWithRequest:request
|
||||
uploadProgress:nil
|
||||
downloadProgress:nil
|
||||
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
|
||||
dispatch_async(self.responseQueue, ^{
|
||||
__strong __typeof__(weakSelf) strongSelf = weakSelf;
|
||||
AFImageDownloaderMergedTask *mergedTask = [strongSelf safelyGetMergedTask:URLIdentifier];
|
||||
if ([mergedTask.identifier isEqual:mergedTaskIdentifier]) {
|
||||
mergedTask = [strongSelf safelyRemoveMergedTaskWithURLIdentifier:URLIdentifier];
|
||||
if (error) {
|
||||
for (AFImageDownloaderResponseHandler *handler in mergedTask.responseHandlers) {
|
||||
if (handler.failureBlock) {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
handler.failureBlock(request, (NSHTTPURLResponse *)response, error);
|
||||
});
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if ([strongSelf.imageCache shouldCacheImage:responseObject forRequest:request withAdditionalIdentifier:nil]) {
|
||||
[strongSelf.imageCache addImage:responseObject forRequest:request withAdditionalIdentifier:nil];
|
||||
}
|
||||
|
||||
for (AFImageDownloaderResponseHandler *handler in mergedTask.responseHandlers) {
|
||||
if (handler.successBlock) {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
handler.successBlock(request, (NSHTTPURLResponse *)response, responseObject);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
[strongSelf safelyDecrementActiveTaskCount];
|
||||
[strongSelf safelyStartNextTaskIfNecessary];
|
||||
});
|
||||
}];
|
||||
|
||||
// 4) Store the response handler for use when the request completes
|
||||
AFImageDownloaderResponseHandler *handler = [[AFImageDownloaderResponseHandler alloc] initWithUUID:receiptID
|
||||
success:success
|
||||
failure:failure];
|
||||
AFImageDownloaderMergedTask *mergedTask = [[AFImageDownloaderMergedTask alloc]
|
||||
initWithURLIdentifier:URLIdentifier
|
||||
identifier:mergedTaskIdentifier
|
||||
task:createdTask];
|
||||
[mergedTask addResponseHandler:handler];
|
||||
self.mergedTasks[URLIdentifier] = mergedTask;
|
||||
|
||||
// 5) Either start the request or enqueue it depending on the current active request count
|
||||
if ([self isActiveRequestCountBelowMaximumLimit]) {
|
||||
[self startMergedTask:mergedTask];
|
||||
} else {
|
||||
[self enqueueMergedTask:mergedTask];
|
||||
}
|
||||
|
||||
task = mergedTask.task;
|
||||
});
|
||||
if (task) {
|
||||
return [[AFImageDownloadReceipt alloc] initWithReceiptID:receiptID task:task];
|
||||
} else {
|
||||
return nil;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)cancelTaskForImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt {
|
||||
dispatch_sync(self.synchronizationQueue, ^{
|
||||
NSString *URLIdentifier = imageDownloadReceipt.task.originalRequest.URL.absoluteString;
|
||||
AFImageDownloaderMergedTask *mergedTask = self.mergedTasks[URLIdentifier];
|
||||
NSUInteger index = [mergedTask.responseHandlers indexOfObjectPassingTest:^BOOL(AFImageDownloaderResponseHandler * _Nonnull handler, __unused NSUInteger idx, __unused BOOL * _Nonnull stop) {
|
||||
return handler.uuid == imageDownloadReceipt.receiptID;
|
||||
}];
|
||||
|
||||
if (index != NSNotFound) {
|
||||
AFImageDownloaderResponseHandler *handler = mergedTask.responseHandlers[index];
|
||||
[mergedTask removeResponseHandler:handler];
|
||||
NSString *failureReason = [NSString stringWithFormat:@"ImageDownloader cancelled URL request: %@",imageDownloadReceipt.task.originalRequest.URL.absoluteString];
|
||||
NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey:failureReason};
|
||||
NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo];
|
||||
if (handler.failureBlock) {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
handler.failureBlock(imageDownloadReceipt.task.originalRequest, nil, error);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (mergedTask.responseHandlers.count == 0) {
|
||||
[mergedTask.task cancel];
|
||||
[self removeMergedTaskWithURLIdentifier:URLIdentifier];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
- (AFImageDownloaderMergedTask *)safelyRemoveMergedTaskWithURLIdentifier:(NSString *)URLIdentifier {
|
||||
__block AFImageDownloaderMergedTask *mergedTask = nil;
|
||||
dispatch_sync(self.synchronizationQueue, ^{
|
||||
mergedTask = [self removeMergedTaskWithURLIdentifier:URLIdentifier];
|
||||
});
|
||||
return mergedTask;
|
||||
}
|
||||
|
||||
//This method should only be called from safely within the synchronizationQueue
|
||||
- (AFImageDownloaderMergedTask *)removeMergedTaskWithURLIdentifier:(NSString *)URLIdentifier {
|
||||
AFImageDownloaderMergedTask *mergedTask = self.mergedTasks[URLIdentifier];
|
||||
[self.mergedTasks removeObjectForKey:URLIdentifier];
|
||||
return mergedTask;
|
||||
}
|
||||
|
||||
- (void)safelyDecrementActiveTaskCount {
|
||||
dispatch_sync(self.synchronizationQueue, ^{
|
||||
if (self.activeRequestCount > 0) {
|
||||
self.activeRequestCount -= 1;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
- (void)safelyStartNextTaskIfNecessary {
|
||||
dispatch_sync(self.synchronizationQueue, ^{
|
||||
if ([self isActiveRequestCountBelowMaximumLimit]) {
|
||||
while (self.queuedMergedTasks.count > 0) {
|
||||
AFImageDownloaderMergedTask *mergedTask = [self dequeueMergedTask];
|
||||
if (mergedTask.task.state == NSURLSessionTaskStateSuspended) {
|
||||
[self startMergedTask:mergedTask];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
- (void)startMergedTask:(AFImageDownloaderMergedTask *)mergedTask {
|
||||
[mergedTask.task resume];
|
||||
++self.activeRequestCount;
|
||||
}
|
||||
|
||||
- (void)enqueueMergedTask:(AFImageDownloaderMergedTask *)mergedTask {
|
||||
switch (self.downloadPrioritization) {
|
||||
case AFImageDownloadPrioritizationFIFO:
|
||||
[self.queuedMergedTasks addObject:mergedTask];
|
||||
break;
|
||||
case AFImageDownloadPrioritizationLIFO:
|
||||
[self.queuedMergedTasks insertObject:mergedTask atIndex:0];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
- (AFImageDownloaderMergedTask *)dequeueMergedTask {
|
||||
AFImageDownloaderMergedTask *mergedTask = nil;
|
||||
mergedTask = [self.queuedMergedTasks firstObject];
|
||||
[self.queuedMergedTasks removeObject:mergedTask];
|
||||
return mergedTask;
|
||||
}
|
||||
|
||||
- (BOOL)isActiveRequestCountBelowMaximumLimit {
|
||||
return self.activeRequestCount < self.maximumActiveDownloads;
|
||||
}
|
||||
|
||||
- (AFImageDownloaderMergedTask *)safelyGetMergedTask:(NSString *)URLIdentifier {
|
||||
__block AFImageDownloaderMergedTask *mergedTask;
|
||||
dispatch_sync(self.synchronizationQueue, ^(){
|
||||
mergedTask = self.mergedTasks[URLIdentifier];
|
||||
});
|
||||
return mergedTask;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
103
Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h
generated
Normal file
103
Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h
generated
Normal file
@@ -0,0 +1,103 @@
|
||||
// AFNetworkActivityIndicatorManager.h
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#import <TargetConditionals.h>
|
||||
|
||||
#if TARGET_OS_IOS
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/**
|
||||
`AFNetworkActivityIndicatorManager` manages the state of the network activity indicator in the status bar. When enabled, it will listen for notifications indicating that a session task has started or finished, and start or stop animating the indicator accordingly. The number of active requests is incremented and decremented much like a stack or a semaphore, and the activity indicator will animate so long as that number is greater than zero.
|
||||
|
||||
You should enable the shared instance of `AFNetworkActivityIndicatorManager` when your application finishes launching. In `AppDelegate application:didFinishLaunchingWithOptions:` you can do so with the following code:
|
||||
|
||||
[[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
|
||||
|
||||
By setting `enabled` to `YES` for `sharedManager`, the network activity indicator will show and hide automatically as requests start and finish. You should not ever need to call `incrementActivityCount` or `decrementActivityCount` yourself.
|
||||
|
||||
See the Apple Human Interface Guidelines section about the Network Activity Indicator for more information:
|
||||
http://developer.apple.com/library/iOS/#documentation/UserExperience/Conceptual/MobileHIG/UIElementGuidelines/UIElementGuidelines.html#//apple_ref/doc/uid/TP40006556-CH13-SW44
|
||||
*/
|
||||
NS_EXTENSION_UNAVAILABLE_IOS("Use view controller based solutions where appropriate instead.")
|
||||
@interface AFNetworkActivityIndicatorManager : NSObject
|
||||
|
||||
/**
|
||||
A Boolean value indicating whether the manager is enabled.
|
||||
|
||||
If YES, the manager will change status bar network activity indicator according to network operation notifications it receives. The default value is NO.
|
||||
*/
|
||||
@property (nonatomic, assign, getter = isEnabled) BOOL enabled;
|
||||
|
||||
/**
|
||||
A Boolean value indicating whether the network activity indicator manager is currently active.
|
||||
*/
|
||||
@property (readonly, nonatomic, assign, getter=isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible;
|
||||
|
||||
/**
|
||||
A time interval indicating the minimum duration of networking activity that should occur before the activity indicator is displayed. The default value 1 second. If the network activity indicator should be displayed immediately when network activity occurs, this value should be set to 0 seconds.
|
||||
|
||||
Apple's HIG describes the following:
|
||||
|
||||
> Display the network activity indicator to provide feedback when your app accesses the network for more than a couple of seconds. If the operation finishes sooner than that, you don’t have to show the network activity indicator, because the indicator is likely to disappear before users notice its presence.
|
||||
|
||||
*/
|
||||
@property (nonatomic, assign) NSTimeInterval activationDelay;
|
||||
|
||||
/**
|
||||
A time interval indicating the duration of time of no networking activity required before the activity indicator is disabled. This allows for continuous display of the network activity indicator across multiple requests. The default value is 0.17 seconds.
|
||||
*/
|
||||
|
||||
@property (nonatomic, assign) NSTimeInterval completionDelay;
|
||||
|
||||
/**
|
||||
Returns the shared network activity indicator manager object for the system.
|
||||
|
||||
@return The systemwide network activity indicator manager.
|
||||
*/
|
||||
+ (instancetype)sharedManager;
|
||||
|
||||
/**
|
||||
Increments the number of active network requests. If this number was zero before incrementing, this will start animating the status bar network activity indicator.
|
||||
*/
|
||||
- (void)incrementActivityCount;
|
||||
|
||||
/**
|
||||
Decrements the number of active network requests. If this number becomes zero after decrementing, this will stop animating the status bar network activity indicator.
|
||||
*/
|
||||
- (void)decrementActivityCount;
|
||||
|
||||
/**
|
||||
Set the a custom method to be executed when the network activity indicator manager should be hidden/shown. By default, this is null, and the UIApplication Network Activity Indicator will be managed automatically. If this block is set, it is the responsiblity of the caller to manager the network activity indicator going forward.
|
||||
|
||||
@param block A block to be executed when the network activity indicator status changes.
|
||||
*/
|
||||
- (void)setNetworkingActivityActionWithBlock:(nullable void (^)(BOOL networkActivityIndicatorVisible))block;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
#endif
|
||||
239
Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m
generated
Normal file
239
Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m
generated
Normal file
@@ -0,0 +1,239 @@
|
||||
// AFNetworkActivityIndicatorManager.m
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import "AFNetworkActivityIndicatorManager.h"
|
||||
|
||||
#if TARGET_OS_IOS
|
||||
#import "AFURLSessionManager.h"
|
||||
|
||||
typedef NS_ENUM(NSInteger, AFNetworkActivityManagerState) {
|
||||
AFNetworkActivityManagerStateNotActive,
|
||||
AFNetworkActivityManagerStateDelayingStart,
|
||||
AFNetworkActivityManagerStateActive,
|
||||
AFNetworkActivityManagerStateDelayingEnd
|
||||
};
|
||||
|
||||
static NSTimeInterval const kDefaultAFNetworkActivityManagerActivationDelay = 1.0;
|
||||
static NSTimeInterval const kDefaultAFNetworkActivityManagerCompletionDelay = 0.17;
|
||||
|
||||
static NSURLRequest * AFNetworkRequestFromNotification(NSNotification *notification) {
|
||||
if ([[notification object] respondsToSelector:@selector(originalRequest)]) {
|
||||
return [(NSURLSessionTask *)[notification object] originalRequest];
|
||||
} else {
|
||||
return nil;
|
||||
}
|
||||
}
|
||||
|
||||
typedef void (^AFNetworkActivityActionBlock)(BOOL networkActivityIndicatorVisible);
|
||||
|
||||
@interface AFNetworkActivityIndicatorManager ()
|
||||
@property (readwrite, nonatomic, assign) NSInteger activityCount;
|
||||
@property (readwrite, nonatomic, strong) NSTimer *activationDelayTimer;
|
||||
@property (readwrite, nonatomic, strong) NSTimer *completionDelayTimer;
|
||||
@property (readonly, nonatomic, getter = isNetworkActivityOccurring) BOOL networkActivityOccurring;
|
||||
@property (nonatomic, copy) AFNetworkActivityActionBlock networkActivityActionBlock;
|
||||
@property (nonatomic, assign) AFNetworkActivityManagerState currentState;
|
||||
@property (nonatomic, assign, getter=isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible;
|
||||
|
||||
- (void)updateCurrentStateForNetworkActivityChange;
|
||||
@end
|
||||
|
||||
@implementation AFNetworkActivityIndicatorManager
|
||||
|
||||
+ (instancetype)sharedManager {
|
||||
static AFNetworkActivityIndicatorManager *_sharedManager = nil;
|
||||
static dispatch_once_t oncePredicate;
|
||||
dispatch_once(&oncePredicate, ^{
|
||||
_sharedManager = [[self alloc] init];
|
||||
});
|
||||
|
||||
return _sharedManager;
|
||||
}
|
||||
|
||||
- (instancetype)init {
|
||||
self = [super init];
|
||||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
self.currentState = AFNetworkActivityManagerStateNotActive;
|
||||
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidStart:) name:AFNetworkingTaskDidResumeNotification object:nil];
|
||||
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingTaskDidSuspendNotification object:nil];
|
||||
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingTaskDidCompleteNotification object:nil];
|
||||
self.activationDelay = kDefaultAFNetworkActivityManagerActivationDelay;
|
||||
self.completionDelay = kDefaultAFNetworkActivityManagerCompletionDelay;
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)dealloc {
|
||||
[[NSNotificationCenter defaultCenter] removeObserver:self];
|
||||
|
||||
[_activationDelayTimer invalidate];
|
||||
[_completionDelayTimer invalidate];
|
||||
}
|
||||
|
||||
- (void)setEnabled:(BOOL)enabled {
|
||||
_enabled = enabled;
|
||||
if (enabled == NO) {
|
||||
[self setCurrentState:AFNetworkActivityManagerStateNotActive];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setNetworkingActivityActionWithBlock:(void (^)(BOOL networkActivityIndicatorVisible))block {
|
||||
self.networkActivityActionBlock = block;
|
||||
}
|
||||
|
||||
- (BOOL)isNetworkActivityOccurring {
|
||||
@synchronized(self) {
|
||||
return self.activityCount > 0;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setNetworkActivityIndicatorVisible:(BOOL)networkActivityIndicatorVisible {
|
||||
if (_networkActivityIndicatorVisible != networkActivityIndicatorVisible) {
|
||||
@synchronized(self) {
|
||||
_networkActivityIndicatorVisible = networkActivityIndicatorVisible;
|
||||
}
|
||||
if (self.networkActivityActionBlock) {
|
||||
self.networkActivityActionBlock(networkActivityIndicatorVisible);
|
||||
} else {
|
||||
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:networkActivityIndicatorVisible];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
- (void)incrementActivityCount {
|
||||
@synchronized(self) {
|
||||
self.activityCount++;
|
||||
}
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self updateCurrentStateForNetworkActivityChange];
|
||||
});
|
||||
}
|
||||
|
||||
- (void)decrementActivityCount {
|
||||
@synchronized(self) {
|
||||
self.activityCount = MAX(_activityCount - 1, 0);
|
||||
}
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self updateCurrentStateForNetworkActivityChange];
|
||||
});
|
||||
}
|
||||
|
||||
- (void)networkRequestDidStart:(NSNotification *)notification {
|
||||
if ([AFNetworkRequestFromNotification(notification) URL]) {
|
||||
[self incrementActivityCount];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)networkRequestDidFinish:(NSNotification *)notification {
|
||||
if ([AFNetworkRequestFromNotification(notification) URL]) {
|
||||
[self decrementActivityCount];
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark - Internal State Management
|
||||
- (void)setCurrentState:(AFNetworkActivityManagerState)currentState {
|
||||
@synchronized(self) {
|
||||
if (_currentState != currentState) {
|
||||
_currentState = currentState;
|
||||
switch (currentState) {
|
||||
case AFNetworkActivityManagerStateNotActive:
|
||||
[self cancelActivationDelayTimer];
|
||||
[self cancelCompletionDelayTimer];
|
||||
[self setNetworkActivityIndicatorVisible:NO];
|
||||
break;
|
||||
case AFNetworkActivityManagerStateDelayingStart:
|
||||
[self startActivationDelayTimer];
|
||||
break;
|
||||
case AFNetworkActivityManagerStateActive:
|
||||
[self cancelCompletionDelayTimer];
|
||||
[self setNetworkActivityIndicatorVisible:YES];
|
||||
break;
|
||||
case AFNetworkActivityManagerStateDelayingEnd:
|
||||
[self startCompletionDelayTimer];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (void)updateCurrentStateForNetworkActivityChange {
|
||||
if (self.enabled) {
|
||||
switch (self.currentState) {
|
||||
case AFNetworkActivityManagerStateNotActive:
|
||||
if (self.isNetworkActivityOccurring) {
|
||||
[self setCurrentState:AFNetworkActivityManagerStateDelayingStart];
|
||||
}
|
||||
break;
|
||||
case AFNetworkActivityManagerStateDelayingStart:
|
||||
//No op. Let the delay timer finish out.
|
||||
break;
|
||||
case AFNetworkActivityManagerStateActive:
|
||||
if (!self.isNetworkActivityOccurring) {
|
||||
[self setCurrentState:AFNetworkActivityManagerStateDelayingEnd];
|
||||
}
|
||||
break;
|
||||
case AFNetworkActivityManagerStateDelayingEnd:
|
||||
if (self.isNetworkActivityOccurring) {
|
||||
[self setCurrentState:AFNetworkActivityManagerStateActive];
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (void)startActivationDelayTimer {
|
||||
self.activationDelayTimer = [NSTimer
|
||||
timerWithTimeInterval:self.activationDelay target:self selector:@selector(activationDelayTimerFired) userInfo:nil repeats:NO];
|
||||
[[NSRunLoop mainRunLoop] addTimer:self.activationDelayTimer forMode:NSRunLoopCommonModes];
|
||||
}
|
||||
|
||||
- (void)activationDelayTimerFired {
|
||||
if (self.networkActivityOccurring) {
|
||||
[self setCurrentState:AFNetworkActivityManagerStateActive];
|
||||
} else {
|
||||
[self setCurrentState:AFNetworkActivityManagerStateNotActive];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)startCompletionDelayTimer {
|
||||
[self.completionDelayTimer invalidate];
|
||||
self.completionDelayTimer = [NSTimer timerWithTimeInterval:self.completionDelay target:self selector:@selector(completionDelayTimerFired) userInfo:nil repeats:NO];
|
||||
[[NSRunLoop mainRunLoop] addTimer:self.completionDelayTimer forMode:NSRunLoopCommonModes];
|
||||
}
|
||||
|
||||
- (void)completionDelayTimerFired {
|
||||
[self setCurrentState:AFNetworkActivityManagerStateNotActive];
|
||||
}
|
||||
|
||||
- (void)cancelActivationDelayTimer {
|
||||
[self.activationDelayTimer invalidate];
|
||||
}
|
||||
|
||||
- (void)cancelCompletionDelayTimer {
|
||||
[self.completionDelayTimer invalidate];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
48
Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h
generated
Normal file
48
Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h
generated
Normal file
@@ -0,0 +1,48 @@
|
||||
// UIActivityIndicatorView+AFNetworking.h
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#import <TargetConditionals.h>
|
||||
|
||||
#if TARGET_OS_IOS || TARGET_OS_TV
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
/**
|
||||
This category adds methods to the UIKit framework's `UIActivityIndicatorView` class. The methods in this category provide support for automatically starting and stopping animation depending on the loading state of a session task.
|
||||
*/
|
||||
@interface UIActivityIndicatorView (AFNetworking)
|
||||
|
||||
///----------------------------------
|
||||
/// @name Animating for Session Tasks
|
||||
///----------------------------------
|
||||
|
||||
/**
|
||||
Binds the animating state to the state of the specified task.
|
||||
|
||||
@param task The task. If `nil`, automatic updating from any previously specified operation will be disabled.
|
||||
*/
|
||||
- (void)setAnimatingWithStateOfTask:(nullable NSURLSessionTask *)task;
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
114
Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m
generated
Normal file
114
Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m
generated
Normal file
@@ -0,0 +1,114 @@
|
||||
// UIActivityIndicatorView+AFNetworking.m
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import "UIActivityIndicatorView+AFNetworking.h"
|
||||
#import <objc/runtime.h>
|
||||
|
||||
#if TARGET_OS_IOS || TARGET_OS_TV
|
||||
|
||||
#import "AFURLSessionManager.h"
|
||||
|
||||
@interface AFActivityIndicatorViewNotificationObserver : NSObject
|
||||
@property (readonly, nonatomic, weak) UIActivityIndicatorView *activityIndicatorView;
|
||||
- (instancetype)initWithActivityIndicatorView:(UIActivityIndicatorView *)activityIndicatorView;
|
||||
|
||||
- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task;
|
||||
|
||||
@end
|
||||
|
||||
@implementation UIActivityIndicatorView (AFNetworking)
|
||||
|
||||
- (AFActivityIndicatorViewNotificationObserver *)af_notificationObserver {
|
||||
AFActivityIndicatorViewNotificationObserver *notificationObserver = objc_getAssociatedObject(self, @selector(af_notificationObserver));
|
||||
if (notificationObserver == nil) {
|
||||
notificationObserver = [[AFActivityIndicatorViewNotificationObserver alloc] initWithActivityIndicatorView:self];
|
||||
objc_setAssociatedObject(self, @selector(af_notificationObserver), notificationObserver, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
|
||||
}
|
||||
return notificationObserver;
|
||||
}
|
||||
|
||||
- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task {
|
||||
[[self af_notificationObserver] setAnimatingWithStateOfTask:task];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation AFActivityIndicatorViewNotificationObserver
|
||||
|
||||
- (instancetype)initWithActivityIndicatorView:(UIActivityIndicatorView *)activityIndicatorView
|
||||
{
|
||||
self = [super init];
|
||||
if (self) {
|
||||
_activityIndicatorView = activityIndicatorView;
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task {
|
||||
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
|
||||
|
||||
[notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil];
|
||||
[notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil];
|
||||
[notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil];
|
||||
|
||||
if (task) {
|
||||
if (task.state != NSURLSessionTaskStateCompleted) {
|
||||
UIActivityIndicatorView *activityIndicatorView = self.activityIndicatorView;
|
||||
if (task.state == NSURLSessionTaskStateRunning) {
|
||||
[activityIndicatorView startAnimating];
|
||||
} else {
|
||||
[activityIndicatorView stopAnimating];
|
||||
}
|
||||
|
||||
[notificationCenter addObserver:self selector:@selector(af_startAnimating) name:AFNetworkingTaskDidResumeNotification object:task];
|
||||
[notificationCenter addObserver:self selector:@selector(af_stopAnimating) name:AFNetworkingTaskDidCompleteNotification object:task];
|
||||
[notificationCenter addObserver:self selector:@selector(af_stopAnimating) name:AFNetworkingTaskDidSuspendNotification object:task];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (void)af_startAnimating {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self.activityIndicatorView startAnimating];
|
||||
});
|
||||
}
|
||||
|
||||
- (void)af_stopAnimating {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self.activityIndicatorView stopAnimating];
|
||||
});
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (void)dealloc {
|
||||
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
|
||||
|
||||
[notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil];
|
||||
[notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil];
|
||||
[notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
175
Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h
generated
Normal file
175
Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h
generated
Normal file
@@ -0,0 +1,175 @@
|
||||
// UIButton+AFNetworking.h
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#import <TargetConditionals.h>
|
||||
|
||||
#if TARGET_OS_IOS || TARGET_OS_TV
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@class AFImageDownloader;
|
||||
|
||||
/**
|
||||
This category adds methods to the UIKit framework's `UIButton` class. The methods in this category provide support for loading remote images and background images asynchronously from a URL.
|
||||
|
||||
@warning Compound values for control `state` (such as `UIControlStateHighlighted | UIControlStateDisabled`) are unsupported.
|
||||
*/
|
||||
@interface UIButton (AFNetworking)
|
||||
|
||||
///------------------------------------
|
||||
/// @name Accessing the Image Downloader
|
||||
///------------------------------------
|
||||
|
||||
/**
|
||||
Set the shared image downloader used to download images.
|
||||
|
||||
@param imageDownloader The shared image downloader used to download images.
|
||||
*/
|
||||
+ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader;
|
||||
|
||||
/**
|
||||
The shared image downloader used to download images.
|
||||
*/
|
||||
+ (AFImageDownloader *)sharedImageDownloader;
|
||||
|
||||
///--------------------
|
||||
/// @name Setting Image
|
||||
///--------------------
|
||||
|
||||
/**
|
||||
Asynchronously downloads an image from the specified URL, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled.
|
||||
|
||||
If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
|
||||
|
||||
@param state The control state.
|
||||
@param url The URL used for the image request.
|
||||
*/
|
||||
- (void)setImageForState:(UIControlState)state
|
||||
withURL:(NSURL *)url;
|
||||
|
||||
/**
|
||||
Asynchronously downloads an image from the specified URL, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled.
|
||||
|
||||
If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
|
||||
|
||||
@param state The control state.
|
||||
@param url The URL used for the image request.
|
||||
@param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the button will not change its image until the image request finishes.
|
||||
*/
|
||||
- (void)setImageForState:(UIControlState)state
|
||||
withURL:(NSURL *)url
|
||||
placeholderImage:(nullable UIImage *)placeholderImage;
|
||||
|
||||
/**
|
||||
Asynchronously downloads an image from the specified URL request, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled.
|
||||
|
||||
If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
|
||||
|
||||
If a success block is specified, it is the responsibility of the block to set the image of the button before returning. If no success block is specified, the default behavior of setting the image with `setImage:forState:` is applied.
|
||||
|
||||
@param state The control state.
|
||||
@param urlRequest The URL request used for the image request.
|
||||
@param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the button will not change its image until the image request finishes.
|
||||
@param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`.
|
||||
@param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred.
|
||||
*/
|
||||
- (void)setImageForState:(UIControlState)state
|
||||
withURLRequest:(NSURLRequest *)urlRequest
|
||||
placeholderImage:(nullable UIImage *)placeholderImage
|
||||
success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success
|
||||
failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure;
|
||||
|
||||
|
||||
///-------------------------------
|
||||
/// @name Setting Background Image
|
||||
///-------------------------------
|
||||
|
||||
/**
|
||||
Asynchronously downloads an image from the specified URL, and sets it as the background image for the specified state once the request is finished. Any previous background image request for the receiver will be cancelled.
|
||||
|
||||
If the background image is cached locally, the background image is set immediately, otherwise the specified placeholder background image will be set immediately, and then the remote background image will be set once the request is finished.
|
||||
|
||||
@param state The control state.
|
||||
@param url The URL used for the background image request.
|
||||
*/
|
||||
- (void)setBackgroundImageForState:(UIControlState)state
|
||||
withURL:(NSURL *)url;
|
||||
|
||||
/**
|
||||
Asynchronously downloads an image from the specified URL, and sets it as the background image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled.
|
||||
|
||||
If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
|
||||
|
||||
@param state The control state.
|
||||
@param url The URL used for the background image request.
|
||||
@param placeholderImage The background image to be set initially, until the background image request finishes. If `nil`, the button will not change its background image until the background image request finishes.
|
||||
*/
|
||||
- (void)setBackgroundImageForState:(UIControlState)state
|
||||
withURL:(NSURL *)url
|
||||
placeholderImage:(nullable UIImage *)placeholderImage;
|
||||
|
||||
/**
|
||||
Asynchronously downloads an image from the specified URL request, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled.
|
||||
|
||||
If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
|
||||
|
||||
If a success block is specified, it is the responsibility of the block to set the image of the button before returning. If no success block is specified, the default behavior of setting the image with `setBackgroundImage:forState:` is applied.
|
||||
|
||||
@param state The control state.
|
||||
@param urlRequest The URL request used for the image request.
|
||||
@param placeholderImage The background image to be set initially, until the background image request finishes. If `nil`, the button will not change its background image until the background image request finishes.
|
||||
@param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`.
|
||||
@param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred.
|
||||
*/
|
||||
- (void)setBackgroundImageForState:(UIControlState)state
|
||||
withURLRequest:(NSURLRequest *)urlRequest
|
||||
placeholderImage:(nullable UIImage *)placeholderImage
|
||||
success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success
|
||||
failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure;
|
||||
|
||||
|
||||
///------------------------------
|
||||
/// @name Canceling Image Loading
|
||||
///------------------------------
|
||||
|
||||
/**
|
||||
Cancels any executing image task for the specified control state of the receiver, if one exists.
|
||||
|
||||
@param state The control state.
|
||||
*/
|
||||
- (void)cancelImageDownloadTaskForState:(UIControlState)state;
|
||||
|
||||
/**
|
||||
Cancels any executing background image task for the specified control state of the receiver, if one exists.
|
||||
|
||||
@param state The control state.
|
||||
*/
|
||||
- (void)cancelBackgroundImageDownloadTaskForState:(UIControlState)state;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
#endif
|
||||
302
Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.m
generated
Normal file
302
Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.m
generated
Normal file
@@ -0,0 +1,302 @@
|
||||
// UIButton+AFNetworking.m
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import "UIButton+AFNetworking.h"
|
||||
|
||||
#import <objc/runtime.h>
|
||||
|
||||
#if TARGET_OS_IOS || TARGET_OS_TV
|
||||
|
||||
#import "UIImageView+AFNetworking.h"
|
||||
#import "AFImageDownloader.h"
|
||||
|
||||
@interface UIButton (_AFNetworking)
|
||||
@end
|
||||
|
||||
@implementation UIButton (_AFNetworking)
|
||||
|
||||
#pragma mark -
|
||||
|
||||
static char AFImageDownloadReceiptNormal;
|
||||
static char AFImageDownloadReceiptHighlighted;
|
||||
static char AFImageDownloadReceiptSelected;
|
||||
static char AFImageDownloadReceiptDisabled;
|
||||
|
||||
static const char * af_imageDownloadReceiptKeyForState(UIControlState state) {
|
||||
switch (state) {
|
||||
case UIControlStateHighlighted:
|
||||
return &AFImageDownloadReceiptHighlighted;
|
||||
case UIControlStateSelected:
|
||||
return &AFImageDownloadReceiptSelected;
|
||||
case UIControlStateDisabled:
|
||||
return &AFImageDownloadReceiptDisabled;
|
||||
case UIControlStateNormal:
|
||||
default:
|
||||
return &AFImageDownloadReceiptNormal;
|
||||
}
|
||||
}
|
||||
|
||||
- (AFImageDownloadReceipt *)af_imageDownloadReceiptForState:(UIControlState)state {
|
||||
return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, af_imageDownloadReceiptKeyForState(state));
|
||||
}
|
||||
|
||||
- (void)af_setImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt
|
||||
forState:(UIControlState)state
|
||||
{
|
||||
objc_setAssociatedObject(self, af_imageDownloadReceiptKeyForState(state), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
static char AFBackgroundImageDownloadReceiptNormal;
|
||||
static char AFBackgroundImageDownloadReceiptHighlighted;
|
||||
static char AFBackgroundImageDownloadReceiptSelected;
|
||||
static char AFBackgroundImageDownloadReceiptDisabled;
|
||||
|
||||
static const char * af_backgroundImageDownloadReceiptKeyForState(UIControlState state) {
|
||||
switch (state) {
|
||||
case UIControlStateHighlighted:
|
||||
return &AFBackgroundImageDownloadReceiptHighlighted;
|
||||
case UIControlStateSelected:
|
||||
return &AFBackgroundImageDownloadReceiptSelected;
|
||||
case UIControlStateDisabled:
|
||||
return &AFBackgroundImageDownloadReceiptDisabled;
|
||||
case UIControlStateNormal:
|
||||
default:
|
||||
return &AFBackgroundImageDownloadReceiptNormal;
|
||||
}
|
||||
}
|
||||
|
||||
- (AFImageDownloadReceipt *)af_backgroundImageDownloadReceiptForState:(UIControlState)state {
|
||||
return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, af_backgroundImageDownloadReceiptKeyForState(state));
|
||||
}
|
||||
|
||||
- (void)af_setBackgroundImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt
|
||||
forState:(UIControlState)state
|
||||
{
|
||||
objc_setAssociatedObject(self, af_backgroundImageDownloadReceiptKeyForState(state), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@implementation UIButton (AFNetworking)
|
||||
|
||||
+ (AFImageDownloader *)sharedImageDownloader {
|
||||
|
||||
return objc_getAssociatedObject([UIButton class], @selector(sharedImageDownloader)) ?: [AFImageDownloader defaultInstance];
|
||||
}
|
||||
|
||||
+ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader {
|
||||
objc_setAssociatedObject([UIButton class], @selector(sharedImageDownloader), imageDownloader, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (void)setImageForState:(UIControlState)state
|
||||
withURL:(NSURL *)url
|
||||
{
|
||||
[self setImageForState:state withURL:url placeholderImage:nil];
|
||||
}
|
||||
|
||||
- (void)setImageForState:(UIControlState)state
|
||||
withURL:(NSURL *)url
|
||||
placeholderImage:(UIImage *)placeholderImage
|
||||
{
|
||||
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
|
||||
[request addValue:@"image/*" forHTTPHeaderField:@"Accept"];
|
||||
|
||||
[self setImageForState:state withURLRequest:request placeholderImage:placeholderImage success:nil failure:nil];
|
||||
}
|
||||
|
||||
- (void)setImageForState:(UIControlState)state
|
||||
withURLRequest:(NSURLRequest *)urlRequest
|
||||
placeholderImage:(nullable UIImage *)placeholderImage
|
||||
success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success
|
||||
failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure
|
||||
{
|
||||
if ([self isActiveTaskURLEqualToURLRequest:urlRequest forState:state]) {
|
||||
return;
|
||||
}
|
||||
|
||||
[self cancelImageDownloadTaskForState:state];
|
||||
|
||||
AFImageDownloader *downloader = [[self class] sharedImageDownloader];
|
||||
id <AFImageRequestCache> imageCache = downloader.imageCache;
|
||||
|
||||
//Use the image from the image cache if it exists
|
||||
UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil];
|
||||
if (cachedImage) {
|
||||
if (success) {
|
||||
success(urlRequest, nil, cachedImage);
|
||||
} else {
|
||||
[self setImage:cachedImage forState:state];
|
||||
}
|
||||
[self af_setImageDownloadReceipt:nil forState:state];
|
||||
} else {
|
||||
if (placeholderImage) {
|
||||
[self setImage:placeholderImage forState:state];
|
||||
}
|
||||
|
||||
__weak __typeof(self)weakSelf = self;
|
||||
NSUUID *downloadID = [NSUUID UUID];
|
||||
AFImageDownloadReceipt *receipt;
|
||||
receipt = [downloader
|
||||
downloadImageForURLRequest:urlRequest
|
||||
withReceiptID:downloadID
|
||||
success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) {
|
||||
__strong __typeof(weakSelf)strongSelf = weakSelf;
|
||||
if ([[strongSelf af_imageDownloadReceiptForState:state].receiptID isEqual:downloadID]) {
|
||||
if (success) {
|
||||
success(request, response, responseObject);
|
||||
} else if (responseObject) {
|
||||
[strongSelf setImage:responseObject forState:state];
|
||||
}
|
||||
[strongSelf af_setImageDownloadReceipt:nil forState:state];
|
||||
}
|
||||
|
||||
}
|
||||
failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {
|
||||
__strong __typeof(weakSelf)strongSelf = weakSelf;
|
||||
if ([[strongSelf af_imageDownloadReceiptForState:state].receiptID isEqual:downloadID]) {
|
||||
if (failure) {
|
||||
failure(request, response, error);
|
||||
}
|
||||
[strongSelf af_setImageDownloadReceipt:nil forState:state];
|
||||
}
|
||||
}];
|
||||
|
||||
[self af_setImageDownloadReceipt:receipt forState:state];
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (void)setBackgroundImageForState:(UIControlState)state
|
||||
withURL:(NSURL *)url
|
||||
{
|
||||
[self setBackgroundImageForState:state withURL:url placeholderImage:nil];
|
||||
}
|
||||
|
||||
- (void)setBackgroundImageForState:(UIControlState)state
|
||||
withURL:(NSURL *)url
|
||||
placeholderImage:(nullable UIImage *)placeholderImage
|
||||
{
|
||||
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
|
||||
[request addValue:@"image/*" forHTTPHeaderField:@"Accept"];
|
||||
|
||||
[self setBackgroundImageForState:state withURLRequest:request placeholderImage:placeholderImage success:nil failure:nil];
|
||||
}
|
||||
|
||||
- (void)setBackgroundImageForState:(UIControlState)state
|
||||
withURLRequest:(NSURLRequest *)urlRequest
|
||||
placeholderImage:(nullable UIImage *)placeholderImage
|
||||
success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success
|
||||
failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure
|
||||
{
|
||||
if ([self isActiveBackgroundTaskURLEqualToURLRequest:urlRequest forState:state]) {
|
||||
return;
|
||||
}
|
||||
|
||||
[self cancelBackgroundImageDownloadTaskForState:state];
|
||||
|
||||
AFImageDownloader *downloader = [[self class] sharedImageDownloader];
|
||||
id <AFImageRequestCache> imageCache = downloader.imageCache;
|
||||
|
||||
//Use the image from the image cache if it exists
|
||||
UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil];
|
||||
if (cachedImage) {
|
||||
if (success) {
|
||||
success(urlRequest, nil, cachedImage);
|
||||
} else {
|
||||
[self setBackgroundImage:cachedImage forState:state];
|
||||
}
|
||||
[self af_setBackgroundImageDownloadReceipt:nil forState:state];
|
||||
} else {
|
||||
if (placeholderImage) {
|
||||
[self setBackgroundImage:placeholderImage forState:state];
|
||||
}
|
||||
|
||||
__weak __typeof(self)weakSelf = self;
|
||||
NSUUID *downloadID = [NSUUID UUID];
|
||||
AFImageDownloadReceipt *receipt;
|
||||
receipt = [downloader
|
||||
downloadImageForURLRequest:urlRequest
|
||||
withReceiptID:downloadID
|
||||
success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) {
|
||||
__strong __typeof(weakSelf)strongSelf = weakSelf;
|
||||
if ([[strongSelf af_backgroundImageDownloadReceiptForState:state].receiptID isEqual:downloadID]) {
|
||||
if (success) {
|
||||
success(request, response, responseObject);
|
||||
} else if (responseObject) {
|
||||
[strongSelf setBackgroundImage:responseObject forState:state];
|
||||
}
|
||||
[strongSelf af_setBackgroundImageDownloadReceipt:nil forState:state];
|
||||
}
|
||||
|
||||
}
|
||||
failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {
|
||||
__strong __typeof(weakSelf)strongSelf = weakSelf;
|
||||
if ([[strongSelf af_backgroundImageDownloadReceiptForState:state].receiptID isEqual:downloadID]) {
|
||||
if (failure) {
|
||||
failure(request, response, error);
|
||||
}
|
||||
[strongSelf af_setBackgroundImageDownloadReceipt:nil forState:state];
|
||||
}
|
||||
}];
|
||||
|
||||
[self af_setBackgroundImageDownloadReceipt:receipt forState:state];
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (void)cancelImageDownloadTaskForState:(UIControlState)state {
|
||||
AFImageDownloadReceipt *receipt = [self af_imageDownloadReceiptForState:state];
|
||||
if (receipt != nil) {
|
||||
[[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:receipt];
|
||||
[self af_setImageDownloadReceipt:nil forState:state];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)cancelBackgroundImageDownloadTaskForState:(UIControlState)state {
|
||||
AFImageDownloadReceipt *receipt = [self af_backgroundImageDownloadReceiptForState:state];
|
||||
if (receipt != nil) {
|
||||
[[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:receipt];
|
||||
[self af_setBackgroundImageDownloadReceipt:nil forState:state];
|
||||
}
|
||||
}
|
||||
|
||||
- (BOOL)isActiveTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest forState:(UIControlState)state {
|
||||
AFImageDownloadReceipt *receipt = [self af_imageDownloadReceiptForState:state];
|
||||
return [receipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString];
|
||||
}
|
||||
|
||||
- (BOOL)isActiveBackgroundTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest forState:(UIControlState)state {
|
||||
AFImageDownloadReceipt *receipt = [self af_backgroundImageDownloadReceiptForState:state];
|
||||
return [receipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString];
|
||||
}
|
||||
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
109
Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h
generated
Normal file
109
Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h
generated
Normal file
@@ -0,0 +1,109 @@
|
||||
// UIImageView+AFNetworking.h
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#import <TargetConditionals.h>
|
||||
|
||||
#if TARGET_OS_IOS || TARGET_OS_TV
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@class AFImageDownloader;
|
||||
|
||||
/**
|
||||
This category adds methods to the UIKit framework's `UIImageView` class. The methods in this category provide support for loading remote images asynchronously from a URL.
|
||||
*/
|
||||
@interface UIImageView (AFNetworking)
|
||||
|
||||
///------------------------------------
|
||||
/// @name Accessing the Image Downloader
|
||||
///------------------------------------
|
||||
|
||||
/**
|
||||
Set the shared image downloader used to download images.
|
||||
|
||||
@param imageDownloader The shared image downloader used to download images.
|
||||
*/
|
||||
+ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader;
|
||||
|
||||
/**
|
||||
The shared image downloader used to download images.
|
||||
*/
|
||||
+ (AFImageDownloader *)sharedImageDownloader;
|
||||
|
||||
///--------------------
|
||||
/// @name Setting Image
|
||||
///--------------------
|
||||
|
||||
/**
|
||||
Asynchronously downloads an image from the specified URL, and sets it once the request is finished. Any previous image request for the receiver will be cancelled.
|
||||
|
||||
If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
|
||||
|
||||
By default, URL requests have a `Accept` header field value of "image / *", a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:`
|
||||
|
||||
@param url The URL used for the image request.
|
||||
*/
|
||||
- (void)setImageWithURL:(NSURL *)url;
|
||||
|
||||
/**
|
||||
Asynchronously downloads an image from the specified URL, and sets it once the request is finished. Any previous image request for the receiver will be cancelled.
|
||||
|
||||
If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
|
||||
|
||||
By default, URL requests have a `Accept` header field value of "image / *", a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:`
|
||||
|
||||
@param url The URL used for the image request.
|
||||
@param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes.
|
||||
*/
|
||||
- (void)setImageWithURL:(NSURL *)url
|
||||
placeholderImage:(nullable UIImage *)placeholderImage;
|
||||
|
||||
/**
|
||||
Asynchronously downloads an image from the specified URL request, and sets it once the request is finished. Any previous image request for the receiver will be cancelled.
|
||||
|
||||
If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
|
||||
|
||||
If a success block is specified, it is the responsibility of the block to set the image of the image view before returning. If no success block is specified, the default behavior of setting the image with `self.image = image` is applied.
|
||||
|
||||
@param urlRequest The URL request used for the image request.
|
||||
@param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes.
|
||||
@param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`.
|
||||
@param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred.
|
||||
*/
|
||||
- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest
|
||||
placeholderImage:(nullable UIImage *)placeholderImage
|
||||
success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success
|
||||
failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure;
|
||||
|
||||
/**
|
||||
Cancels any executing image operation for the receiver, if one exists.
|
||||
*/
|
||||
- (void)cancelImageDownloadTask;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
#endif
|
||||
159
Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.m
generated
Normal file
159
Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.m
generated
Normal file
@@ -0,0 +1,159 @@
|
||||
// UIImageView+AFNetworking.m
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import "UIImageView+AFNetworking.h"
|
||||
|
||||
#import <objc/runtime.h>
|
||||
|
||||
#if TARGET_OS_IOS || TARGET_OS_TV
|
||||
|
||||
#import "AFImageDownloader.h"
|
||||
|
||||
@interface UIImageView (_AFNetworking)
|
||||
@property (readwrite, nonatomic, strong, setter = af_setActiveImageDownloadReceipt:) AFImageDownloadReceipt *af_activeImageDownloadReceipt;
|
||||
@end
|
||||
|
||||
@implementation UIImageView (_AFNetworking)
|
||||
|
||||
- (AFImageDownloadReceipt *)af_activeImageDownloadReceipt {
|
||||
return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, @selector(af_activeImageDownloadReceipt));
|
||||
}
|
||||
|
||||
- (void)af_setActiveImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt {
|
||||
objc_setAssociatedObject(self, @selector(af_activeImageDownloadReceipt), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@implementation UIImageView (AFNetworking)
|
||||
|
||||
+ (AFImageDownloader *)sharedImageDownloader {
|
||||
return objc_getAssociatedObject([UIImageView class], @selector(sharedImageDownloader)) ?: [AFImageDownloader defaultInstance];
|
||||
}
|
||||
|
||||
+ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader {
|
||||
objc_setAssociatedObject([UIImageView class], @selector(sharedImageDownloader), imageDownloader, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (void)setImageWithURL:(NSURL *)url {
|
||||
[self setImageWithURL:url placeholderImage:nil];
|
||||
}
|
||||
|
||||
- (void)setImageWithURL:(NSURL *)url
|
||||
placeholderImage:(UIImage *)placeholderImage
|
||||
{
|
||||
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
|
||||
[request addValue:@"image/*" forHTTPHeaderField:@"Accept"];
|
||||
|
||||
[self setImageWithURLRequest:request placeholderImage:placeholderImage success:nil failure:nil];
|
||||
}
|
||||
|
||||
- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest
|
||||
placeholderImage:(UIImage *)placeholderImage
|
||||
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success
|
||||
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure
|
||||
{
|
||||
if ([urlRequest URL] == nil) {
|
||||
self.image = placeholderImage;
|
||||
if (failure) {
|
||||
NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorBadURL userInfo:nil];
|
||||
failure(urlRequest, nil, error);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if ([self isActiveTaskURLEqualToURLRequest:urlRequest]) {
|
||||
return;
|
||||
}
|
||||
|
||||
[self cancelImageDownloadTask];
|
||||
|
||||
AFImageDownloader *downloader = [[self class] sharedImageDownloader];
|
||||
id <AFImageRequestCache> imageCache = downloader.imageCache;
|
||||
|
||||
//Use the image from the image cache if it exists
|
||||
UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil];
|
||||
if (cachedImage) {
|
||||
if (success) {
|
||||
success(urlRequest, nil, cachedImage);
|
||||
} else {
|
||||
self.image = cachedImage;
|
||||
}
|
||||
[self clearActiveDownloadInformation];
|
||||
} else {
|
||||
if (placeholderImage) {
|
||||
self.image = placeholderImage;
|
||||
}
|
||||
|
||||
__weak __typeof(self)weakSelf = self;
|
||||
NSUUID *downloadID = [NSUUID UUID];
|
||||
AFImageDownloadReceipt *receipt;
|
||||
receipt = [downloader
|
||||
downloadImageForURLRequest:urlRequest
|
||||
withReceiptID:downloadID
|
||||
success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) {
|
||||
__strong __typeof(weakSelf)strongSelf = weakSelf;
|
||||
if ([strongSelf.af_activeImageDownloadReceipt.receiptID isEqual:downloadID]) {
|
||||
if (success) {
|
||||
success(request, response, responseObject);
|
||||
} else if (responseObject) {
|
||||
strongSelf.image = responseObject;
|
||||
}
|
||||
[strongSelf clearActiveDownloadInformation];
|
||||
}
|
||||
|
||||
}
|
||||
failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {
|
||||
__strong __typeof(weakSelf)strongSelf = weakSelf;
|
||||
if ([strongSelf.af_activeImageDownloadReceipt.receiptID isEqual:downloadID]) {
|
||||
if (failure) {
|
||||
failure(request, response, error);
|
||||
}
|
||||
[strongSelf clearActiveDownloadInformation];
|
||||
}
|
||||
}];
|
||||
|
||||
self.af_activeImageDownloadReceipt = receipt;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)cancelImageDownloadTask {
|
||||
if (self.af_activeImageDownloadReceipt != nil) {
|
||||
[[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:self.af_activeImageDownloadReceipt];
|
||||
[self clearActiveDownloadInformation];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)clearActiveDownloadInformation {
|
||||
self.af_activeImageDownloadReceipt = nil;
|
||||
}
|
||||
|
||||
- (BOOL)isActiveTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest {
|
||||
return [self.af_activeImageDownloadReceipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
43
Pods/AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h
generated
Normal file
43
Pods/AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h
generated
Normal file
@@ -0,0 +1,43 @@
|
||||
// UIKit+AFNetworking.h
|
||||
//
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import <TargetConditionals.h>
|
||||
|
||||
#ifndef _UIKIT_AFNETWORKING_
|
||||
#define _UIKIT_AFNETWORKING_
|
||||
|
||||
#if TARGET_OS_IOS || TARGET_OS_TV
|
||||
#import "AFAutoPurgingImageCache.h"
|
||||
#import "AFImageDownloader.h"
|
||||
#import "UIActivityIndicatorView+AFNetworking.h"
|
||||
#import "UIButton+AFNetworking.h"
|
||||
#import "UIImageView+AFNetworking.h"
|
||||
#import "UIProgressView+AFNetworking.h"
|
||||
#endif
|
||||
|
||||
#if TARGET_OS_IOS
|
||||
#import "AFNetworkActivityIndicatorManager.h"
|
||||
#import "UIRefreshControl+AFNetworking.h"
|
||||
#import "WKWebView+AFNetworking.h"
|
||||
#endif
|
||||
|
||||
#endif /* _UIKIT_AFNETWORKING_ */
|
||||
64
Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h
generated
Normal file
64
Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h
generated
Normal file
@@ -0,0 +1,64 @@
|
||||
// UIProgressView+AFNetworking.h
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#import <TargetConditionals.h>
|
||||
|
||||
#if TARGET_OS_IOS || TARGET_OS_TV
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
|
||||
/**
|
||||
This category adds methods to the UIKit framework's `UIProgressView` class. The methods in this category provide support for binding the progress to the upload and download progress of a session task.
|
||||
*/
|
||||
@interface UIProgressView (AFNetworking)
|
||||
|
||||
///------------------------------------
|
||||
/// @name Setting Session Task Progress
|
||||
///------------------------------------
|
||||
|
||||
/**
|
||||
Binds the progress to the upload progress of the specified session task.
|
||||
|
||||
@param task The session task.
|
||||
@param animated `YES` if the change should be animated, `NO` if the change should happen immediately.
|
||||
*/
|
||||
- (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task
|
||||
animated:(BOOL)animated;
|
||||
|
||||
/**
|
||||
Binds the progress to the download progress of the specified session task.
|
||||
|
||||
@param task The session task.
|
||||
@param animated `YES` if the change should be animated, `NO` if the change should happen immediately.
|
||||
*/
|
||||
- (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task
|
||||
animated:(BOOL)animated;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
#endif
|
||||
126
Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.m
generated
Normal file
126
Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.m
generated
Normal file
@@ -0,0 +1,126 @@
|
||||
// UIProgressView+AFNetworking.m
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import "UIProgressView+AFNetworking.h"
|
||||
|
||||
#import <objc/runtime.h>
|
||||
|
||||
#if TARGET_OS_IOS || TARGET_OS_TV
|
||||
|
||||
#import "AFURLSessionManager.h"
|
||||
|
||||
static void * AFTaskCountOfBytesSentContext = &AFTaskCountOfBytesSentContext;
|
||||
static void * AFTaskCountOfBytesReceivedContext = &AFTaskCountOfBytesReceivedContext;
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@implementation UIProgressView (AFNetworking)
|
||||
|
||||
- (BOOL)af_uploadProgressAnimated {
|
||||
return [(NSNumber *)objc_getAssociatedObject(self, @selector(af_uploadProgressAnimated)) boolValue];
|
||||
}
|
||||
|
||||
- (void)af_setUploadProgressAnimated:(BOOL)animated {
|
||||
objc_setAssociatedObject(self, @selector(af_uploadProgressAnimated), @(animated), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
|
||||
}
|
||||
|
||||
- (BOOL)af_downloadProgressAnimated {
|
||||
return [(NSNumber *)objc_getAssociatedObject(self, @selector(af_downloadProgressAnimated)) boolValue];
|
||||
}
|
||||
|
||||
- (void)af_setDownloadProgressAnimated:(BOOL)animated {
|
||||
objc_setAssociatedObject(self, @selector(af_downloadProgressAnimated), @(animated), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task
|
||||
animated:(BOOL)animated
|
||||
{
|
||||
if (task.state == NSURLSessionTaskStateCompleted) {
|
||||
return;
|
||||
}
|
||||
|
||||
[task addObserver:self forKeyPath:@"state" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesSentContext];
|
||||
[task addObserver:self forKeyPath:@"countOfBytesSent" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesSentContext];
|
||||
|
||||
[self af_setUploadProgressAnimated:animated];
|
||||
}
|
||||
|
||||
- (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task
|
||||
animated:(BOOL)animated
|
||||
{
|
||||
if (task.state == NSURLSessionTaskStateCompleted) {
|
||||
return;
|
||||
}
|
||||
|
||||
[task addObserver:self forKeyPath:@"state" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext];
|
||||
[task addObserver:self forKeyPath:@"countOfBytesReceived" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext];
|
||||
|
||||
[self af_setDownloadProgressAnimated:animated];
|
||||
}
|
||||
|
||||
#pragma mark - NSKeyValueObserving
|
||||
|
||||
- (void)observeValueForKeyPath:(NSString *)keyPath
|
||||
ofObject:(id)object
|
||||
change:(__unused NSDictionary *)change
|
||||
context:(void *)context
|
||||
{
|
||||
if (context == AFTaskCountOfBytesSentContext || context == AFTaskCountOfBytesReceivedContext) {
|
||||
if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesSent))]) {
|
||||
if ([object countOfBytesExpectedToSend] > 0) {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self setProgress:[object countOfBytesSent] / ([object countOfBytesExpectedToSend] * 1.0f) animated:self.af_uploadProgressAnimated];
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesReceived))]) {
|
||||
if ([object countOfBytesExpectedToReceive] > 0) {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self setProgress:[object countOfBytesReceived] / ([object countOfBytesExpectedToReceive] * 1.0f) animated:self.af_downloadProgressAnimated];
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if ([keyPath isEqualToString:NSStringFromSelector(@selector(state))]) {
|
||||
if ([(NSURLSessionTask *)object state] == NSURLSessionTaskStateCompleted) {
|
||||
@try {
|
||||
[object removeObserver:self forKeyPath:NSStringFromSelector(@selector(state))];
|
||||
|
||||
if (context == AFTaskCountOfBytesSentContext) {
|
||||
[object removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesSent))];
|
||||
}
|
||||
|
||||
if (context == AFTaskCountOfBytesReceivedContext) {
|
||||
[object removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesReceived))];
|
||||
}
|
||||
}
|
||||
@catch (NSException * __unused exception) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
53
Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h
generated
Normal file
53
Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h
generated
Normal file
@@ -0,0 +1,53 @@
|
||||
// UIRefreshControl+AFNetworking.m
|
||||
//
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#import <TargetConditionals.h>
|
||||
|
||||
#if TARGET_OS_IOS
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/**
|
||||
This category adds methods to the UIKit framework's `UIRefreshControl` class. The methods in this category provide support for automatically beginning and ending refreshing depending on the loading state of a session task.
|
||||
*/
|
||||
@interface UIRefreshControl (AFNetworking)
|
||||
|
||||
///-----------------------------------
|
||||
/// @name Refreshing for Session Tasks
|
||||
///-----------------------------------
|
||||
|
||||
/**
|
||||
Binds the refreshing state to the state of the specified task.
|
||||
|
||||
@param task The task. If `nil`, automatic updating from any previously specified operation will be disabled.
|
||||
*/
|
||||
- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
#endif
|
||||
113
Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.m
generated
Normal file
113
Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.m
generated
Normal file
@@ -0,0 +1,113 @@
|
||||
// UIRefreshControl+AFNetworking.m
|
||||
//
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import "UIRefreshControl+AFNetworking.h"
|
||||
#import <objc/runtime.h>
|
||||
|
||||
#if TARGET_OS_IOS
|
||||
|
||||
#import "AFURLSessionManager.h"
|
||||
|
||||
@interface AFRefreshControlNotificationObserver : NSObject
|
||||
@property (readonly, nonatomic, weak) UIRefreshControl *refreshControl;
|
||||
- (instancetype)initWithActivityRefreshControl:(UIRefreshControl *)refreshControl;
|
||||
|
||||
- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task;
|
||||
|
||||
@end
|
||||
|
||||
@implementation UIRefreshControl (AFNetworking)
|
||||
|
||||
- (AFRefreshControlNotificationObserver *)af_notificationObserver {
|
||||
AFRefreshControlNotificationObserver *notificationObserver = objc_getAssociatedObject(self, @selector(af_notificationObserver));
|
||||
if (notificationObserver == nil) {
|
||||
notificationObserver = [[AFRefreshControlNotificationObserver alloc] initWithActivityRefreshControl:self];
|
||||
objc_setAssociatedObject(self, @selector(af_notificationObserver), notificationObserver, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
|
||||
}
|
||||
return notificationObserver;
|
||||
}
|
||||
|
||||
- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task {
|
||||
[[self af_notificationObserver] setRefreshingWithStateOfTask:task];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation AFRefreshControlNotificationObserver
|
||||
|
||||
- (instancetype)initWithActivityRefreshControl:(UIRefreshControl *)refreshControl
|
||||
{
|
||||
self = [super init];
|
||||
if (self) {
|
||||
_refreshControl = refreshControl;
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task {
|
||||
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
|
||||
|
||||
[notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil];
|
||||
[notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil];
|
||||
[notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil];
|
||||
|
||||
if (task) {
|
||||
UIRefreshControl *refreshControl = self.refreshControl;
|
||||
if (task.state == NSURLSessionTaskStateRunning) {
|
||||
[refreshControl beginRefreshing];
|
||||
|
||||
[notificationCenter addObserver:self selector:@selector(af_beginRefreshing) name:AFNetworkingTaskDidResumeNotification object:task];
|
||||
[notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingTaskDidCompleteNotification object:task];
|
||||
[notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingTaskDidSuspendNotification object:task];
|
||||
} else {
|
||||
[refreshControl endRefreshing];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (void)af_beginRefreshing {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self.refreshControl beginRefreshing];
|
||||
});
|
||||
}
|
||||
|
||||
- (void)af_endRefreshing {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self.refreshControl endRefreshing];
|
||||
});
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (void)dealloc {
|
||||
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
|
||||
|
||||
[notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil];
|
||||
[notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil];
|
||||
[notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
80
Pods/AFNetworking/UIKit+AFNetworking/WKWebView+AFNetworking.h
generated
Normal file
80
Pods/AFNetworking/UIKit+AFNetworking/WKWebView+AFNetworking.h
generated
Normal file
@@ -0,0 +1,80 @@
|
||||
// WkWebView+AFNetworking.h
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#import <TargetConditionals.h>
|
||||
|
||||
#if TARGET_OS_IOS
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
#import <WebKit/WebKit.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@class AFHTTPSessionManager;
|
||||
|
||||
@interface WKWebView (AFNetworking)
|
||||
|
||||
/**
|
||||
The session manager used to download all request
|
||||
*/
|
||||
@property (nonatomic, strong) AFHTTPSessionManager *sessionManager;
|
||||
|
||||
/**
|
||||
Asynchronously loads the specified request.
|
||||
|
||||
@param request A URL request identifying the location of the content to load. This must not be `nil`.
|
||||
@param navigation The WKNavigation object that containts information for tracking the loading progress of a webpage. This must not be `nil`.
|
||||
@param progress A progress object monitoring the current download progress.
|
||||
@param success A block object to be executed when the request finishes loading successfully. This block returns the HTML string to be loaded by the web view, and takes two arguments: the response, and the response string.
|
||||
@param failure A block object to be executed when the data task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a single argument: the error that occurred.
|
||||
*/
|
||||
- (void)loadRequest:(NSURLRequest *)request
|
||||
navigation:(WKNavigation * _Nonnull)navigation
|
||||
progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress
|
||||
success:(nullable NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success
|
||||
failure:(nullable void (^)(NSError *error))failure;
|
||||
|
||||
/**
|
||||
Asynchronously loads the data associated with a particular request with a specified MIME type and text encoding.
|
||||
|
||||
@param request A URL request identifying the location of the content to load. This must not be `nil`.
|
||||
@param navigation The WKNavigation object that containts information for tracking the loading progress of a webpage. This must not be `nil`.
|
||||
@param MIMEType The MIME type of the content. Defaults to the content type of the response if not specified.
|
||||
@param textEncodingName The IANA encoding name, as in `utf-8` or `utf-16`. Defaults to the response text encoding if not specified.
|
||||
@param progress A progress object monitoring the current download progress.
|
||||
@param success A block object to be executed when the request finishes loading successfully. This block returns the data to be loaded by the web view and takes two arguments: the response, and the downloaded data.
|
||||
@param failure A block object to be executed when the data task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a single argument: the error that occurred.
|
||||
*/
|
||||
- (void)loadRequest:(NSURLRequest *)request
|
||||
navigation:(WKNavigation * _Nonnull)navigation
|
||||
MIMEType:(nullable NSString *)MIMEType
|
||||
textEncodingName:(nullable NSString *)textEncodingName
|
||||
progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress
|
||||
success:(nullable NSData * (^)(NSHTTPURLResponse *response, NSData *data))success
|
||||
failure:(nullable void (^)(NSError *error))failure;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
#endif
|
||||
154
Pods/AFNetworking/UIKit+AFNetworking/WKWebView+AFNetworking.m
generated
Normal file
154
Pods/AFNetworking/UIKit+AFNetworking/WKWebView+AFNetworking.m
generated
Normal file
@@ -0,0 +1,154 @@
|
||||
// WkWebView+AFNetworking.m
|
||||
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import "WKWebView+AFNetworking.h"
|
||||
|
||||
#import <objc/runtime.h>
|
||||
|
||||
#if TARGET_OS_IOS
|
||||
|
||||
#import "AFHTTPSessionManager.h"
|
||||
#import "AFURLResponseSerialization.h"
|
||||
#import "AFURLRequestSerialization.h"
|
||||
|
||||
@interface WKWebView (_AFNetworking)
|
||||
@property (readwrite, nonatomic, strong, setter = af_setURLSessionTask:) NSURLSessionDataTask *af_URLSessionTask;
|
||||
@end
|
||||
|
||||
@implementation WKWebView (_AFNetworking)
|
||||
|
||||
- (NSURLSessionDataTask *)af_URLSessionTask {
|
||||
return (NSURLSessionDataTask *)objc_getAssociatedObject(self, @selector(af_URLSessionTask));
|
||||
}
|
||||
|
||||
- (void)af_setURLSessionTask:(NSURLSessionDataTask *)af_URLSessionTask {
|
||||
objc_setAssociatedObject(self, @selector(af_URLSessionTask), af_URLSessionTask, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@implementation WKWebView (AFNetworking)
|
||||
|
||||
- (AFHTTPSessionManager *)sessionManager {
|
||||
static AFHTTPSessionManager *_af_defaultHTTPSessionManager = nil;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
_af_defaultHTTPSessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
|
||||
_af_defaultHTTPSessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
|
||||
_af_defaultHTTPSessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
|
||||
});
|
||||
|
||||
return objc_getAssociatedObject(self, @selector(sessionManager)) ?: _af_defaultHTTPSessionManager;
|
||||
}
|
||||
|
||||
- (void)setSessionManager:(AFHTTPSessionManager *)sessionManager {
|
||||
objc_setAssociatedObject(self, @selector(sessionManager), sessionManager, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
|
||||
}
|
||||
|
||||
- (AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer {
|
||||
static AFHTTPResponseSerializer <AFURLResponseSerialization> *_af_defaultResponseSerializer = nil;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
_af_defaultResponseSerializer = [AFHTTPResponseSerializer serializer];
|
||||
});
|
||||
|
||||
return objc_getAssociatedObject(self, @selector(responseSerializer)) ?: _af_defaultResponseSerializer;
|
||||
}
|
||||
|
||||
- (void)setResponseSerializer:(AFHTTPResponseSerializer<AFURLResponseSerialization> *)responseSerializer {
|
||||
objc_setAssociatedObject(self, @selector(responseSerializer), responseSerializer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (void)loadRequest:(NSURLRequest *)request
|
||||
navigation:(WKNavigation * _Nonnull)navigation
|
||||
progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress
|
||||
success:(nullable NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success
|
||||
failure:(nullable void (^)(NSError *error))failure {
|
||||
[self loadRequest:request navigation:navigation MIMEType:nil textEncodingName:nil progress:progress success:^NSData * _Nonnull(NSHTTPURLResponse * _Nonnull response, NSData * _Nonnull data) {
|
||||
NSStringEncoding stringEncoding = NSUTF8StringEncoding;
|
||||
if (response.textEncodingName) {
|
||||
CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)response.textEncodingName);
|
||||
if (encoding != kCFStringEncodingInvalidId) {
|
||||
stringEncoding = CFStringConvertEncodingToNSStringEncoding(encoding);
|
||||
}
|
||||
}
|
||||
|
||||
NSString *string = [[NSString alloc] initWithData:data encoding:stringEncoding];
|
||||
if (success) {
|
||||
string = success(response, string);
|
||||
}
|
||||
|
||||
return [string dataUsingEncoding:stringEncoding];
|
||||
} failure:failure];
|
||||
}
|
||||
|
||||
- (void)loadRequest:(NSURLRequest *)request
|
||||
navigation:(WKNavigation * _Nonnull)navigation
|
||||
MIMEType:(nullable NSString *)MIMEType
|
||||
textEncodingName:(nullable NSString *)textEncodingName
|
||||
progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress
|
||||
success:(nullable NSData * (^)(NSHTTPURLResponse *response, NSData *data))success
|
||||
failure:(nullable void (^)(NSError *error))failure {
|
||||
NSParameterAssert(request);
|
||||
|
||||
if (self.af_URLSessionTask.state == NSURLSessionTaskStateRunning || self.af_URLSessionTask.state == NSURLSessionTaskStateSuspended) {
|
||||
[self.af_URLSessionTask cancel];
|
||||
}
|
||||
self.af_URLSessionTask = nil;
|
||||
|
||||
__weak __typeof(self)weakSelf = self;
|
||||
__block NSURLSessionDataTask *dataTask;
|
||||
__strong __typeof(weakSelf) strongSelf = weakSelf;
|
||||
__strong __typeof(weakSelf.navigationDelegate) strongSelfDelegate = strongSelf.navigationDelegate;
|
||||
dataTask = [self.sessionManager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
|
||||
if (error) {
|
||||
if (failure) {
|
||||
failure(error);
|
||||
}
|
||||
} else {
|
||||
if (success) {
|
||||
success((NSHTTPURLResponse *)response, responseObject);
|
||||
}
|
||||
[strongSelf loadData:responseObject MIMEType:MIMEType characterEncodingName:textEncodingName baseURL:[dataTask.currentRequest URL]];
|
||||
|
||||
if ([strongSelfDelegate respondsToSelector:@selector(webView:didFinishNavigation:)]) {
|
||||
[strongSelfDelegate webView:strongSelf didFinishNavigation:navigation];
|
||||
}
|
||||
}
|
||||
}];
|
||||
self.af_URLSessionTask = dataTask;
|
||||
if (progress != nil) {
|
||||
*progress = [self.sessionManager downloadProgressForTask:dataTask];
|
||||
}
|
||||
[self.af_URLSessionTask resume];
|
||||
|
||||
if ([strongSelfDelegate respondsToSelector:@selector(webView:didStartProvisionalNavigation:)]) {
|
||||
[strongSelfDelegate webView:self didStartProvisionalNavigation:navigation];
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
BIN
Pods/Bugly/Bugly.framework/Bugly
generated
Normal file
BIN
Pods/Bugly/Bugly.framework/Bugly
generated
Normal file
Binary file not shown.
163
Pods/Bugly/Bugly.framework/Headers/Bugly.h
generated
Normal file
163
Pods/Bugly/Bugly.framework/Headers/Bugly.h
generated
Normal file
@@ -0,0 +1,163 @@
|
||||
//
|
||||
// Bugly.h
|
||||
//
|
||||
// Version: 2.6(1)
|
||||
//
|
||||
// Copyright (c) 2017年 Tencent. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#import "BuglyConfig.h"
|
||||
#import "BuglyLog.h"
|
||||
|
||||
BLY_START_NONNULL
|
||||
|
||||
@interface Bugly : NSObject
|
||||
|
||||
/**
|
||||
* 初始化Bugly,使用默认BuglyConfigs
|
||||
*
|
||||
* @param appId 注册Bugly分配的应用唯一标识
|
||||
*/
|
||||
+ (void)startWithAppId:(NSString * BLY_NULLABLE)appId;
|
||||
|
||||
/**
|
||||
* 使用指定配置初始化Bugly
|
||||
*
|
||||
* @param appId 注册Bugly分配的应用唯一标识
|
||||
* @param config 传入配置的 BuglyConfig
|
||||
*/
|
||||
+ (void)startWithAppId:(NSString * BLY_NULLABLE)appId
|
||||
config:(BuglyConfig * BLY_NULLABLE)config;
|
||||
|
||||
/**
|
||||
* 使用指定配置初始化Bugly
|
||||
*
|
||||
* @param appId 注册Bugly分配的应用唯一标识
|
||||
* @param development 是否开发设备
|
||||
* @param config 传入配置的 BuglyConfig
|
||||
*/
|
||||
+ (void)startWithAppId:(NSString * BLY_NULLABLE)appId
|
||||
developmentDevice:(BOOL)development
|
||||
config:(BuglyConfig * BLY_NULLABLE)config;
|
||||
|
||||
/**
|
||||
* 设置用户标识
|
||||
*
|
||||
* @param userId 用户标识
|
||||
*/
|
||||
+ (void)setUserIdentifier:(NSString *)userId;
|
||||
|
||||
/**
|
||||
* 更新版本信息
|
||||
*
|
||||
* @param version 应用版本信息
|
||||
*/
|
||||
+ (void)updateAppVersion:(NSString *)version;
|
||||
|
||||
/**
|
||||
* 设置关键数据,随崩溃信息上报
|
||||
*
|
||||
* @param value KEY
|
||||
* @param key VALUE
|
||||
*/
|
||||
+ (void)setUserValue:(NSString *)value
|
||||
forKey:(NSString *)key;
|
||||
|
||||
/**
|
||||
* 获取USER ID
|
||||
*
|
||||
* @return USER ID
|
||||
*/
|
||||
+ (NSString *)buglyUserIdentifier;
|
||||
|
||||
/**
|
||||
* 获取关键数据
|
||||
*
|
||||
* @return 关键数据
|
||||
*/
|
||||
+ (NSDictionary * BLY_NULLABLE)allUserValues;
|
||||
|
||||
/**
|
||||
* 设置标签
|
||||
*
|
||||
* @param tag 标签ID,可在网站生成
|
||||
*/
|
||||
+ (void)setTag:(NSUInteger)tag;
|
||||
|
||||
/**
|
||||
* 获取当前设置标签
|
||||
*
|
||||
* @return 当前标签ID
|
||||
*/
|
||||
+ (NSUInteger)currentTag;
|
||||
|
||||
/**
|
||||
* 获取设备ID
|
||||
*
|
||||
* @return 设备ID
|
||||
*/
|
||||
+ (NSString *)buglyDeviceId;
|
||||
|
||||
/**
|
||||
* 上报自定义Objective-C异常
|
||||
*
|
||||
* @param exception 异常信息
|
||||
*/
|
||||
+ (void)reportException:(NSException *)exception;
|
||||
|
||||
/**
|
||||
* 上报错误
|
||||
*
|
||||
* @param error 错误信息
|
||||
*/
|
||||
+ (void)reportError:(NSError *)error;
|
||||
|
||||
/**
|
||||
* @brief 上报自定义错误
|
||||
*
|
||||
* @param category 类型(Cocoa=3,CSharp=4,JS=5,Lua=6)
|
||||
* @param aName 名称
|
||||
* @param aReason 错误原因
|
||||
* @param aStackArray 堆栈
|
||||
* @param info 附加数据
|
||||
* @param terminate 上报后是否退出应用进程
|
||||
*/
|
||||
+ (void)reportExceptionWithCategory:(NSUInteger)category
|
||||
name:(NSString *)aName
|
||||
reason:(NSString *)aReason
|
||||
callStack:(NSArray *)aStackArray
|
||||
extraInfo:(NSDictionary *)info
|
||||
terminateApp:(BOOL)terminate;
|
||||
|
||||
/**
|
||||
* SDK 版本信息
|
||||
*
|
||||
* @return SDK版本号
|
||||
*/
|
||||
+ (NSString *)sdkVersion;
|
||||
|
||||
/**
|
||||
* APP 版本信息
|
||||
*
|
||||
* @return SDK版本号
|
||||
*/
|
||||
+ (NSString *)appVersion;
|
||||
|
||||
/**
|
||||
* App 是否发生了连续闪退
|
||||
* 如果 启动SDK 且 5秒内 闪退,且次数达到 3次 则判定为连续闪退
|
||||
*
|
||||
* @return 是否连续闪退
|
||||
*/
|
||||
+ (BOOL)isAppCrashedOnStartUpExceedTheLimit;
|
||||
|
||||
/**
|
||||
* 关闭bugly监控
|
||||
*/
|
||||
+ (void)closeCrashReport;
|
||||
|
||||
BLY_END_NONNULL
|
||||
|
||||
@end
|
||||
149
Pods/Bugly/Bugly.framework/Headers/BuglyConfig.h
generated
Normal file
149
Pods/Bugly/Bugly.framework/Headers/BuglyConfig.h
generated
Normal file
@@ -0,0 +1,149 @@
|
||||
//
|
||||
// BuglyConfig.h
|
||||
// Bugly
|
||||
//
|
||||
// Copyright (c) 2016年 Tencent. All rights reserved.
|
||||
//
|
||||
|
||||
#pragma once
|
||||
|
||||
#define BLY_UNAVAILABLE(x) __attribute__((unavailable(x)))
|
||||
|
||||
#if __has_feature(nullability)
|
||||
#define BLY_NONNULL __nonnull
|
||||
#define BLY_NULLABLE __nullable
|
||||
#define BLY_START_NONNULL _Pragma("clang assume_nonnull begin")
|
||||
#define BLY_END_NONNULL _Pragma("clang assume_nonnull end")
|
||||
#else
|
||||
#define BLY_NONNULL
|
||||
#define BLY_NULLABLE
|
||||
#define BLY_START_NONNULL
|
||||
#define BLY_END_NONNULL
|
||||
#endif
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#import "BuglyLog.h"
|
||||
|
||||
BLY_START_NONNULL
|
||||
|
||||
@protocol BuglyDelegate <NSObject>
|
||||
|
||||
@optional
|
||||
/**
|
||||
* 发生异常时回调
|
||||
*
|
||||
* @param exception 异常信息
|
||||
*
|
||||
* @return 返回需上报记录,随异常上报一起上报
|
||||
*/
|
||||
- (NSString * BLY_NULLABLE)attachmentForException:(NSException * BLY_NULLABLE)exception;
|
||||
|
||||
/**
|
||||
* 发生sigkill时回调
|
||||
*
|
||||
* @param exception 异常信息
|
||||
*
|
||||
* @return 返回需上报记录,随sigkill异常上报一起上报,返回值由app开发者决定
|
||||
*/
|
||||
- (NSString * BLY_NULLABLE)attachmentForSigkill;
|
||||
|
||||
/**
|
||||
* 策略激活时回调
|
||||
*
|
||||
* @param tacticInfo
|
||||
*
|
||||
* @return app是否弹框展示
|
||||
*/
|
||||
- (BOOL) h5AlertForTactic:(NSDictionary *)tacticInfo;
|
||||
|
||||
@end
|
||||
|
||||
@interface BuglyConfig : NSObject
|
||||
|
||||
/**
|
||||
* SDK Debug信息开关, 默认关闭
|
||||
*/
|
||||
@property (nonatomic, assign) BOOL debugMode;
|
||||
|
||||
/**
|
||||
* 设置自定义渠道标识
|
||||
*/
|
||||
@property (nonatomic, copy) NSString *channel;
|
||||
|
||||
/**
|
||||
* 设置自定义版本号
|
||||
*/
|
||||
@property (nonatomic, copy) NSString *version;
|
||||
|
||||
/**
|
||||
* 设置自定义设备唯一标识
|
||||
*/
|
||||
@property (nonatomic, copy) NSString *deviceIdentifier;
|
||||
|
||||
/**
|
||||
* 卡顿监控开关,默认关闭
|
||||
*/
|
||||
@property (nonatomic) BOOL blockMonitorEnable;
|
||||
|
||||
/**
|
||||
* 卡顿监控判断间隔,单位为秒
|
||||
*/
|
||||
@property (nonatomic) NSTimeInterval blockMonitorTimeout;
|
||||
|
||||
/**
|
||||
* 设置 App Groups Id (如有使用 Bugly iOS Extension SDK,请设置该值)
|
||||
*/
|
||||
@property (nonatomic, copy) NSString *applicationGroupIdentifier;
|
||||
|
||||
/**
|
||||
* 进程内还原开关,默认开启
|
||||
*/
|
||||
@property (nonatomic) BOOL symbolicateInProcessEnable;
|
||||
|
||||
/**
|
||||
* 非正常退出事件记录开关,默认关闭
|
||||
*/
|
||||
@property (nonatomic) BOOL unexpectedTerminatingDetectionEnable;
|
||||
|
||||
/**
|
||||
* 页面信息记录开关,默认开启
|
||||
*/
|
||||
@property (nonatomic) BOOL viewControllerTrackingEnable;
|
||||
|
||||
/**
|
||||
* Bugly Delegate
|
||||
*/
|
||||
@property (nonatomic, assign) id<BuglyDelegate> delegate;
|
||||
|
||||
/**
|
||||
* 控制自定义日志上报,默认值为BuglyLogLevelSilent,即关闭日志记录功能。
|
||||
* 如果设置为BuglyLogLevelWarn,则在崩溃时会上报Warn、Error接口打印的日志
|
||||
*/
|
||||
@property (nonatomic, assign) BuglyLogLevel reportLogLevel;
|
||||
|
||||
/**
|
||||
* 崩溃数据过滤器,如果崩溃堆栈的模块名包含过滤器中设置的关键字,则崩溃数据不会进行上报
|
||||
* 例如,过滤崩溃堆栈中包含搜狗输入法的数据,可以添加过滤器关键字SogouInputIPhone.dylib等
|
||||
*/
|
||||
@property (nonatomic, copy) NSArray *excludeModuleFilter;
|
||||
|
||||
/**
|
||||
* 控制台日志上报开关,默认开启
|
||||
*/
|
||||
@property (nonatomic, assign) BOOL consolelogEnable;
|
||||
|
||||
/**
|
||||
* 崩溃退出超时,如果监听到崩溃后,App一直没有退出,则到达超时时间后会自动abort进程退出
|
||||
* 默认值 5s, 单位 秒
|
||||
* 当赋值为0时,则不会自动abort进程退出
|
||||
*/
|
||||
@property (nonatomic, assign) NSUInteger crashAbortTimeout;
|
||||
|
||||
/**
|
||||
* 设置自定义联网、crash上报域名
|
||||
*/
|
||||
@property (nonatomic, copy) NSString *crashServerUrl;
|
||||
|
||||
@end
|
||||
BLY_END_NONNULL
|
||||
78
Pods/Bugly/Bugly.framework/Headers/BuglyLog.h
generated
Normal file
78
Pods/Bugly/Bugly.framework/Headers/BuglyLog.h
generated
Normal file
@@ -0,0 +1,78 @@
|
||||
//
|
||||
// BuglyLog.h
|
||||
// Bugly
|
||||
//
|
||||
// Copyright (c) 2017年 Tencent. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
// Log level for Bugly Log
|
||||
typedef NS_ENUM(NSUInteger, BuglyLogLevel) {
|
||||
BuglyLogLevelSilent = 0,
|
||||
BuglyLogLevelError = 1,
|
||||
BuglyLogLevelWarn = 2,
|
||||
BuglyLogLevelInfo = 3,
|
||||
BuglyLogLevelDebug = 4,
|
||||
BuglyLogLevelVerbose = 5,
|
||||
};
|
||||
#pragma mark -
|
||||
|
||||
OBJC_EXTERN void BLYLog(BuglyLogLevel level, NSString *format, ...) NS_FORMAT_FUNCTION(2, 3);
|
||||
|
||||
OBJC_EXTERN void BLYLogv(BuglyLogLevel level, NSString *format, va_list args) NS_FORMAT_FUNCTION(2, 0);
|
||||
|
||||
#pragma mark -
|
||||
#define BUGLY_LOG_MACRO(_level, fmt, ...) [BuglyLog level:_level tag:nil log:fmt, ##__VA_ARGS__]
|
||||
|
||||
#define BLYLogError(fmt, ...) BUGLY_LOG_MACRO(BuglyLogLevelError, fmt, ##__VA_ARGS__)
|
||||
#define BLYLogWarn(fmt, ...) BUGLY_LOG_MACRO(BuglyLogLevelWarn, fmt, ##__VA_ARGS__)
|
||||
#define BLYLogInfo(fmt, ...) BUGLY_LOG_MACRO(BuglyLogLevelInfo, fmt, ##__VA_ARGS__)
|
||||
#define BLYLogDebug(fmt, ...) BUGLY_LOG_MACRO(BuglyLogLevelDebug, fmt, ##__VA_ARGS__)
|
||||
#define BLYLogVerbose(fmt, ...) BUGLY_LOG_MACRO(BuglyLogLevelVerbose, fmt, ##__VA_ARGS__)
|
||||
|
||||
#pragma mark - Interface
|
||||
@interface BuglyLog : NSObject
|
||||
|
||||
/**
|
||||
* @brief 初始化日志模块
|
||||
*
|
||||
* @param level 设置默认日志级别,默认BLYLogLevelSilent
|
||||
*
|
||||
* @param printConsole 是否打印到控制台,默认NO
|
||||
*/
|
||||
+ (void)initLogger:(BuglyLogLevel) level consolePrint:(BOOL)printConsole;
|
||||
|
||||
/**
|
||||
* @brief 打印BLYLogLevelInfo日志
|
||||
*
|
||||
* @param format 日志内容 总日志大小限制为:字符串长度30k,条数200
|
||||
*/
|
||||
+ (void)log:(NSString *)format, ... NS_FORMAT_FUNCTION(1, 2);
|
||||
|
||||
/**
|
||||
* @brief 打印日志
|
||||
*
|
||||
* @param level 日志级别
|
||||
* @param message 日志内容 总日志大小限制为:字符串长度30k,条数200
|
||||
*/
|
||||
+ (void)level:(BuglyLogLevel) level logs:(NSString *)message;
|
||||
|
||||
/**
|
||||
* @brief 打印日志
|
||||
*
|
||||
* @param level 日志级别
|
||||
* @param format 日志内容 总日志大小限制为:字符串长度30k,条数200
|
||||
*/
|
||||
+ (void)level:(BuglyLogLevel) level log:(NSString *)format, ... NS_FORMAT_FUNCTION(2, 3);
|
||||
|
||||
/**
|
||||
* @brief 打印日志
|
||||
*
|
||||
* @param level 日志级别
|
||||
* @param tag 日志模块分类
|
||||
* @param format 日志内容 总日志大小限制为:字符串长度30k,条数200
|
||||
*/
|
||||
+ (void)level:(BuglyLogLevel) level tag:(NSString *) tag log:(NSString *)format, ... NS_FORMAT_FUNCTION(3, 4);
|
||||
|
||||
@end
|
||||
12
Pods/Bugly/Bugly.framework/Modules/module.modulemap
generated
Normal file
12
Pods/Bugly/Bugly.framework/Modules/module.modulemap
generated
Normal file
@@ -0,0 +1,12 @@
|
||||
framework module Bugly {
|
||||
umbrella header "Bugly.h"
|
||||
|
||||
export *
|
||||
module * { export * }
|
||||
|
||||
link framework "Foundation"
|
||||
link framework "Security"
|
||||
link framework "SystemConfiguration"
|
||||
link "c++"
|
||||
link "z"
|
||||
}
|
||||
41
Pods/Bugly/Bugly.framework/PrivacyInfo.xcprivacy
generated
Normal file
41
Pods/Bugly/Bugly.framework/PrivacyInfo.xcprivacy
generated
Normal file
@@ -0,0 +1,41 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>NSPrivacyAccessedAPITypes</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>NSPrivacyAccessedAPIType</key>
|
||||
<string>NSPrivacyAccessedAPICategoryFileTimestamp</string>
|
||||
<key>NSPrivacyAccessedAPITypeReasons</key>
|
||||
<array>
|
||||
<string>C617.1</string>
|
||||
</array>
|
||||
</dict>
|
||||
<dict>
|
||||
<key>NSPrivacyAccessedAPIType</key>
|
||||
<string>NSPrivacyAccessedAPICategorySystemBootTime</string>
|
||||
<key>NSPrivacyAccessedAPITypeReasons</key>
|
||||
<array>
|
||||
<string>35F9.1</string>
|
||||
</array>
|
||||
</dict>
|
||||
<dict>
|
||||
<key>NSPrivacyAccessedAPIType</key>
|
||||
<string>NSPrivacyAccessedAPICategoryDiskSpace</string>
|
||||
<key>NSPrivacyAccessedAPITypeReasons</key>
|
||||
<array>
|
||||
<string>E174.1</string>
|
||||
</array>
|
||||
</dict>
|
||||
<dict>
|
||||
<key>NSPrivacyAccessedAPIType</key>
|
||||
<string>NSPrivacyAccessedAPICategoryUserDefaults</string>
|
||||
<key>NSPrivacyAccessedAPITypeReasons</key>
|
||||
<array>
|
||||
<string>CA92.1</string>
|
||||
</array>
|
||||
</dict>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
9
Pods/DZNEmptyDataSet/LICENSE
generated
Normal file
9
Pods/DZNEmptyDataSet/LICENSE
generated
Normal file
@@ -0,0 +1,9 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2016 Ignacio Romero Zurbuchen iromero@dzen.cl
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
296
Pods/DZNEmptyDataSet/README.md
generated
Normal file
296
Pods/DZNEmptyDataSet/README.md
generated
Normal file
@@ -0,0 +1,296 @@
|
||||
DZNEmptyDataSet
|
||||
=================
|
||||
|
||||
[](http://cocoadocs.org/docsets/DZNEmptyDataSet/)
|
||||
[](https://github.com/Carthage/Carthage)
|
||||
[](http://opensource.org/licenses/MIT)
|
||||
|
||||
### Projects using this library
|
||||
|
||||
[Add your project to the list here](https://github.com/dzenbot/DZNEmptyDataSet/wiki/Projects-using-DZNEmptyDataSet) and provide a (320px wide) render of the result.
|
||||
|
||||
|
||||
### The Empty Data Set Pattern
|
||||
Also known as *[Empty State](http://emptystat.es/)* or *[Blank Slate](http://patternry.com/p=blank-slate/)*.
|
||||
|
||||
Most applications show lists of content (data sets), which many turn out to be empty at one point, specially for new users with blank accounts. Empty screens create confusion by not being clear about what's going on, if there is an error/bug or if the user is supposed to do something within your app to be able to consume the content.
|
||||
|
||||
Please read this very interesting article about [*Designing For The Empty States*](http://tympanus.net/codrops/2013/01/09/designing-for-the-empty-states/).
|
||||
|
||||

|
||||

|
||||
(*These are real life examples, available in the 'Applications' sample project*)
|
||||
|
||||
**[Empty Data Sets](http://pttrns.com/?did=1&scid=30)** are helpful for:
|
||||
* Avoiding white-screens and communicating to your users why the screen is empty.
|
||||
* Calling to action (particularly as an onboarding process).
|
||||
* Avoiding other interruptive mechanisms like showing error alerts.
|
||||
* Being consistent and improving the user experience.
|
||||
* Delivering a brand presence.
|
||||
|
||||
|
||||
### Features
|
||||
* Compatible with UITableView and UICollectionView. Also compatible with UISearchDisplayController and UIScrollView.
|
||||
* Gives multiple possibilities of layout and appearance, by showing an image and/or title label and/or description label and/or button.
|
||||
* Uses NSAttributedString for easier appearance customisation.
|
||||
* Uses auto-layout to automagically center the content to the tableview, with auto-rotation support. Also accepts custom vertical and horizontal alignment.
|
||||
* Background color customisation.
|
||||
* Allows tap gesture on the whole tableview rectangle (useful for resigning first responder or similar actions).
|
||||
* For more advanced customisation, it allows a custom view.
|
||||
* Compatible with Storyboard.
|
||||
* Compatible with iOS 6 or later.
|
||||
* Compatible with iPhone and iPad.
|
||||
* **App Store ready**
|
||||
|
||||
This library has been designed in a way where you won't need to extend UITableView or UICollectionView class. It will still work when using UITableViewController or UICollectionViewController.
|
||||
By just conforming to DZNEmptyDataSetSource & DZNEmptyDataSetDelegate, you will be able to fully customize the content and appearance of the empty states for your application.
|
||||
|
||||
|
||||
## Installation
|
||||
|
||||
Available in [CocoaPods](http://cocoapods.org/?q=DZNEmptyDataSet)
|
||||
```ruby
|
||||
pod 'DZNEmptyDataSet'
|
||||
```
|
||||
|
||||
To integrate DZNEmptyDataSet into your Xcode project using Carthage, specify it in your `Cartfile`:
|
||||
|
||||
```ruby
|
||||
github "dzenbot/DZNEmptyDataSet"
|
||||
```
|
||||
|
||||
|
||||
## How to use
|
||||
For complete documentation, [visit CocoaPods' auto-generated doc](http://cocoadocs.org/docsets/DZNEmptyDataSet/)
|
||||
|
||||
### Import
|
||||
```objc
|
||||
#import "UIScrollView+EmptyDataSet.h"
|
||||
```
|
||||
Unless you are importing as a framework, then do:
|
||||
```objc
|
||||
#import "<DZNEmptyDataSet/UIScrollView+EmptyDataSet.h>"
|
||||
```
|
||||
|
||||
### Protocol Conformance
|
||||
Conform to datasource and/or delegate.
|
||||
```objc
|
||||
@interface MainViewController : UITableViewController <DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>
|
||||
|
||||
- (void)viewDidLoad
|
||||
{
|
||||
[super viewDidLoad];
|
||||
|
||||
self.tableView.emptyDataSetSource = self;
|
||||
self.tableView.emptyDataSetDelegate = self;
|
||||
|
||||
// A little trick for removing the cell separators
|
||||
self.tableView.tableFooterView = [UIView new];
|
||||
}
|
||||
```
|
||||
|
||||
### Data Source Implementation
|
||||
Return the content you want to show on the empty state, and take advantage of NSAttributedString features to customise the text appearance.
|
||||
|
||||
The image for the empty state:
|
||||
```objc
|
||||
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
|
||||
{
|
||||
return [UIImage imageNamed:@"empty_placeholder"];
|
||||
}
|
||||
```
|
||||
|
||||
The image view animation
|
||||
```objc
|
||||
- (CAAnimation *)imageAnimationForEmptyDataSet:(UIScrollView *)scrollView
|
||||
{
|
||||
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath: @"transform"];
|
||||
|
||||
animation.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
|
||||
animation.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeRotation(M_PI_2, 0.0, 0.0, 1.0)];
|
||||
|
||||
animation.duration = 0.25;
|
||||
animation.cumulative = YES;
|
||||
animation.repeatCount = MAXFLOAT;
|
||||
|
||||
return animation;
|
||||
}
|
||||
```
|
||||
|
||||
The attributed string for the title of the empty state:
|
||||
```objc
|
||||
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
|
||||
{
|
||||
NSString *text = @"Please Allow Photo Access";
|
||||
|
||||
NSDictionary *attributes = @{NSFontAttributeName: [UIFont boldSystemFontOfSize:18.0f],
|
||||
NSForegroundColorAttributeName: [UIColor darkGrayColor]};
|
||||
|
||||
return [[NSAttributedString alloc] initWithString:text attributes:attributes];
|
||||
}
|
||||
```
|
||||
|
||||
The attributed string for the description of the empty state:
|
||||
```objc
|
||||
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
|
||||
{
|
||||
NSString *text = @"This allows you to share photos from your library and save photos to your camera roll.";
|
||||
|
||||
NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
|
||||
paragraph.lineBreakMode = NSLineBreakByWordWrapping;
|
||||
paragraph.alignment = NSTextAlignmentCenter;
|
||||
|
||||
NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0f],
|
||||
NSForegroundColorAttributeName: [UIColor lightGrayColor],
|
||||
NSParagraphStyleAttributeName: paragraph};
|
||||
|
||||
return [[NSAttributedString alloc] initWithString:text attributes:attributes];
|
||||
}
|
||||
```
|
||||
|
||||
The attributed string to be used for the specified button state:
|
||||
```objc
|
||||
- (NSAttributedString *)buttonTitleForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state
|
||||
{
|
||||
NSDictionary *attributes = @{NSFontAttributeName: [UIFont boldSystemFontOfSize:17.0f]};
|
||||
|
||||
return [[NSAttributedString alloc] initWithString:@"Continue" attributes:attributes];
|
||||
}
|
||||
```
|
||||
|
||||
or the image to be used for the specified button state:
|
||||
```objc
|
||||
- (UIImage *)buttonImageForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state
|
||||
{
|
||||
return [UIImage imageNamed:@"button_image"];
|
||||
}
|
||||
```
|
||||
|
||||
The background color for the empty state:
|
||||
```objc
|
||||
- (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
|
||||
{
|
||||
return [UIColor whiteColor];
|
||||
}
|
||||
```
|
||||
|
||||
If you need a more complex layout, you can return a custom view instead:
|
||||
```objc
|
||||
- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView
|
||||
{
|
||||
UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
|
||||
[activityView startAnimating];
|
||||
return activityView;
|
||||
}
|
||||
```
|
||||
|
||||
Additionally, you can also adjust the vertical alignment of the content view (ie: useful when there is tableHeaderView visible):
|
||||
```objc
|
||||
- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView
|
||||
{
|
||||
return -self.tableView.tableHeaderView.frame.size.height/2.0f;
|
||||
}
|
||||
```
|
||||
|
||||
Finally, you can separate components from each other (default separation is 11 pts):
|
||||
```objc
|
||||
- (CGFloat)spaceHeightForEmptyDataSet:(UIScrollView *)scrollView
|
||||
{
|
||||
return 20.0f;
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### Delegate Implementation
|
||||
Return the behaviours you would expect from the empty states, and receive the user events.
|
||||
|
||||
Asks to know if the empty state should be rendered and displayed (Default is YES) :
|
||||
```objc
|
||||
- (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView
|
||||
{
|
||||
return YES;
|
||||
}
|
||||
```
|
||||
|
||||
Asks for interaction permission (Default is YES) :
|
||||
```objc
|
||||
- (BOOL)emptyDataSetShouldAllowTouch:(UIScrollView *)scrollView
|
||||
{
|
||||
return YES;
|
||||
}
|
||||
```
|
||||
|
||||
Asks for scrolling permission (Default is NO) :
|
||||
```objc
|
||||
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
|
||||
{
|
||||
return YES;
|
||||
}
|
||||
```
|
||||
|
||||
Asks for image view animation permission (Default is NO) :
|
||||
```objc
|
||||
- (BOOL) emptyDataSetShouldAllowImageViewAnimate:(UIScrollView *)scrollView
|
||||
{
|
||||
return YES;
|
||||
}
|
||||
```
|
||||
|
||||
Notifies when the dataset view was tapped:
|
||||
```objc
|
||||
- (void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view
|
||||
{
|
||||
// Do something
|
||||
}
|
||||
```
|
||||
|
||||
Notifies when the data set call to action button was tapped:
|
||||
```objc
|
||||
- (void)emptyDataSet:(UIScrollView *)scrollView didTapButton:(UIButton *)button
|
||||
{
|
||||
// Do something
|
||||
}
|
||||
```
|
||||
|
||||
### Refresh layout
|
||||
If you need to refresh the empty state layout, simply call:
|
||||
|
||||
```objc
|
||||
[self.tableView reloadData];
|
||||
```
|
||||
or
|
||||
```objc
|
||||
[self.collectionView reloadData];
|
||||
```
|
||||
depending of which you are using.
|
||||
|
||||
### Force layout update
|
||||
You can also call `[self.tableView reloadEmptyDataSet]` to invalidate the current empty state layout and trigger a layout update, bypassing `-reloadData`. This might be useful if you have a lot of logic on your data source that you want to avoid calling, when not needed. `[self.scrollView reloadEmptyDataSet]` is the only way to refresh content when using with UIScrollView.
|
||||
|
||||
|
||||
## Sample projects
|
||||
|
||||
#### Applications
|
||||
This project replicates several popular application's empty states (~20) with their exact content and appearance, such as Airbnb, Dropbox, Facebook, Foursquare, and many others. See how easy and flexible it is to customize the appearance of your empty states. You can also use this project as a playground to test things.
|
||||
|
||||
#### Countries
|
||||
This project shows a list of the world countries loaded from CoreData. It uses NSFecthedResultController for filtering search. When searching and no content is matched, a simple empty state is shown. See how to interact between the UITableViewDataSource and the DZNEmptyDataSetSource protocols, while using a typical CoreData stack.
|
||||
|
||||
#### Colors
|
||||
This project is a simple example of how this library also works with UICollectionView and UISearchDisplayController, while using Storyboards.
|
||||
|
||||
|
||||
## Collaboration
|
||||
Feel free to collaborate with ideas, issues and/or pull requests.
|
||||
|
||||
|
||||
## License
|
||||
(The MIT License)
|
||||
|
||||
Copyright (c) 2016 Ignacio Romero Zurbuchen iromero@dzen.cl
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
280
Pods/DZNEmptyDataSet/Source/UIScrollView+EmptyDataSet.h
generated
Normal file
280
Pods/DZNEmptyDataSet/Source/UIScrollView+EmptyDataSet.h
generated
Normal file
@@ -0,0 +1,280 @@
|
||||
//
|
||||
// UIScrollView+EmptyDataSet.h
|
||||
// DZNEmptyDataSet
|
||||
// https://github.com/dzenbot/DZNEmptyDataSet
|
||||
//
|
||||
// Created by Ignacio Romero Zurbuchen on 6/20/14.
|
||||
// Copyright (c) 2016 DZN Labs. All rights reserved.
|
||||
// Licence: MIT-Licence
|
||||
//
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
@protocol DZNEmptyDataSetSource;
|
||||
@protocol DZNEmptyDataSetDelegate;
|
||||
|
||||
#define DZNEmptyDataSetDeprecated(instead) DEPRECATED_MSG_ATTRIBUTE(" Use " # instead " instead")
|
||||
|
||||
/**
|
||||
A drop-in UITableView/UICollectionView superclass category for showing empty datasets whenever the view has no content to display.
|
||||
@discussion It will work automatically, by just conforming to DZNEmptyDataSetSource, and returning the data you want to show.
|
||||
*/
|
||||
@interface UIScrollView (EmptyDataSet)
|
||||
|
||||
/** The empty datasets data source. */
|
||||
@property (nonatomic, weak) IBOutlet id <DZNEmptyDataSetSource> emptyDataSetSource;
|
||||
/** The empty datasets delegate. */
|
||||
@property (nonatomic, weak) IBOutlet id <DZNEmptyDataSetDelegate> emptyDataSetDelegate;
|
||||
/** YES if any empty dataset is visible. */
|
||||
@property (nonatomic, readonly, getter = isEmptyDataSetVisible) BOOL emptyDataSetVisible;
|
||||
|
||||
/**
|
||||
Reloads the empty dataset content receiver.
|
||||
@discussion Call this method to force all the data to refresh. Calling -reloadData is similar, but this forces only the empty dataset to reload, not the entire table view or collection view.
|
||||
*/
|
||||
- (void)reloadEmptyDataSet;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
/**
|
||||
The object that acts as the data source of the empty datasets.
|
||||
@discussion The data source must adopt the DZNEmptyDataSetSource protocol. The data source is not retained. All data source methods are optional.
|
||||
*/
|
||||
@protocol DZNEmptyDataSetSource <NSObject>
|
||||
@optional
|
||||
|
||||
/**
|
||||
Asks the data source for the title of the dataset.
|
||||
The dataset uses a fixed font style by default, if no attributes are set. If you want a different font style, return a attributed string.
|
||||
|
||||
@param scrollView A scrollView subclass informing the data source.
|
||||
@return An attributed string for the dataset title, combining font, text color, text pararaph style, etc.
|
||||
*/
|
||||
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView;
|
||||
|
||||
/**
|
||||
Asks the data source for the description of the dataset.
|
||||
The dataset uses a fixed font style by default, if no attributes are set. If you want a different font style, return a attributed string.
|
||||
|
||||
@param scrollView A scrollView subclass informing the data source.
|
||||
@return An attributed string for the dataset description text, combining font, text color, text pararaph style, etc.
|
||||
*/
|
||||
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView;
|
||||
|
||||
/**
|
||||
Asks the data source for the image of the dataset.
|
||||
|
||||
@param scrollView A scrollView subclass informing the data source.
|
||||
@return An image for the dataset.
|
||||
*/
|
||||
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView;
|
||||
|
||||
|
||||
/**
|
||||
Asks the data source for a tint color of the image dataset. Default is nil.
|
||||
|
||||
@param scrollView A scrollView subclass object informing the data source.
|
||||
@return A color to tint the image of the dataset.
|
||||
*/
|
||||
- (UIColor *)imageTintColorForEmptyDataSet:(UIScrollView *)scrollView;
|
||||
|
||||
/**
|
||||
* Asks the data source for the image animation of the dataset.
|
||||
*
|
||||
* @param scrollView A scrollView subclass object informing the delegate.
|
||||
*
|
||||
* @return image animation
|
||||
*/
|
||||
- (CAAnimation *) imageAnimationForEmptyDataSet:(UIScrollView *) scrollView;
|
||||
|
||||
/**
|
||||
Asks the data source for the title to be used for the specified button state.
|
||||
The dataset uses a fixed font style by default, if no attributes are set. If you want a different font style, return a attributed string.
|
||||
|
||||
@param scrollView A scrollView subclass object informing the data source.
|
||||
@param state The state that uses the specified title. The possible values are described in UIControlState.
|
||||
@return An attributed string for the dataset button title, combining font, text color, text pararaph style, etc.
|
||||
*/
|
||||
- (NSAttributedString *)buttonTitleForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state;
|
||||
|
||||
/**
|
||||
Asks the data source for the image to be used for the specified button state.
|
||||
This method will override buttonTitleForEmptyDataSet:forState: and present the image only without any text.
|
||||
|
||||
@param scrollView A scrollView subclass object informing the data source.
|
||||
@param state The state that uses the specified title. The possible values are described in UIControlState.
|
||||
@return An image for the dataset button imageview.
|
||||
*/
|
||||
- (UIImage *)buttonImageForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state;
|
||||
|
||||
/**
|
||||
Asks the data source for a background image to be used for the specified button state.
|
||||
There is no default style for this call.
|
||||
|
||||
@param scrollView A scrollView subclass informing the data source.
|
||||
@param state The state that uses the specified image. The values are described in UIControlState.
|
||||
@return An attributed string for the dataset button title, combining font, text color, text pararaph style, etc.
|
||||
*/
|
||||
- (UIImage *)buttonBackgroundImageForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state;
|
||||
|
||||
/**
|
||||
Asks the data source for the background color of the dataset. Default is clear color.
|
||||
|
||||
@param scrollView A scrollView subclass object informing the data source.
|
||||
@return A color to be applied to the dataset background view.
|
||||
*/
|
||||
- (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView;
|
||||
|
||||
/**
|
||||
Asks the data source for a custom view to be displayed instead of the default views such as labels, imageview and button. Default is nil.
|
||||
Use this method to show an activity view indicator for loading feedback, or for complete custom empty data set.
|
||||
Returning a custom view will ignore -offsetForEmptyDataSet and -spaceHeightForEmptyDataSet configurations.
|
||||
|
||||
@param scrollView A scrollView subclass object informing the delegate.
|
||||
@return The custom view.
|
||||
*/
|
||||
- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView;
|
||||
|
||||
/**
|
||||
Asks the data source for a offset for vertical and horizontal alignment of the content. Default is CGPointZero.
|
||||
|
||||
@param scrollView A scrollView subclass object informing the delegate.
|
||||
@return The offset for vertical and horizontal alignment.
|
||||
*/
|
||||
- (CGPoint)offsetForEmptyDataSet:(UIScrollView *)scrollView DZNEmptyDataSetDeprecated(-verticalOffsetForEmptyDataSet:);
|
||||
- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView;
|
||||
|
||||
/**
|
||||
Asks the data source for a vertical space between elements. Default is 11 pts.
|
||||
|
||||
@param scrollView A scrollView subclass object informing the delegate.
|
||||
@return The space height between elements.
|
||||
*/
|
||||
- (CGFloat)spaceHeightForEmptyDataSet:(UIScrollView *)scrollView;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
/**
|
||||
The object that acts as the delegate of the empty datasets.
|
||||
@discussion The delegate can adopt the DZNEmptyDataSetDelegate protocol. The delegate is not retained. All delegate methods are optional.
|
||||
|
||||
@discussion All delegate methods are optional. Use this delegate for receiving action callbacks.
|
||||
*/
|
||||
@protocol DZNEmptyDataSetDelegate <NSObject>
|
||||
@optional
|
||||
|
||||
/**
|
||||
Asks the delegate to know if the empty dataset should fade in when displayed. Default is YES.
|
||||
|
||||
@param scrollView A scrollView subclass object informing the delegate.
|
||||
@return YES if the empty dataset should fade in.
|
||||
*/
|
||||
- (BOOL)emptyDataSetShouldFadeIn:(UIScrollView *)scrollView;
|
||||
|
||||
/**
|
||||
Asks the delegate to know if the empty dataset should still be displayed when the amount of items is more than 0. Default is NO
|
||||
|
||||
@param scrollView A scrollView subclass object informing the delegate.
|
||||
@return YES if empty dataset should be forced to display
|
||||
*/
|
||||
- (BOOL)emptyDataSetShouldBeForcedToDisplay:(UIScrollView *)scrollView;
|
||||
|
||||
/**
|
||||
Asks the delegate to know if the empty dataset should be rendered and displayed. Default is YES.
|
||||
|
||||
@param scrollView A scrollView subclass object informing the delegate.
|
||||
@return YES if the empty dataset should show.
|
||||
*/
|
||||
- (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView;
|
||||
|
||||
/**
|
||||
Asks the delegate for touch permission. Default is YES.
|
||||
|
||||
@param scrollView A scrollView subclass object informing the delegate.
|
||||
@return YES if the empty dataset receives touch gestures.
|
||||
*/
|
||||
- (BOOL)emptyDataSetShouldAllowTouch:(UIScrollView *)scrollView;
|
||||
|
||||
/**
|
||||
Asks the delegate for scroll permission. Default is NO.
|
||||
|
||||
@param scrollView A scrollView subclass object informing the delegate.
|
||||
@return YES if the empty dataset is allowed to be scrollable.
|
||||
*/
|
||||
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView;
|
||||
|
||||
/**
|
||||
Asks the delegate for image view animation permission. Default is NO.
|
||||
Make sure to return a valid CAAnimation object from imageAnimationForEmptyDataSet:
|
||||
|
||||
@param scrollView A scrollView subclass object informing the delegate.
|
||||
@return YES if the empty dataset is allowed to animate
|
||||
*/
|
||||
- (BOOL)emptyDataSetShouldAnimateImageView:(UIScrollView *)scrollView;
|
||||
|
||||
/**
|
||||
Tells the delegate that the empty dataset view was tapped.
|
||||
Use this method either to resignFirstResponder of a textfield or searchBar.
|
||||
|
||||
@param scrollView A scrollView subclass informing the delegate.
|
||||
*/
|
||||
- (void)emptyDataSetDidTapView:(UIScrollView *)scrollView DZNEmptyDataSetDeprecated(-emptyDataSet:didTapView:);
|
||||
|
||||
/**
|
||||
Tells the delegate that the action button was tapped.
|
||||
|
||||
@param scrollView A scrollView subclass informing the delegate.
|
||||
*/
|
||||
- (void)emptyDataSetDidTapButton:(UIScrollView *)scrollView DZNEmptyDataSetDeprecated(-emptyDataSet:didTapButton:);
|
||||
|
||||
/**
|
||||
Tells the delegate that the empty dataset view was tapped.
|
||||
Use this method either to resignFirstResponder of a textfield or searchBar.
|
||||
|
||||
@param scrollView A scrollView subclass informing the delegate.
|
||||
@param view the view tapped by the user
|
||||
*/
|
||||
- (void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view;
|
||||
|
||||
/**
|
||||
Tells the delegate that the action button was tapped.
|
||||
|
||||
@param scrollView A scrollView subclass informing the delegate.
|
||||
@param button the button tapped by the user
|
||||
*/
|
||||
- (void)emptyDataSet:(UIScrollView *)scrollView didTapButton:(UIButton *)button;
|
||||
|
||||
/**
|
||||
Tells the delegate that the empty data set will appear.
|
||||
|
||||
@param scrollView A scrollView subclass informing the delegate.
|
||||
*/
|
||||
- (void)emptyDataSetWillAppear:(UIScrollView *)scrollView;
|
||||
|
||||
/**
|
||||
Tells the delegate that the empty data set did appear.
|
||||
|
||||
@param scrollView A scrollView subclass informing the delegate.
|
||||
*/
|
||||
- (void)emptyDataSetDidAppear:(UIScrollView *)scrollView;
|
||||
|
||||
/**
|
||||
Tells the delegate that the empty data set will disappear.
|
||||
|
||||
@param scrollView A scrollView subclass informing the delegate.
|
||||
*/
|
||||
- (void)emptyDataSetWillDisappear:(UIScrollView *)scrollView;
|
||||
|
||||
/**
|
||||
Tells the delegate that the empty data set did disappear.
|
||||
|
||||
@param scrollView A scrollView subclass informing the delegate.
|
||||
*/
|
||||
- (void)emptyDataSetDidDisappear:(UIScrollView *)scrollView;
|
||||
|
||||
@end
|
||||
|
||||
#undef DZNEmptyDataSetDeprecated
|
||||
|
||||
1074
Pods/DZNEmptyDataSet/Source/UIScrollView+EmptyDataSet.m
generated
Normal file
1074
Pods/DZNEmptyDataSet/Source/UIScrollView+EmptyDataSet.m
generated
Normal file
File diff suppressed because it is too large
Load Diff
52
Pods/Local Podspecs/lottie-ios.podspec.json
generated
Normal file
52
Pods/Local Podspecs/lottie-ios.podspec.json
generated
Normal file
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"name": "lottie-ios",
|
||||
"version": "2.5.3",
|
||||
"summary": "Used to natively render vector animations exported from After Effects.",
|
||||
"description": "Lottie is a mobile library for Android and iOS that parses Adobe After Effects animations exported as json with bodymovin and renders the vector animations natively on mobile and through React Native!\n\nFor the first time, designers can create and ship beautiful animations without an engineer painstakingly recreating it be hand. Since the animation is backed by JSON they are extremely small in size but can be large in complexity! Animations can be played, resized, looped, sped up, slowed down, and even interactively scrubbed.",
|
||||
"homepage": "https://github.com/airbnb/lottie-ios",
|
||||
"license": {
|
||||
"type": "Apache",
|
||||
"file": "LICENSE"
|
||||
},
|
||||
"authors": {
|
||||
"Brandon Withrow": "buba447@gmail.com"
|
||||
},
|
||||
"source": {
|
||||
"git": "https://github.com/airbnb/lottie-ios.git",
|
||||
"tag": "2.5.3"
|
||||
},
|
||||
"platforms": {
|
||||
"ios": "8.0",
|
||||
"osx": "10.9",
|
||||
"tvos": "9.0"
|
||||
},
|
||||
"exclude_files": "lottie-ios/Classes/include/**/*",
|
||||
"source_files": "lottie-ios/Classes/**/*",
|
||||
"osx": {
|
||||
"exclude_files": [
|
||||
"lottie-ios/Classes/PublicHeaders/LOTAnimationTransitionController.h",
|
||||
"lottie-ios/Classes/Private/LOTAnimationTransitionController.m",
|
||||
"lottie-ios/Classes/PublicHeaders/LOTCacheProvider.h",
|
||||
"lottie-ios/Classes/Private/LOTCacheProvider.m",
|
||||
"lottie-ios/Classes/PublicHeaders/LOTAnimatedSwitch.h",
|
||||
"lottie-ios/Classes/Private/LOTAnimatedSwitch.m",
|
||||
"lottie-ios/Classes/PublicHeaders/LOTAnimatedControl.h",
|
||||
"lottie-ios/Classes/Private/LOTAnimatedControl.m"
|
||||
],
|
||||
"frameworks": [
|
||||
"AppKit",
|
||||
"CoreVideo"
|
||||
]
|
||||
},
|
||||
"resource_bundles": {
|
||||
"Lottie": [
|
||||
"Lottie/PrivacyInfo.xcprivacy"
|
||||
]
|
||||
},
|
||||
"public_header_files": "lottie-ios/Classes/PublicHeaders/*.h",
|
||||
"ios": {
|
||||
"frameworks": "UIKit"
|
||||
},
|
||||
"module_name": "Lottie",
|
||||
"header_dir": "Lottie"
|
||||
}
|
||||
21
Pods/LookinServer/LICENSE
generated
Normal file
21
Pods/LookinServer/LICENSE
generated
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) [2023] [LI KAI]
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
73
Pods/LookinServer/README.md
generated
Normal file
73
Pods/LookinServer/README.md
generated
Normal file
@@ -0,0 +1,73 @@
|
||||

|
||||
|
||||
# Introduction
|
||||
You can inspect and modify views in iOS app via Lookin, just like UI Inspector in Xcode, or another app called Reveal.
|
||||
|
||||
Official Website:https://lookin.work/
|
||||
|
||||
# Integration Guide
|
||||
To use Lookin macOS app, you need to integrate LookinServer (iOS Framework of Lookin) into your iOS project.
|
||||
|
||||
> **Warning**
|
||||
> 1. Never integrate LookinServer in Release building configuration.
|
||||
> 2. Do not use versions earlier than 1.0.6, as it contains a critical bug that could lead to online incidents in your project: https://qxh1ndiez2w.feishu.cn/wiki/Z9SpwT7zWiqvYvkBe7Lc6Disnab
|
||||
|
||||
## via CocoaPods:
|
||||
### Swift Project
|
||||
`pod 'LookinServer', :subspecs => ['Swift'], :configurations => ['Debug']`
|
||||
### Objective-C Project
|
||||
`pod 'LookinServer', :configurations => ['Debug']`
|
||||
## via Swift Package Manager:
|
||||
`https://github.com/QMUI/LookinServer/`
|
||||
|
||||
# Repository
|
||||
LookinServer: https://github.com/QMUI/LookinServer
|
||||
|
||||
macOS app: https://github.com/hughkli/Lookin/
|
||||
|
||||
# Tips
|
||||
- How to display custom information in Lookin: https://bytedance.larkoffice.com/docx/TRridRXeUoErMTxs94bcnGchnlb
|
||||
- How to display more member variables in Lookin: https://bytedance.larkoffice.com/docx/CKRndHqdeoub11xSqUZcMlFhnWe
|
||||
- How to turn on Swift optimization for Lookin: https://bytedance.larkoffice.com/docx/GFRLdzpeKoakeyxvwgCcZ5XdnTb
|
||||
- Documentation Collection: https://bytedance.larkoffice.com/docx/Yvv1d57XQoe5l0xZ0ZRc0ILfnWb
|
||||
|
||||
# Acknowledgements
|
||||
https://qxh1ndiez2w.feishu.cn/docx/YIFjdE4gIolp3hxn1tGckiBxnWf
|
||||
|
||||
---
|
||||
# 简介
|
||||
Lookin 可以查看与修改 iOS App 里的 UI 对象,类似于 Xcode 自带的 UI Inspector 工具,或另一款叫做 Reveal 的软件。
|
||||
|
||||
官网:https://lookin.work/
|
||||
|
||||
# 安装 LookinServer Framework
|
||||
如果这是你的 iOS 项目第一次使用 Lookin,则需要先把 LookinServer 这款 iOS Framework 集成到你的 iOS 项目中。
|
||||
|
||||
> **Warning**
|
||||
>
|
||||
> 1. 不要在 AppStore 模式下集成 LookinServer。
|
||||
> 2. 不要使用早于 1.0.6 的版本,因为它包含一个严重 Bug,可能导致线上事故: https://qxh1ndiez2w.feishu.cn/wiki/Z9SpwT7zWiqvYvkBe7Lc6Disnab
|
||||
## 通过 CocoaPods:
|
||||
|
||||
### Swift 项目
|
||||
`pod 'LookinServer', :subspecs => ['Swift'], :configurations => ['Debug']`
|
||||
### Objective-C 项目
|
||||
`pod 'LookinServer', :configurations => ['Debug']`
|
||||
|
||||
## 通过 Swift Package Manager:
|
||||
`https://github.com/QMUI/LookinServer/`
|
||||
|
||||
# 源代码仓库
|
||||
|
||||
iOS 端 LookinServer:https://github.com/QMUI/LookinServer
|
||||
|
||||
macOS 端软件:https://github.com/hughkli/Lookin/
|
||||
|
||||
# 技巧
|
||||
- 如何在 Lookin 中展示自定义信息: https://bytedance.larkoffice.com/docx/TRridRXeUoErMTxs94bcnGchnlb
|
||||
- 如何在 Lookin 中展示更多成员变量: https://bytedance.larkoffice.com/docx/CKRndHqdeoub11xSqUZcMlFhnWe
|
||||
- 如何为 Lookin 开启 Swift 优化: https://bytedance.larkoffice.com/docx/GFRLdzpeKoakeyxvwgCcZ5XdnTb
|
||||
- 文档汇总:https://bytedance.larkoffice.com/docx/Yvv1d57XQoe5l0xZ0ZRc0ILfnWb
|
||||
|
||||
# 鸣谢
|
||||
https://qxh1ndiez2w.feishu.cn/docx/YIFjdE4gIolp3hxn1tGckiBxnWf
|
||||
40
Pods/LookinServer/Src/Base/LookinIvarTrace.h
generated
Normal file
40
Pods/LookinServer/Src/Base/LookinIvarTrace.h
generated
Normal file
@@ -0,0 +1,40 @@
|
||||
#ifdef SHOULD_COMPILE_LOOKIN_SERVER
|
||||
|
||||
//
|
||||
// LookinIvarTrace.h
|
||||
// Lookin
|
||||
//
|
||||
// Created by Li Kai on 2019/4/30.
|
||||
// https://lookin.work
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
extern NSString *const LookinIvarTraceRelationValue_Self;
|
||||
|
||||
/// 如果 hostClassName 和 ivarName 均 equal,则认为两个 LookinIvarTrace 对象彼此 equal
|
||||
/// 比如 A 是 B 的 superview,且 A 的 "_stageView" 指向 B,则 B 会有一个 LookinIvarTrace:hostType 为 “superview”,hostClassName 为 A 的 class,ivarName 为 “_stageView”
|
||||
@interface LookinIvarTrace : NSObject <NSSecureCoding, NSCopying>
|
||||
|
||||
/// 该值可能是 "superview"、"superlayer"、“self” 或 nil
|
||||
@property(nonatomic, copy) NSString *relation;
|
||||
|
||||
@property(nonatomic, copy) NSString *hostClassName;
|
||||
|
||||
@property(nonatomic, copy) NSString *ivarName;
|
||||
|
||||
#pragma mark - No Coding
|
||||
|
||||
#if TARGET_OS_IPHONE
|
||||
@property(nonatomic, weak) id hostObject;
|
||||
#endif
|
||||
|
||||
@end
|
||||
|
||||
@interface NSObject (LookinServerTrace)
|
||||
|
||||
@property(nonatomic, copy) NSArray<LookinIvarTrace *> *lks_ivarTraces;
|
||||
|
||||
@end
|
||||
|
||||
#endif /* SHOULD_COMPILE_LOOKIN_SERVER */
|
||||
70
Pods/LookinServer/Src/Base/LookinIvarTrace.m
generated
Normal file
70
Pods/LookinServer/Src/Base/LookinIvarTrace.m
generated
Normal file
@@ -0,0 +1,70 @@
|
||||
#ifdef SHOULD_COMPILE_LOOKIN_SERVER
|
||||
|
||||
//
|
||||
// LookinIvarTrace.m
|
||||
// Lookin
|
||||
//
|
||||
// Created by Li Kai on 2019/4/30.
|
||||
// https://lookin.work
|
||||
//
|
||||
|
||||
#import "LookinIvarTrace.h"
|
||||
|
||||
NSString *const LookinIvarTraceRelationValue_Self = @"self";
|
||||
|
||||
@implementation LookinIvarTrace
|
||||
|
||||
#pragma mark - Equal
|
||||
|
||||
- (NSUInteger)hash {
|
||||
return self.hostClassName.hash ^ self.ivarName.hash;
|
||||
}
|
||||
|
||||
- (BOOL)isEqual:(id)object {
|
||||
if (self == object) {
|
||||
return YES;
|
||||
}
|
||||
if (![object isKindOfClass:[LookinIvarTrace class]]) {
|
||||
return NO;
|
||||
}
|
||||
LookinIvarTrace *comparedObj = object;
|
||||
if ([self.hostClassName isEqualToString:comparedObj.hostClassName] && [self.ivarName isEqualToString:comparedObj.ivarName]) {
|
||||
return YES;
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
#pragma mark - <NSCopying>
|
||||
|
||||
- (id)copyWithZone:(NSZone *)zone {
|
||||
LookinIvarTrace *newTrace = [[LookinIvarTrace allocWithZone:zone] init];
|
||||
newTrace.relation = self.relation;
|
||||
newTrace.hostClassName = self.hostClassName;
|
||||
newTrace.ivarName = self.ivarName;
|
||||
return newTrace;
|
||||
}
|
||||
|
||||
#pragma mark - <NSCoding>
|
||||
|
||||
- (void)encodeWithCoder:(NSCoder *)aCoder {
|
||||
[aCoder encodeObject:self.relation forKey:@"relation"];
|
||||
[aCoder encodeObject:self.hostClassName forKey:@"hostClassName"];
|
||||
[aCoder encodeObject:self.ivarName forKey:@"ivarName"];
|
||||
}
|
||||
|
||||
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
|
||||
if (self = [super init]) {
|
||||
self.relation = [aDecoder decodeObjectForKey:@"relation"];
|
||||
self.hostClassName = [aDecoder decodeObjectForKey:@"hostClassName"];
|
||||
self.ivarName = [aDecoder decodeObjectForKey:@"ivarName"];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
+ (BOOL)supportsSecureCoding {
|
||||
return YES;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#endif /* SHOULD_COMPILE_LOOKIN_SERVER */
|
||||
41
Pods/LookinServer/Src/Main/Server/Category/CALayer+LookinServer.h
generated
Normal file
41
Pods/LookinServer/Src/Main/Server/Category/CALayer+LookinServer.h
generated
Normal file
@@ -0,0 +1,41 @@
|
||||
#ifdef SHOULD_COMPILE_LOOKIN_SERVER
|
||||
|
||||
//
|
||||
// UIView+LookinMobile.h
|
||||
// WeRead
|
||||
//
|
||||
// Created by Li Kai on 2018/11/30.
|
||||
// Copyright © 2018 tencent. All rights reserved.
|
||||
//
|
||||
|
||||
#import "LookinDefines.h"
|
||||
#import "TargetConditionals.h"
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
@interface CALayer (LookinServer)
|
||||
|
||||
/// 如果 myView.layer == myLayer,则 myLayer.lks_hostView 会返回 myView
|
||||
@property(nonatomic, readonly, weak) UIView *lks_hostView;
|
||||
|
||||
- (UIWindow *)lks_window;
|
||||
|
||||
- (CGRect)lks_frameInWindow:(UIWindow *)window;
|
||||
|
||||
- (UIImage *)lks_groupScreenshotWithLowQuality:(BOOL)lowQuality;
|
||||
/// 当没有 sublayers 时,该方法返回 nil
|
||||
- (UIImage *)lks_soloScreenshotWithLowQuality:(BOOL)lowQuality;
|
||||
|
||||
/// 获取和该对象有关的对象的 Class 层级树
|
||||
- (NSArray<NSArray<NSString *> *> *)lks_relatedClassChainList;
|
||||
|
||||
- (NSArray<NSString *> *)lks_selfRelation;
|
||||
|
||||
@property(nonatomic, strong) UIColor *lks_backgroundColor;
|
||||
@property(nonatomic, strong) UIColor *lks_borderColor;
|
||||
@property(nonatomic, strong) UIColor *lks_shadowColor;
|
||||
@property(nonatomic, assign) CGFloat lks_shadowOffsetWidth;
|
||||
@property(nonatomic, assign) CGFloat lks_shadowOffsetHeight;
|
||||
|
||||
@end
|
||||
|
||||
#endif /* SHOULD_COMPILE_LOOKIN_SERVER */
|
||||
233
Pods/LookinServer/Src/Main/Server/Category/CALayer+LookinServer.m
generated
Normal file
233
Pods/LookinServer/Src/Main/Server/Category/CALayer+LookinServer.m
generated
Normal file
@@ -0,0 +1,233 @@
|
||||
#ifdef SHOULD_COMPILE_LOOKIN_SERVER
|
||||
|
||||
//
|
||||
// UIView+LookinMobile.m
|
||||
// WeRead
|
||||
//
|
||||
// Created by Li Kai on 2018/11/30.
|
||||
// Copyright © 2018 tencent. All rights reserved.
|
||||
//
|
||||
|
||||
#import "CALayer+LookinServer.h"
|
||||
#import "LKS_HierarchyDisplayItemsMaker.h"
|
||||
#import "LookinDisplayItem.h"
|
||||
#import <objc/runtime.h>
|
||||
#import "LKS_ConnectionManager.h"
|
||||
#import "LookinIvarTrace.h"
|
||||
#import "LookinServerDefines.h"
|
||||
#import "UIColor+LookinServer.h"
|
||||
#import "LKS_MultiplatformAdapter.h"
|
||||
|
||||
@implementation CALayer (LookinServer)
|
||||
|
||||
- (UIWindow *)lks_window {
|
||||
CALayer *layer = self;
|
||||
while (layer) {
|
||||
UIView *hostView = layer.lks_hostView;
|
||||
if (hostView.window) {
|
||||
return hostView.window;
|
||||
} else if ([hostView isKindOfClass:[UIWindow class]]) {
|
||||
return (UIWindow *)hostView;
|
||||
}
|
||||
layer = layer.superlayer;
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
- (CGRect)lks_frameInWindow:(UIWindow *)window {
|
||||
UIWindow *selfWindow = [self lks_window];
|
||||
if (!selfWindow) {
|
||||
return CGRectZero;
|
||||
}
|
||||
|
||||
CGRect rectInSelfWindow = [selfWindow.layer convertRect:self.frame fromLayer:self.superlayer];
|
||||
CGRect rectInWindow = [window convertRect:rectInSelfWindow fromWindow:selfWindow];
|
||||
return rectInWindow;
|
||||
}
|
||||
|
||||
#pragma mark - Host View
|
||||
|
||||
- (UIView *)lks_hostView {
|
||||
if (self.delegate && [self.delegate isKindOfClass:UIView.class]) {
|
||||
UIView *view = (UIView *)self.delegate;
|
||||
if (view.layer == self) {
|
||||
return view;
|
||||
}
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
#pragma mark - Screenshot
|
||||
|
||||
- (UIImage *)lks_groupScreenshotWithLowQuality:(BOOL)lowQuality {
|
||||
|
||||
CGFloat screenScale = [LKS_MultiplatformAdapter mainScreenScale];
|
||||
CGFloat pixelWidth = self.frame.size.width * screenScale;
|
||||
CGFloat pixelHeight = self.frame.size.height * screenScale;
|
||||
if (pixelWidth <= 0 || pixelHeight <= 0) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
CGFloat renderScale = lowQuality ? 1 : 0;
|
||||
CGFloat maxLength = MAX(pixelWidth, pixelHeight);
|
||||
if (maxLength > LookinNodeImageMaxLengthInPx) {
|
||||
// 确保最终绘制出的图片长和宽都不能超过 LookinNodeImageMaxLengthInPx
|
||||
// 如果算出的 renderScale 大于 1 则取 1,因为似乎用 1 渲染的速度要比一个别的奇怪的带小数点的数字要更快
|
||||
renderScale = MIN(screenScale * LookinNodeImageMaxLengthInPx / maxLength, 1);
|
||||
}
|
||||
|
||||
CGSize contextSize = self.frame.size;
|
||||
if (contextSize.width <= 0 || contextSize.height <= 0 || contextSize.width > 20000 || contextSize.height > 20000) {
|
||||
NSLog(@"LookinServer - Failed to capture screenshot. Invalid context size: %@ x %@", @(contextSize.width), @(contextSize.height));
|
||||
return nil;
|
||||
}
|
||||
UIGraphicsBeginImageContextWithOptions(contextSize, NO, renderScale);
|
||||
CGContextRef context = UIGraphicsGetCurrentContext();
|
||||
if (self.lks_hostView && !self.lks_hostView.lks_isChildrenViewOfTabBar) {
|
||||
[self.lks_hostView drawViewHierarchyInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height) afterScreenUpdates:YES];
|
||||
} else {
|
||||
[self renderInContext:context];
|
||||
}
|
||||
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
|
||||
UIGraphicsEndImageContext();
|
||||
return image;
|
||||
}
|
||||
|
||||
- (UIImage *)lks_soloScreenshotWithLowQuality:(BOOL)lowQuality {
|
||||
if (!self.sublayers.count) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
CGFloat screenScale = [LKS_MultiplatformAdapter mainScreenScale];
|
||||
CGFloat pixelWidth = self.frame.size.width * screenScale;
|
||||
CGFloat pixelHeight = self.frame.size.height * screenScale;
|
||||
if (pixelWidth <= 0 || pixelHeight <= 0) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
CGFloat renderScale = lowQuality ? 1 : 0;
|
||||
CGFloat maxLength = MAX(pixelWidth, pixelHeight);
|
||||
if (maxLength > LookinNodeImageMaxLengthInPx) {
|
||||
// 确保最终绘制出的图片长和宽都不能超过 LookinNodeImageMaxLengthInPx
|
||||
// 如果算出的 renderScale 大于 1 则取 1,因为似乎用 1 渲染的速度要比一个别的奇怪的带小数点的数字要更快
|
||||
renderScale = MIN(screenScale * LookinNodeImageMaxLengthInPx / maxLength, 1);
|
||||
}
|
||||
|
||||
if (self.sublayers.count) {
|
||||
NSArray<CALayer *> *sublayers = [self.sublayers copy];
|
||||
NSMutableArray<CALayer *> *visibleSublayers = [NSMutableArray arrayWithCapacity:sublayers.count];
|
||||
[sublayers enumerateObjectsUsingBlock:^(__kindof CALayer * _Nonnull sublayer, NSUInteger idx, BOOL * _Nonnull stop) {
|
||||
if (!sublayer.hidden) {
|
||||
sublayer.hidden = YES;
|
||||
[visibleSublayers addObject:sublayer];
|
||||
}
|
||||
}];
|
||||
|
||||
CGSize contextSize = self.frame.size;
|
||||
if (contextSize.width <= 0 || contextSize.height <= 0 || contextSize.width > 20000 || contextSize.height > 20000) {
|
||||
NSLog(@"LookinServer - Failed to capture screenshot. Invalid context size: %@ x %@", @(contextSize.width), @(contextSize.height));
|
||||
return nil;
|
||||
}
|
||||
|
||||
UIGraphicsBeginImageContextWithOptions(contextSize, NO, renderScale);
|
||||
CGContextRef context = UIGraphicsGetCurrentContext();
|
||||
if (self.lks_hostView && !self.lks_hostView.lks_isChildrenViewOfTabBar) {
|
||||
[self.lks_hostView drawViewHierarchyInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height) afterScreenUpdates:YES];
|
||||
} else {
|
||||
[self renderInContext:context];
|
||||
}
|
||||
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
|
||||
UIGraphicsEndImageContext();
|
||||
|
||||
[visibleSublayers enumerateObjectsUsingBlock:^(CALayer * _Nonnull sublayer, NSUInteger idx, BOOL * _Nonnull stop) {
|
||||
sublayer.hidden = NO;
|
||||
}];
|
||||
|
||||
return image;
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
- (NSArray<NSArray<NSString *> *> *)lks_relatedClassChainList {
|
||||
NSMutableArray *array = [NSMutableArray arrayWithCapacity:2];
|
||||
if (self.lks_hostView) {
|
||||
[array addObject:[CALayer lks_getClassListOfObject:self.lks_hostView endingClass:@"UIView"]];
|
||||
UIViewController* vc = [self.lks_hostView lks_findHostViewController];
|
||||
if (vc) {
|
||||
[array addObject:[CALayer lks_getClassListOfObject:vc endingClass:@"UIViewController"]];
|
||||
}
|
||||
} else {
|
||||
[array addObject:[CALayer lks_getClassListOfObject:self endingClass:@"CALayer"]];
|
||||
}
|
||||
return array.copy;
|
||||
}
|
||||
|
||||
+ (NSArray<NSString *> *)lks_getClassListOfObject:(id)object endingClass:(NSString *)endingClass {
|
||||
NSArray<NSString *> *completedList = [object lks_classChainList];
|
||||
NSUInteger endingIdx = [completedList indexOfObject:endingClass];
|
||||
if (endingIdx != NSNotFound) {
|
||||
completedList = [completedList subarrayWithRange:NSMakeRange(0, endingIdx + 1)];
|
||||
}
|
||||
return completedList;
|
||||
}
|
||||
|
||||
- (NSArray<NSString *> *)lks_selfRelation {
|
||||
NSMutableArray *array = [NSMutableArray array];
|
||||
NSMutableArray<LookinIvarTrace *> *ivarTraces = [NSMutableArray array];
|
||||
if (self.lks_hostView) {
|
||||
UIViewController* vc = [self.lks_hostView lks_findHostViewController];
|
||||
if (vc) {
|
||||
[array addObject:[NSString stringWithFormat:@"(%@ *).view", NSStringFromClass(vc.class)]];
|
||||
|
||||
[ivarTraces addObjectsFromArray:vc.lks_ivarTraces];
|
||||
}
|
||||
[ivarTraces addObjectsFromArray:self.lks_hostView.lks_ivarTraces];
|
||||
} else {
|
||||
[ivarTraces addObjectsFromArray:self.lks_ivarTraces];
|
||||
}
|
||||
if (ivarTraces.count) {
|
||||
[array addObjectsFromArray:[ivarTraces lookin_map:^id(NSUInteger idx, LookinIvarTrace *value) {
|
||||
return [NSString stringWithFormat:@"(%@ *) -> %@", value.hostClassName, value.ivarName];
|
||||
}]];
|
||||
}
|
||||
return array.count ? array.copy : nil;
|
||||
}
|
||||
|
||||
- (UIColor *)lks_backgroundColor {
|
||||
return [UIColor lks_colorWithCGColor:self.backgroundColor];
|
||||
}
|
||||
- (void)setLks_backgroundColor:(UIColor *)lks_backgroundColor {
|
||||
self.backgroundColor = lks_backgroundColor.CGColor;
|
||||
}
|
||||
|
||||
- (UIColor *)lks_borderColor {
|
||||
return [UIColor lks_colorWithCGColor:self.borderColor];
|
||||
}
|
||||
- (void)setLks_borderColor:(UIColor *)lks_borderColor {
|
||||
self.borderColor = lks_borderColor.CGColor;
|
||||
}
|
||||
|
||||
- (UIColor *)lks_shadowColor {
|
||||
return [UIColor lks_colorWithCGColor:self.shadowColor];
|
||||
}
|
||||
- (void)setLks_shadowColor:(UIColor *)lks_shadowColor {
|
||||
self.shadowColor = lks_shadowColor.CGColor;
|
||||
}
|
||||
|
||||
- (CGFloat)lks_shadowOffsetWidth {
|
||||
return self.shadowOffset.width;
|
||||
}
|
||||
- (void)setLks_shadowOffsetWidth:(CGFloat)lks_shadowOffsetWidth {
|
||||
self.shadowOffset = CGSizeMake(lks_shadowOffsetWidth, self.shadowOffset.height);
|
||||
}
|
||||
|
||||
- (CGFloat)lks_shadowOffsetHeight {
|
||||
return self.shadowOffset.height;
|
||||
}
|
||||
- (void)setLks_shadowOffsetHeight:(CGFloat)lks_shadowOffsetHeight {
|
||||
self.shadowOffset = CGSizeMake(self.shadowOffset.width, lks_shadowOffsetHeight);
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#endif /* SHOULD_COMPILE_LOOKIN_SERVER */
|
||||
41
Pods/LookinServer/Src/Main/Server/Category/NSObject+LookinServer.h
generated
Normal file
41
Pods/LookinServer/Src/Main/Server/Category/NSObject+LookinServer.h
generated
Normal file
@@ -0,0 +1,41 @@
|
||||
#ifdef SHOULD_COMPILE_LOOKIN_SERVER
|
||||
|
||||
//
|
||||
// NSObject+LookinServer.h
|
||||
// LookinServer
|
||||
//
|
||||
// Created by Li Kai on 2019/4/21.
|
||||
// https://lookin.work
|
||||
//
|
||||
|
||||
#import "LookinDefines.h"
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
@class LookinIvarTrace;
|
||||
|
||||
@interface NSObject (LookinServer)
|
||||
|
||||
#pragma mark - oid
|
||||
|
||||
/// 如果 oid 不存在则会创建新的 oid
|
||||
- (unsigned long)lks_registerOid;
|
||||
|
||||
/// 0 表示不存在
|
||||
@property(nonatomic, assign) unsigned long lks_oid;
|
||||
|
||||
+ (NSObject *)lks_objectWithOid:(unsigned long)oid;
|
||||
|
||||
#pragma mark - trace
|
||||
|
||||
@property(nonatomic, copy) NSString *lks_specialTrace;
|
||||
|
||||
+ (void)lks_clearAllObjectsTraces;
|
||||
|
||||
/**
|
||||
获取当前对象的 Class 层级树,如 @[@"UIView", @"UIResponder", @"NSObject"]。未 demangle,有 Swift Module Name
|
||||
*/
|
||||
- (NSArray<NSString *> *)lks_classChainList;
|
||||
|
||||
@end
|
||||
|
||||
#endif /* SHOULD_COMPILE_LOOKIN_SERVER */
|
||||
99
Pods/LookinServer/Src/Main/Server/Category/NSObject+LookinServer.m
generated
Normal file
99
Pods/LookinServer/Src/Main/Server/Category/NSObject+LookinServer.m
generated
Normal file
@@ -0,0 +1,99 @@
|
||||
#ifdef SHOULD_COMPILE_LOOKIN_SERVER
|
||||
|
||||
//
|
||||
// NSObject+LookinServer.m
|
||||
// LookinServer
|
||||
//
|
||||
// Created by Li Kai on 2019/4/21.
|
||||
// https://lookin.work
|
||||
//
|
||||
|
||||
#import "NSObject+Lookin.h"
|
||||
#import "NSObject+LookinServer.h"
|
||||
#import "LookinServerDefines.h"
|
||||
#import "LKS_ObjectRegistry.h"
|
||||
#import <objc/runtime.h>
|
||||
|
||||
@implementation NSObject (LookinServer)
|
||||
|
||||
#pragma mark - oid
|
||||
|
||||
- (unsigned long)lks_registerOid {
|
||||
if (!self.lks_oid) {
|
||||
unsigned long oid = [[LKS_ObjectRegistry sharedInstance] addObject:self];
|
||||
self.lks_oid = oid;
|
||||
}
|
||||
return self.lks_oid;
|
||||
}
|
||||
|
||||
- (void)setLks_oid:(unsigned long)lks_oid {
|
||||
[self lookin_bindObject:@(lks_oid) forKey:@"lks_oid"];
|
||||
}
|
||||
|
||||
- (unsigned long)lks_oid {
|
||||
NSNumber *number = [self lookin_getBindObjectForKey:@"lks_oid"];
|
||||
return [number unsignedLongValue];
|
||||
}
|
||||
|
||||
+ (NSObject *)lks_objectWithOid:(unsigned long)oid {
|
||||
return [[LKS_ObjectRegistry sharedInstance] objectWithOid:oid];
|
||||
}
|
||||
|
||||
#pragma mark - trace
|
||||
|
||||
- (void)setLks_ivarTraces:(NSArray<LookinIvarTrace *> *)lks_ivarTraces {
|
||||
[self lookin_bindObject:lks_ivarTraces.copy forKey:@"lks_ivarTraces"];
|
||||
|
||||
if (lks_ivarTraces) {
|
||||
[[NSObject lks_allObjectsWithTraces] addPointer:(void *)self];
|
||||
}
|
||||
}
|
||||
|
||||
- (NSArray<LookinIvarTrace *> *)lks_ivarTraces {
|
||||
return [self lookin_getBindObjectForKey:@"lks_ivarTraces"];
|
||||
}
|
||||
|
||||
- (void)setLks_specialTrace:(NSString *)lks_specialTrace {
|
||||
[self lookin_bindObject:lks_specialTrace forKey:@"lks_specialTrace"];
|
||||
if (lks_specialTrace) {
|
||||
[[NSObject lks_allObjectsWithTraces] addPointer:(void *)self];
|
||||
}
|
||||
}
|
||||
- (NSString *)lks_specialTrace {
|
||||
return [self lookin_getBindObjectForKey:@"lks_specialTrace"];
|
||||
}
|
||||
|
||||
+ (void)lks_clearAllObjectsTraces {
|
||||
[[[NSObject lks_allObjectsWithTraces] allObjects] enumerateObjectsUsingBlock:^(NSObject * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
|
||||
obj.lks_ivarTraces = nil;
|
||||
obj.lks_specialTrace = nil;
|
||||
}];
|
||||
[NSObject lks_allObjectsWithTraces].count = 0;
|
||||
}
|
||||
|
||||
+ (NSPointerArray *)lks_allObjectsWithTraces {
|
||||
static dispatch_once_t onceToken;
|
||||
static NSPointerArray *lks_allObjectsWithTraces = nil;
|
||||
dispatch_once(&onceToken,^{
|
||||
lks_allObjectsWithTraces = [NSPointerArray weakObjectsPointerArray];
|
||||
});
|
||||
return lks_allObjectsWithTraces;
|
||||
}
|
||||
|
||||
- (NSArray<NSString *> *)lks_classChainList {
|
||||
NSMutableArray<NSString *> *classChainList = [NSMutableArray array];
|
||||
Class currentClass = self.class;
|
||||
|
||||
while (currentClass) {
|
||||
NSString *currentClassName = NSStringFromClass(currentClass);
|
||||
if (currentClassName) {
|
||||
[classChainList addObject:currentClassName];
|
||||
}
|
||||
currentClass = [currentClass superclass];
|
||||
}
|
||||
return classChainList.copy;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#endif /* SHOULD_COMPILE_LOOKIN_SERVER */
|
||||
21
Pods/LookinServer/Src/Main/Server/Category/UIBlurEffect+LookinServer.h
generated
Normal file
21
Pods/LookinServer/Src/Main/Server/Category/UIBlurEffect+LookinServer.h
generated
Normal file
@@ -0,0 +1,21 @@
|
||||
#ifdef SHOULD_COMPILE_LOOKIN_SERVER
|
||||
|
||||
//
|
||||
// UIBlurEffect+LookinServer.h
|
||||
// LookinServer
|
||||
//
|
||||
// Created by Li Kai on 2019/10/8.
|
||||
// https://lookin.work
|
||||
//
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
@interface UIBlurEffect (LookinServer)
|
||||
|
||||
/// 该 number 包装的对象是 UIBlurEffectStyle,之所以用 NSNumber 是因为想把 0 和 nil 区分开,毕竟这里是在 hook 系统,稳一点好。
|
||||
/// 该方法的实现需要 Hook,因此若定义了 LOOKIN_SERVER_DISABLE_HOOK 宏,则属性会返回 nil
|
||||
@property(nonatomic, strong) NSNumber *lks_effectStyleNumber;
|
||||
|
||||
@end
|
||||
|
||||
#endif /* SHOULD_COMPILE_LOOKIN_SERVER */
|
||||
57
Pods/LookinServer/Src/Main/Server/Category/UIBlurEffect+LookinServer.m
generated
Normal file
57
Pods/LookinServer/Src/Main/Server/Category/UIBlurEffect+LookinServer.m
generated
Normal file
@@ -0,0 +1,57 @@
|
||||
#ifdef SHOULD_COMPILE_LOOKIN_SERVER
|
||||
|
||||
//
|
||||
// UIBlurEffect+LookinServer.m
|
||||
// LookinServer
|
||||
//
|
||||
// Created by Li Kai on 2019/10/8.
|
||||
// https://lookin.work
|
||||
//
|
||||
|
||||
#import "UIBlurEffect+LookinServer.h"
|
||||
#import "NSObject+Lookin.h"
|
||||
#import <objc/runtime.h>
|
||||
|
||||
@implementation UIBlurEffect (LookinServer)
|
||||
|
||||
#ifdef LOOKIN_SERVER_DISABLE_HOOK
|
||||
|
||||
- (void)setLks_effectStyleNumber:(NSNumber *)lks_effectStyleNumber {
|
||||
}
|
||||
|
||||
- (NSNumber *)lks_effectStyleNumber {
|
||||
return nil;
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
+ (void)load {
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
Method oriMethod = class_getClassMethod([self class], @selector(effectWithStyle:));
|
||||
Method newMethod = class_getClassMethod([self class], @selector(lks_effectWithStyle:));
|
||||
method_exchangeImplementations(oriMethod, newMethod);
|
||||
});
|
||||
}
|
||||
|
||||
+ (UIBlurEffect *)lks_effectWithStyle:(UIBlurEffectStyle)style {
|
||||
id effect = [self lks_effectWithStyle:style];
|
||||
if ([effect respondsToSelector:@selector(setLks_effectStyleNumber:)]) {
|
||||
[effect setLks_effectStyleNumber:@(style)];
|
||||
}
|
||||
return effect;
|
||||
}
|
||||
|
||||
- (void)setLks_effectStyleNumber:(NSNumber *)lks_effectStyleNumber {
|
||||
[self lookin_bindObject:lks_effectStyleNumber forKey:@"lks_effectStyleNumber"];
|
||||
}
|
||||
|
||||
- (NSNumber *)lks_effectStyleNumber {
|
||||
return [self lookin_getBindObjectForKey:@"lks_effectStyleNumber"];
|
||||
}
|
||||
|
||||
#endif /* LOOKIN_SERVER_DISABLE_HOOK */
|
||||
|
||||
@end
|
||||
|
||||
#endif /* SHOULD_COMPILE_LOOKIN_SERVER */
|
||||
26
Pods/LookinServer/Src/Main/Server/Category/UIColor+LookinServer.h
generated
Normal file
26
Pods/LookinServer/Src/Main/Server/Category/UIColor+LookinServer.h
generated
Normal file
@@ -0,0 +1,26 @@
|
||||
#ifdef SHOULD_COMPILE_LOOKIN_SERVER
|
||||
|
||||
//
|
||||
// UIColor+LookinServer.h
|
||||
// LookinServer
|
||||
//
|
||||
// Created by Li Kai on 2019/6/5.
|
||||
// https://lookin.work
|
||||
//
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
@interface UIColor (LookinServer)
|
||||
|
||||
- (NSArray<NSNumber *> *)lks_rgbaComponents;
|
||||
+ (instancetype)lks_colorFromRGBAComponents:(NSArray<NSNumber *> *)components;
|
||||
|
||||
- (NSString *)lks_rgbaString;
|
||||
- (NSString *)lks_hexString;
|
||||
|
||||
/// will check if the argument is a real CGColor
|
||||
+ (UIColor *)lks_colorWithCGColor:(CGColorRef)cgColor;
|
||||
|
||||
@end
|
||||
|
||||
#endif /* SHOULD_COMPILE_LOOKIN_SERVER */
|
||||
183
Pods/LookinServer/Src/Main/Server/Category/UIColor+LookinServer.m
generated
Normal file
183
Pods/LookinServer/Src/Main/Server/Category/UIColor+LookinServer.m
generated
Normal file
@@ -0,0 +1,183 @@
|
||||
#ifdef SHOULD_COMPILE_LOOKIN_SERVER
|
||||
|
||||
//
|
||||
// UIColor+LookinServer.m
|
||||
// LookinServer
|
||||
//
|
||||
// Created by Li Kai on 2019/6/5.
|
||||
// https://lookin.work
|
||||
//
|
||||
|
||||
#import "UIColor+LookinServer.h"
|
||||
|
||||
@implementation UIColor (LookinServer)
|
||||
|
||||
- (NSArray<NSNumber *> *)lks_rgbaComponents {
|
||||
CGFloat r, g, b, a;
|
||||
CGColorRef cgColor = [self CGColor];
|
||||
const CGFloat *components = CGColorGetComponents(cgColor);
|
||||
if (CGColorGetNumberOfComponents(cgColor) == 4) {
|
||||
r = components[0];
|
||||
g = components[1];
|
||||
b = components[2];
|
||||
a = components[3];
|
||||
} else if (CGColorGetNumberOfComponents(cgColor) == 2) {
|
||||
r = components[0];
|
||||
g = components[0];
|
||||
b = components[0];
|
||||
a = components[1];
|
||||
} else if (CGColorGetNumberOfComponents(cgColor) == 1) {
|
||||
r = components[0];
|
||||
g = components[0];
|
||||
b = components[0];
|
||||
a = components[0];
|
||||
} else {
|
||||
r = 0;
|
||||
g = 0;
|
||||
b = 0;
|
||||
a = 0;
|
||||
NSAssert(NO, @"");
|
||||
}
|
||||
NSArray<NSNumber *> *rgba = @[@(r), @(g), @(b), @(a)];
|
||||
return rgba;
|
||||
}
|
||||
|
||||
+ (instancetype)lks_colorFromRGBAComponents:(NSArray<NSNumber *> *)components {
|
||||
if (!components) {
|
||||
return nil;
|
||||
}
|
||||
if (components.count != 4) {
|
||||
NSAssert(NO, @"");
|
||||
return nil;
|
||||
}
|
||||
UIColor *color = [UIColor colorWithRed:components[0].doubleValue green:components[1].doubleValue blue:components[2].doubleValue alpha:components[3].doubleValue];
|
||||
return color;
|
||||
}
|
||||
|
||||
- (NSString *)lks_rgbaString {
|
||||
CGFloat r, g, b, a;
|
||||
CGColorRef cgColor = [self CGColor];
|
||||
const CGFloat *components = CGColorGetComponents(cgColor);
|
||||
if (CGColorGetNumberOfComponents(cgColor) == 4) {
|
||||
r = components[0];
|
||||
g = components[1];
|
||||
b = components[2];
|
||||
a = components[3];
|
||||
} else if (CGColorGetNumberOfComponents(cgColor) == 2) {
|
||||
r = components[0];
|
||||
g = components[0];
|
||||
b = components[0];
|
||||
a = components[1];
|
||||
} else {
|
||||
r = 0;
|
||||
g = 0;
|
||||
b = 0;
|
||||
a = 0;
|
||||
NSAssert(NO, @"");
|
||||
}
|
||||
|
||||
if (a >= 1) {
|
||||
return [NSString stringWithFormat:@"(%.0f, %.0f, %.0f)", r * 255, g * 255, b * 255];
|
||||
} else {
|
||||
return [NSString stringWithFormat:@"(%.0f, %.0f, %.0f, %.2f)", r * 255, g * 255, b * 255, a];
|
||||
}
|
||||
}
|
||||
|
||||
- (NSString *)lks_hexString {
|
||||
CGFloat r, g, b, a;
|
||||
CGColorRef cgColor = [self CGColor];
|
||||
const CGFloat *components = CGColorGetComponents(cgColor);
|
||||
if (CGColorGetNumberOfComponents(cgColor) == 4) {
|
||||
r = components[0];
|
||||
g = components[1];
|
||||
b = components[2];
|
||||
a = components[3];
|
||||
} else if (CGColorGetNumberOfComponents(cgColor) == 2) {
|
||||
r = components[0];
|
||||
g = components[0];
|
||||
b = components[0];
|
||||
a = components[1];
|
||||
} else {
|
||||
r = 0;
|
||||
g = 0;
|
||||
b = 0;
|
||||
a = 0;
|
||||
NSAssert(NO, @"");
|
||||
}
|
||||
|
||||
NSInteger red = r * 255;
|
||||
NSInteger green = g * 255;
|
||||
NSInteger blue = b * 255;
|
||||
NSInteger alpha = a * 255;
|
||||
|
||||
return [[NSString stringWithFormat:@"#%@%@%@%@",
|
||||
[UIColor _alignColorHexStringLength:[UIColor _hexStringWithInteger:alpha]],
|
||||
[UIColor _alignColorHexStringLength:[UIColor _hexStringWithInteger:red]],
|
||||
[UIColor _alignColorHexStringLength:[UIColor _hexStringWithInteger:green]],
|
||||
[UIColor _alignColorHexStringLength:[UIColor _hexStringWithInteger:blue]]] lowercaseString];
|
||||
}
|
||||
|
||||
// 对于色值只有单位数的,在前面补一个0,例如“F”会补齐为“0F”
|
||||
+ (NSString *)_alignColorHexStringLength:(NSString *)hexString {
|
||||
return hexString.length < 2 ? [@"0" stringByAppendingString:hexString] : hexString;
|
||||
}
|
||||
|
||||
+ (NSString *)_hexStringWithInteger:(NSInteger)integer {
|
||||
NSString *hexString = @"";
|
||||
NSInteger remainder = 0;
|
||||
for (NSInteger i = 0; i < 9; i++) {
|
||||
remainder = integer % 16;
|
||||
integer = integer / 16;
|
||||
NSString *letter = [self _hexLetterStringWithInteger:remainder];
|
||||
hexString = [letter stringByAppendingString:hexString];
|
||||
if (integer == 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
}
|
||||
return hexString;
|
||||
}
|
||||
|
||||
+ (NSString *)_hexLetterStringWithInteger:(NSInteger)integer {
|
||||
NSAssert(integer < 16, @"要转换的数必须是16进制里的个位数,也即小于16,但你传给我是%@", @(integer));
|
||||
|
||||
NSString *letter = nil;
|
||||
switch (integer) {
|
||||
case 10:
|
||||
letter = @"A";
|
||||
break;
|
||||
case 11:
|
||||
letter = @"B";
|
||||
break;
|
||||
case 12:
|
||||
letter = @"C";
|
||||
break;
|
||||
case 13:
|
||||
letter = @"D";
|
||||
break;
|
||||
case 14:
|
||||
letter = @"E";
|
||||
break;
|
||||
case 15:
|
||||
letter = @"F";
|
||||
break;
|
||||
default:
|
||||
letter = [[NSString alloc]initWithFormat:@"%@", @(integer)];
|
||||
break;
|
||||
}
|
||||
return letter;
|
||||
}
|
||||
|
||||
+ (UIColor *)lks_colorWithCGColor:(CGColorRef)cgColor {
|
||||
if (!cgColor) {
|
||||
return nil;
|
||||
}
|
||||
if (CFGetTypeID(cgColor) != CGColorGetTypeID()) {
|
||||
return nil;
|
||||
}
|
||||
return [UIColor colorWithCGColor:cgColor];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#endif /* SHOULD_COMPILE_LOOKIN_SERVER */
|
||||
22
Pods/LookinServer/Src/Main/Server/Category/UIImage+LookinServer.h
generated
Normal file
22
Pods/LookinServer/Src/Main/Server/Category/UIImage+LookinServer.h
generated
Normal file
@@ -0,0 +1,22 @@
|
||||
#ifdef SHOULD_COMPILE_LOOKIN_SERVER
|
||||
|
||||
//
|
||||
// UIImage+LookinServer.h
|
||||
// LookinServer
|
||||
//
|
||||
// Created by Li Kai on 2019/5/14.
|
||||
// https://lookin.work
|
||||
//
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
@interface UIImage (LookinServer)
|
||||
|
||||
/// 该方法的实现需要 Hook,因此若定义了 LOOKIN_SERVER_DISABLE_HOOK 宏,则属性会返回 nil
|
||||
@property(nonatomic, copy) NSString *lks_imageSourceName;
|
||||
|
||||
- (NSData *)lookin_data;
|
||||
|
||||
@end
|
||||
|
||||
#endif /* SHOULD_COMPILE_LOOKIN_SERVER */
|
||||
95
Pods/LookinServer/Src/Main/Server/Category/UIImage+LookinServer.m
generated
Normal file
95
Pods/LookinServer/Src/Main/Server/Category/UIImage+LookinServer.m
generated
Normal file
@@ -0,0 +1,95 @@
|
||||
#ifdef SHOULD_COMPILE_LOOKIN_SERVER
|
||||
|
||||
//
|
||||
// UIImage+LookinServer.m
|
||||
// LookinServer
|
||||
//
|
||||
// Created by Li Kai on 2019/5/14.
|
||||
// https://lookin.work
|
||||
//
|
||||
|
||||
#import <objc/runtime.h>
|
||||
#import "UIImage+LookinServer.h"
|
||||
#import "LookinServerDefines.h"
|
||||
|
||||
@implementation UIImage (LookinServer)
|
||||
|
||||
#ifdef LOOKIN_SERVER_DISABLE_HOOK
|
||||
|
||||
- (void)setLks_imageSourceName:(NSString *)lks_imageSourceName {
|
||||
}
|
||||
|
||||
- (NSString *)lks_imageSourceName {
|
||||
return nil;
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
+ (void)load {
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
Method oriMethod = class_getClassMethod([self class], @selector(imageNamed:));
|
||||
Method newMethod = class_getClassMethod([self class], @selector(lks_imageNamed:));
|
||||
method_exchangeImplementations(oriMethod, newMethod);
|
||||
|
||||
oriMethod = class_getClassMethod([self class], @selector(imageWithContentsOfFile:));
|
||||
newMethod = class_getClassMethod([self class], @selector(lks_imageWithContentsOfFile:));
|
||||
method_exchangeImplementations(oriMethod, newMethod);
|
||||
|
||||
oriMethod = class_getClassMethod([self class], @selector(imageNamed:inBundle:compatibleWithTraitCollection:));
|
||||
newMethod = class_getClassMethod([self class], @selector(lks_imageNamed:inBundle:compatibleWithTraitCollection:));
|
||||
method_exchangeImplementations(oriMethod, newMethod);
|
||||
|
||||
if (@available(iOS 13.0, tvOS 13.0, watchOS 6.0, *)) {
|
||||
oriMethod = class_getClassMethod([self class], @selector(imageNamed:inBundle:withConfiguration:));
|
||||
newMethod = class_getClassMethod([self class], @selector(lks_imageNamed:inBundle:withConfiguration:));
|
||||
method_exchangeImplementations(oriMethod, newMethod);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
+ (nullable UIImage *)lks_imageNamed:(NSString *)name inBundle:(nullable NSBundle *)bundle withConfiguration:(nullable UIImageConfiguration *)configuration API_AVAILABLE(ios(13.0),tvos(13.0),watchos(6.0))
|
||||
{
|
||||
UIImage *image = [self lks_imageNamed:name inBundle:bundle withConfiguration:configuration];
|
||||
image.lks_imageSourceName = name;
|
||||
return image;
|
||||
}
|
||||
|
||||
+ (nullable UIImage *)lks_imageNamed:(NSString *)name inBundle:(nullable NSBundle *)bundle compatibleWithTraitCollection:(nullable UITraitCollection *)traitCollection API_AVAILABLE(ios(8.0))
|
||||
{
|
||||
UIImage *image = [self lks_imageNamed:name inBundle:bundle compatibleWithTraitCollection:traitCollection];
|
||||
image.lks_imageSourceName = name;
|
||||
return image;
|
||||
}
|
||||
|
||||
+ (UIImage *)lks_imageNamed:(NSString *)name {
|
||||
UIImage *image = [self lks_imageNamed:name];
|
||||
image.lks_imageSourceName = name;
|
||||
return image;
|
||||
}
|
||||
|
||||
+ (UIImage *)lks_imageWithContentsOfFile:(NSString *)path {
|
||||
UIImage *image = [self lks_imageWithContentsOfFile:path];
|
||||
|
||||
NSString *fileName = [[path componentsSeparatedByString:@"/"].lastObject componentsSeparatedByString:@"."].firstObject;
|
||||
image.lks_imageSourceName = fileName;
|
||||
return image;
|
||||
}
|
||||
|
||||
- (void)setLks_imageSourceName:(NSString *)lks_imageSourceName {
|
||||
[self lookin_bindObject:lks_imageSourceName.copy forKey:@"lks_imageSourceName"];
|
||||
}
|
||||
|
||||
- (NSString *)lks_imageSourceName {
|
||||
return [self lookin_getBindObjectForKey:@"lks_imageSourceName"];
|
||||
}
|
||||
|
||||
#endif /* LOOKIN_SERVER_DISABLE_HOOK */
|
||||
|
||||
- (NSData *)lookin_data {
|
||||
return UIImagePNGRepresentation(self);
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#endif /* SHOULD_COMPILE_LOOKIN_SERVER */
|
||||
20
Pods/LookinServer/Src/Main/Server/Category/UIImageView+LookinServer.h
generated
Normal file
20
Pods/LookinServer/Src/Main/Server/Category/UIImageView+LookinServer.h
generated
Normal file
@@ -0,0 +1,20 @@
|
||||
#ifdef SHOULD_COMPILE_LOOKIN_SERVER
|
||||
|
||||
//
|
||||
// UIImageView+LookinServer.h
|
||||
// LookinServer
|
||||
//
|
||||
// Created by Li Kai on 2019/9/18.
|
||||
// https://lookin.work
|
||||
//
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
@interface UIImageView (LookinServer)
|
||||
|
||||
- (NSString *)lks_imageSourceName;
|
||||
- (NSNumber *)lks_imageViewOidIfHasImage;
|
||||
|
||||
@end
|
||||
|
||||
#endif /* SHOULD_COMPILE_LOOKIN_SERVER */
|
||||
31
Pods/LookinServer/Src/Main/Server/Category/UIImageView+LookinServer.m
generated
Normal file
31
Pods/LookinServer/Src/Main/Server/Category/UIImageView+LookinServer.m
generated
Normal file
@@ -0,0 +1,31 @@
|
||||
#ifdef SHOULD_COMPILE_LOOKIN_SERVER
|
||||
|
||||
//
|
||||
// UIImageView+LookinServer.m
|
||||
// LookinServer
|
||||
//
|
||||
// Created by Li Kai on 2019/9/18.
|
||||
// https://lookin.work
|
||||
//
|
||||
|
||||
#import "UIImageView+LookinServer.h"
|
||||
#import "UIImage+LookinServer.h"
|
||||
#import "NSObject+LookinServer.h"
|
||||
|
||||
@implementation UIImageView (LookinServer)
|
||||
|
||||
- (NSString *)lks_imageSourceName {
|
||||
return self.image.lks_imageSourceName;
|
||||
}
|
||||
|
||||
- (NSNumber *)lks_imageViewOidIfHasImage {
|
||||
if (!self.image) {
|
||||
return nil;
|
||||
}
|
||||
unsigned long oid = [self lks_registerOid];
|
||||
return @(oid);
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#endif /* SHOULD_COMPILE_LOOKIN_SERVER */
|
||||
21
Pods/LookinServer/Src/Main/Server/Category/UILabel+LookinServer.h
generated
Normal file
21
Pods/LookinServer/Src/Main/Server/Category/UILabel+LookinServer.h
generated
Normal file
@@ -0,0 +1,21 @@
|
||||
#ifdef SHOULD_COMPILE_LOOKIN_SERVER
|
||||
|
||||
//
|
||||
// UILabel+LookinServer.h
|
||||
// LookinServer
|
||||
//
|
||||
// Created by Li Kai on 2019/2/26.
|
||||
// https://lookin.work
|
||||
//
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
@interface UILabel (LookinServer)
|
||||
|
||||
@property(nonatomic, assign) CGFloat lks_fontSize;
|
||||
|
||||
- (NSString *)lks_fontName;
|
||||
|
||||
@end
|
||||
|
||||
#endif /* SHOULD_COMPILE_LOOKIN_SERVER */
|
||||
29
Pods/LookinServer/Src/Main/Server/Category/UILabel+LookinServer.m
generated
Normal file
29
Pods/LookinServer/Src/Main/Server/Category/UILabel+LookinServer.m
generated
Normal file
@@ -0,0 +1,29 @@
|
||||
#ifdef SHOULD_COMPILE_LOOKIN_SERVER
|
||||
|
||||
//
|
||||
// UILabel+LookinServer.m
|
||||
// LookinServer
|
||||
//
|
||||
// Created by Li Kai on 2019/2/26.
|
||||
// https://lookin.work
|
||||
//
|
||||
|
||||
#import "UILabel+LookinServer.h"
|
||||
|
||||
@implementation UILabel (LookinServer)
|
||||
|
||||
- (CGFloat)lks_fontSize {
|
||||
return self.font.pointSize;
|
||||
}
|
||||
- (void)setLks_fontSize:(CGFloat)lks_fontSize {
|
||||
UIFont *font = [self.font fontWithSize:lks_fontSize];
|
||||
self.font = font;
|
||||
}
|
||||
|
||||
- (NSString *)lks_fontName {
|
||||
return self.font.fontName;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#endif /* SHOULD_COMPILE_LOOKIN_SERVER */
|
||||
19
Pods/LookinServer/Src/Main/Server/Category/UITableView+LookinServer.h
generated
Normal file
19
Pods/LookinServer/Src/Main/Server/Category/UITableView+LookinServer.h
generated
Normal file
@@ -0,0 +1,19 @@
|
||||
#ifdef SHOULD_COMPILE_LOOKIN_SERVER
|
||||
|
||||
//
|
||||
// UITableView+LookinServer.h
|
||||
// LookinServer
|
||||
//
|
||||
// Created by Li Kai on 2019/9/5.
|
||||
// https://lookin.work
|
||||
//
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
@interface UITableView (LookinServer)
|
||||
|
||||
- (NSArray<NSNumber *> *)lks_numberOfRows;
|
||||
|
||||
@end
|
||||
|
||||
#endif /* SHOULD_COMPILE_LOOKIN_SERVER */
|
||||
29
Pods/LookinServer/Src/Main/Server/Category/UITableView+LookinServer.m
generated
Normal file
29
Pods/LookinServer/Src/Main/Server/Category/UITableView+LookinServer.m
generated
Normal file
@@ -0,0 +1,29 @@
|
||||
#ifdef SHOULD_COMPILE_LOOKIN_SERVER
|
||||
|
||||
//
|
||||
// UITableView+LookinServer.m
|
||||
// LookinServer
|
||||
//
|
||||
// Created by Li Kai on 2019/9/5.
|
||||
// https://lookin.work
|
||||
//
|
||||
|
||||
#import "UITableView+LookinServer.h"
|
||||
#import "LookinServerDefines.h"
|
||||
|
||||
@implementation UITableView (LookinServer)
|
||||
|
||||
- (NSArray<NSNumber *> *)lks_numberOfRows {
|
||||
NSUInteger sectionsCount = MIN(self.numberOfSections, 10);
|
||||
NSArray<NSNumber *> *rowsCount = [NSArray lookin_arrayWithCount:sectionsCount block:^id(NSUInteger idx) {
|
||||
return @([self numberOfRowsInSection:idx]);
|
||||
}];
|
||||
if (rowsCount.count == 0) {
|
||||
return nil;
|
||||
}
|
||||
return rowsCount;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#endif /* SHOULD_COMPILE_LOOKIN_SERVER */
|
||||
21
Pods/LookinServer/Src/Main/Server/Category/UITextField+LookinServer.h
generated
Normal file
21
Pods/LookinServer/Src/Main/Server/Category/UITextField+LookinServer.h
generated
Normal file
@@ -0,0 +1,21 @@
|
||||
#ifdef SHOULD_COMPILE_LOOKIN_SERVER
|
||||
|
||||
//
|
||||
// UITextField+LookinServer.h
|
||||
// LookinServer
|
||||
//
|
||||
// Created by Li Kai on 2019/2/26.
|
||||
// https://lookin.work
|
||||
//
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
@interface UITextField (LookinServer)
|
||||
|
||||
@property(nonatomic, assign) CGFloat lks_fontSize;
|
||||
|
||||
- (NSString *)lks_fontName;
|
||||
|
||||
@end
|
||||
|
||||
#endif /* SHOULD_COMPILE_LOOKIN_SERVER */
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user