file_path
stringlengths
3
280
file_language
stringclasses
66 values
content
stringlengths
1
1.04M
repo_name
stringlengths
5
92
repo_stars
int64
0
154k
repo_description
stringlengths
0
402
repo_primary_language
stringclasses
108 values
developer_username
stringlengths
1
25
developer_name
stringlengths
0
30
developer_company
stringlengths
0
82
ios/Classes/PullToRefresh/UIView+SNEdge.h
C/C++ Header
// // UIView+SNEdge.h // navigation // // Created by lamo on 14-5-29. // Copyright (c) 2014年 jhs. All rights reserved. // #import <UIKit/UIKit.h> #define SNStructWith(_Origin_, _Path_, _Value_) \ ({ \ typeof(_Origin_) a = (_Origin_); \ a._Path_ = (_Value_); \ a; \ }) @interface UIView (SNEdge) @property(nonatomic, assign) CGFloat sn_top; @property(nonatomic, assign) CGFloat sn_bottom; @property(nonatomic, assign) CGFloat sn_left; @property(nonatomic, assign) CGFloat sn_right; @property(nonatomic, assign) CGFloat sn_width; @property(nonatomic, assign) CGFloat sn_height; @property(nonatomic, assign) CGFloat sn_centerX; @property(nonatomic, assign) CGFloat sn_centerY; @property(nonatomic, assign) CGPoint sn_origin; @property(nonatomic, assign) CGSize sn_size; - (void)removeAllSubviews; - (UIViewController*)viewController; @end
xiekw2010/Cnodejs-React-Native
0
Yet another client for https://cnodejs.org/ building on react-native
Objective-C
xiekw2010
David Tse
Alipay
ios/Classes/PullToRefresh/UIView+SNEdge.m
Objective-C
// // UIView+SNEdge.m // navigation // // Created by lamo on 14-5-29. // Copyright (c) 2014年 jhs. All rights reserved. // #import "UIView+SNEdge.h" #define returnOnEqual(_P_) \ do { \ if (self._P_ == _P_) \ return; \ } while (0) #define selfCenterWithY(_Y_) (SNStructWith(self.center, y, _Y_)) #define selfCenterWithX(_X_) (SNStructWith(self.center, x, _X_)) /* * frame属性在transform不等于CGAffineTransformIdentity时,返回值未定义并且不应该被修改 * 下面实现全部基于center和bounds属性 */ @implementation UIView (SNEdge) - (CGFloat)sn_top { return self.center.y - self.sn_height / 2.0; } - (void)setSn_top:(CGFloat)sn_top { returnOnEqual(sn_top); self.center = selfCenterWithY(sn_top + self.sn_height / 2.0); } - (CGFloat)sn_bottom { return self.center.y + self.sn_height / 2.0; } - (void)setSn_bottom:(CGFloat)sn_bottom { returnOnEqual(sn_bottom); self.center = selfCenterWithY(sn_bottom - self.sn_height / 2.0); } - (CGFloat)sn_left { return self.center.x - self.sn_width / 2.0; } - (void)setSn_left:(CGFloat)sn_left { returnOnEqual(sn_left); self.center = selfCenterWithX(sn_left + self.sn_width / 2.0); } - (CGFloat)sn_right { return self.center.x + self.sn_width / 2.0; } - (void)setSn_right:(CGFloat)sn_right { returnOnEqual(sn_right); self.center = selfCenterWithX(sn_right - self.sn_width / 2.0); } - (CGFloat)sn_width { return self.bounds.size.width; } - (void)setSn_width:(CGFloat)sn_width { returnOnEqual(sn_width); self.bounds = SNStructWith(self.bounds, size.width, sn_width); } - (CGFloat)sn_height { return self.bounds.size.height; } - (void)setSn_height:(CGFloat)sn_height { returnOnEqual(sn_height); self.bounds = SNStructWith(self.bounds, size.height, sn_height); } - (CGFloat)sn_centerX { return self.center.x; } - (void)setSn_centerX:(CGFloat)sn_centerX { returnOnEqual(sn_centerX); self.center = selfCenterWithX(sn_centerX); } - (CGFloat)sn_centerY { return self.center.y; } - (void)setSn_centerY:(CGFloat)sn_centerY { returnOnEqual(sn_centerY); self.center = selfCenterWithX(sn_centerY); } -(void)setSn_origin:(CGPoint)sn_origin{ if (CGPointEqualToPoint(sn_origin, self.frame.origin)){ return; } CGRect frame = self.frame; frame.origin = sn_origin; self.frame = frame; } -(CGPoint)sn_origin{ return self.frame.origin; } -(void)setSn_size:(CGSize)sn_size{ if (CGSizeEqualToSize(sn_size, self.frame.size)){ return; } CGRect frame = self.frame; frame.size = sn_size; self.frame = frame; } -(CGSize)sn_size{ return self.frame.size; } - (void)removeAllSubviews { while (self.subviews.count) { UIView* child = self.subviews.lastObject; [child removeFromSuperview]; } } - (UIViewController*)viewController { for (UIView* next = self; next; next = next.superview) { if ([next.nextResponder isKindOfClass:[UIViewController class]]) { return (UIViewController*)next.nextResponder; } } return nil; } @end #undef returnOnEqual
xiekw2010/Cnodejs-React-Native
0
Yet another client for https://cnodejs.org/ building on react-native
Objective-C
xiekw2010
David Tse
Alipay
ios/Classes/UIView+TopBarMessage.h
C/C++ Header
// // UIViewController+TopBarMessage.h // DXTopBarMessageView // // Created by xiekw on 14-3-17. // Copyright (c) 2014年 xiekw. All rights reserved. // #import <UIKit/UIKit.h> @interface TopWarningView : UIView @property (nonatomic, strong) NSString *warningText; @property (nonatomic, strong) UIImageView *iconIgv; @property (nonatomic, copy) dispatch_block_t tapHandler; @property (nonatomic, assign) CGFloat dimissDelay; @property (nonatomic, strong) UILabel *label; - (void)resetViews; @end @interface UIView (TopBarMessage) /** * Set the global default apperance of the top message, may be the appdelegate class is a good place to setup * * @param apperance the top bar view config, the whole version will be @{kDXTopBarBackgroundColor:[UIColor blueColor], kDXTopBarTextColor : [UIColor yellowColor], kDXTopBarIcon : [UIImage imageNamed:@"icon.png"], kDXTopBarTextFont : [UIFont boldSystemFontOfSize:15.0]} */ + (void)setTopMessageDefaultApperance:(NSDictionary *)apperance; /** * show the message with config on the top bar, note the config won't change the default top message apperance, this is the setTopMessageDefaultApperance: does. * * @param message the text to show * @param config the top bar view config, the whole version will be @{kDXTopBarBackgroundColor:[UIColor blueColor], kDXTopBarTextColor : [UIColor yellowColor], kDXTopBarIcon : [UIImage imageNamed:@"icon.png"], kDXTopBarTextFont : [UIFont boldSystemFontOfSize:15.0]} * @param delay time to dismiss * @param tapHandler the tap handler */ - (void)showTopMessage:(NSString *)message topBarConfig:(NSDictionary *)config dismissDelay:(CGFloat)delay withTapBlock:(dispatch_block_t)tapHandler; /** * Default style message something like Instagram does * * @param message message to tell */ - (void)showTopMessage:(NSString *)message; @end extern NSString * const kDXTopBarBackgroundColor; extern NSString * const kDXTopBarTextColor; extern NSString * const kDXTopBarTextFont; extern NSString * const kDXTopBarIcon; extern NSString * const kDXTopBarOffset;
xiekw2010/Cnodejs-React-Native
0
Yet another client for https://cnodejs.org/ building on react-native
Objective-C
xiekw2010
David Tse
Alipay
ios/Classes/UIView+TopBarMessage.m
Objective-C
// // UIViewController+TopBarMessage.m // DXTopBarMessageView // // Created by xiekw on 14-3-17. // Copyright (c) 2014年 xiekw. All rights reserved. // #import "UIView+TopBarMessage.h" #import <objc/runtime.h> #define kTopBarHeight 38.0f #define kDefaultDimissDelay 3.0f NSString * const kDXTopBarBackgroundColor = @"dx.kDXTopBarBackgroundColor"; NSString * const kDXTopBarTextColor = @"dx.kDXTopBarTextColor"; NSString * const kDXTopBarTextFont = @"dx.kDXTopBarTextFont"; NSString * const kDXTopBarIcon = @"dx.kDXTopBarIcon"; NSString * const kDXTopBarOffset = @"dx.kDXTopBarOffset"; static NSMutableDictionary *__defaultTopMessageConfig = nil; @interface TopWarningView() @property (nonatomic, strong) NSTimer *dimissTimer; @end @implementation TopWarningView - (void)dealloc { [self.dimissTimer invalidate]; self.dimissTimer = nil; } - (instancetype)initWithFrame:(CGRect)frame { if (self = [super initWithFrame:frame]) { self.autoresizingMask = UIViewAutoresizingFlexibleWidth; self.label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 50, 50)]; self.label.backgroundColor = [UIColor clearColor]; self.label.autoresizingMask = UIViewAutoresizingFlexibleWidth; [self addSubview:self.label]; self.iconIgv = [[UIImageView alloc] init]; [self addSubview:self.iconIgv]; UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(dismiss)]; swipe.direction = UISwipeGestureRecognizerDirectionUp; [self addGestureRecognizer:swipe]; UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapNow)]; [self addGestureRecognizer:tap]; [self resetViews]; } return self; } - (void)resetViews { if (!__defaultTopMessageConfig) { __defaultTopMessageConfig = [@{kDXTopBarBackgroundColor : [UIColor colorWithRed:0.64 green:0.65 blue:0.66 alpha:0.96], kDXTopBarTextColor : [UIColor whiteColor], kDXTopBarTextFont : [UIFont fontWithName:@"HelveticaNeue-Medium" size:17.0]} mutableCopy]; } self.iconIgv.image = __defaultTopMessageConfig[kDXTopBarIcon]; self.backgroundColor = __defaultTopMessageConfig[kDXTopBarBackgroundColor]; self.label.textColor = __defaultTopMessageConfig[kDXTopBarTextColor]; self.label.font = __defaultTopMessageConfig[kDXTopBarTextFont]; } - (void)layoutSubviews { CGSize textSize = [self.label.text boundingRectWithSize:CGSizeMake(CGRectGetWidth(self.bounds) * 0.9, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.label.font} context:nil].size; CGFloat betweenIconAndText = 10.0f; CGFloat iconWidth = 20.0f; CGFloat labelDefaultHeight = 20.0; if (!self.iconIgv.image) { iconWidth = 0.0f; } self.iconIgv.frame = CGRectMake((CGRectGetWidth(self.bounds) - (textSize.width + iconWidth + betweenIconAndText)) * 0.5, (CGRectGetHeight(self.bounds) - iconWidth) * 0.5, iconWidth, iconWidth); self.label.frame = CGRectMake(CGRectGetMaxX(self.iconIgv.frame) + betweenIconAndText, (CGRectGetHeight(self.bounds) - labelDefaultHeight) * 0.5, textSize.width, labelDefaultHeight); } - (void)setWarningText:(NSString *)warningText { _warningText = warningText; self.label.text = _warningText; [self setNeedsLayout]; } - (void)tapNow { if (self.tapHandler) { self.tapHandler(); } } - (void)dismiss { CGRect selfFrame = self.frame; selfFrame.origin.y -= CGRectGetHeight(selfFrame); [UIView animateWithDuration:0.25f animations:^{ self.frame = selfFrame; self.alpha = 0.3; } completion:^(BOOL finished) { [self removeFromSuperview]; }]; } - (void)willMoveToSuperview:(UIView *)newSuperview { if (newSuperview) { self.alpha = 1.0; CGRect selfFrame = self.frame; CGFloat originY = self.frame.origin.y; selfFrame.origin.y -= CGRectGetHeight(selfFrame); self.frame = selfFrame; selfFrame.origin.y = originY; [UIView animateWithDuration:0.25f animations:^{ self.frame = selfFrame; } completion:^(BOOL finished) { [super willMoveToSuperview:newSuperview]; }]; [self.dimissTimer invalidate]; self.dimissTimer = nil; self.dimissTimer = [NSTimer scheduledTimerWithTimeInterval:MAX(self.dimissDelay, kDefaultDimissDelay) target:self selector:@selector(dismiss) userInfo:nil repeats:0]; }else { [self.dimissTimer invalidate]; self.dimissTimer = nil; [super willMoveToSuperview:newSuperview]; } } @end static char TopWarningKey; @implementation UIView (TopBarMessage) + (void)setTopMessageDefaultApperance:(NSDictionary *)apperance { if (!__defaultTopMessageConfig) { __defaultTopMessageConfig = [NSMutableDictionary dictionary]; } if (apperance) { UIColor *bgColor = apperance[kDXTopBarBackgroundColor]; if (bgColor && [bgColor isKindOfClass:[UIColor class]]) { __defaultTopMessageConfig[kDXTopBarBackgroundColor] = bgColor; } UIColor *textColor = apperance[kDXTopBarTextColor]; if (textColor && [textColor isKindOfClass:[UIColor class]]) { __defaultTopMessageConfig[kDXTopBarTextColor] = textColor; } UIImage *icon = apperance[kDXTopBarIcon]; if (icon && [icon isKindOfClass:[UIImage class]]) { __defaultTopMessageConfig[kDXTopBarIcon] = icon; } UIFont *font = apperance[kDXTopBarTextFont]; if (font && [font isKindOfClass:[UIFont class]]) { __defaultTopMessageConfig[kDXTopBarTextFont] = font; } } } - (void)showTopMessage:(NSString *)message { [self showTopMessage:message topBarConfig:nil dismissDelay:kDefaultDimissDelay withTapBlock:nil]; } - (void)showTopMessage:(NSString *)message topBarConfig:(NSDictionary *)config dismissDelay:(CGFloat)delay withTapBlock:(dispatch_block_t)tapHandler { TopWarningView *topV = objc_getAssociatedObject(self, &TopWarningKey); if (!topV) { topV = [[TopWarningView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.bounds), kTopBarHeight)]; objc_setAssociatedObject(self, &TopWarningKey, topV, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } CGFloat startY = [config[kDXTopBarOffset] floatValue]; if ([self isKindOfClass:[UIScrollView class]]) { UIScrollView *scv = (UIScrollView *)self; startY = scv.contentInset.top; } topV.frame = CGRectMake(0, startY, CGRectGetWidth(self.bounds), kTopBarHeight); topV.warningText = message; topV.tapHandler = tapHandler; topV.dimissDelay = delay; if (config) { UIColor *bgColor = config[kDXTopBarBackgroundColor]; if (bgColor && [bgColor isKindOfClass:[UIColor class]]) { topV.backgroundColor = bgColor; } UIColor *textColor = config[kDXTopBarTextColor]; if (textColor && [textColor isKindOfClass:[UIColor class]]) { topV.label.textColor = textColor; } UIImage *icon = config[kDXTopBarIcon]; if (icon && [icon isKindOfClass:[UIImage class]]) { topV.iconIgv.image = icon; } UIFont *font = config[kDXTopBarTextFont]; if (font && [font isKindOfClass:[UIFont class]]) { topV.label.font = font; } }else { [topV resetViews]; } [self addSubview:topV]; } @end
xiekw2010/Cnodejs-React-Native
0
Yet another client for https://cnodejs.org/ building on react-native
Objective-C
xiekw2010
David Tse
Alipay
ios/NativePlayViewControllr.h
C/C++ Header
// // NativePlayViewControllr.h // RN_CNNode // // Created by xiekw on 15/10/22. // Copyright © 2015年 Facebook. All rights reserved. // #import <UIKit/UIKit.h> @interface NativePlayViewControllr : UIViewController @end
xiekw2010/Cnodejs-React-Native
0
Yet another client for https://cnodejs.org/ building on react-native
Objective-C
xiekw2010
David Tse
Alipay
ios/NativePlayViewControllr.m
Objective-C
// // NativePlayViewControllr.m // RN_CNNode // // Created by xiekw on 15/10/22. // Copyright © 2015年 Facebook. All rights reserved. // #import "NativePlayViewControllr.h" #import "DXTextCategoryMenu.h" @interface NativePlayViewControllr () { DXTextCategoryMenu *_menu; } @end @implementation NativePlayViewControllr - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. UIImage *image = [UIImage imageNamed:@"IMG_1718"]; UIImageView *imageV = [[UIImageView alloc] initWithFrame:self.view.bounds]; imageV.image = image; [self.view addSubview:imageV]; NSArray *options = @[@"nihao", @"我好", @"大家号", @"不错", @"aiyo", @"周杰伦", @"才衣领", @"王心凌", @"go", @"mic", @"大家号", @"不错", @"aiyo", @"周杰伦", @"才衣领", @"王心凌"]; // NSArray *options = @[@"王心凌", @"王心凌", @"大家号", @"王心凌", @"王心凌", @"周杰伦", @"才衣领", @"王心凌"]; _menu = [[DXTextCategoryMenu alloc] initWithFrame:CGRectMake(0, 100, CGRectGetWidth(self.view.bounds), 38.0)]; _menu.options = options; [self.view addSubview:_menu]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } /* #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ @end
xiekw2010/Cnodejs-React-Native
0
Yet another client for https://cnodejs.org/ building on react-native
Objective-C
xiekw2010
David Tse
Alipay
ios/RN_CNNode/AppDelegate.h
C/C++ Header
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (nonatomic, strong) UIWindow *window; @end
xiekw2010/Cnodejs-React-Native
0
Yet another client for https://cnodejs.org/ building on react-native
Objective-C
xiekw2010
David Tse
Alipay
ios/RN_CNNode/AppDelegate.m
Objective-C
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #import "AppDelegate.h" #import "RCTRootView.h" #import "NativePlayViewControllr.h" @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { NSURL *jsCodeLocation; /** * Loading JavaScript code - uncomment the one you want. * * OPTION 1 * Load from development server. Start the server from the repository root: * * $ npm start * * To run on device, change `localhost` to the IP address of your computer * (you can get this by typing `ifconfig` into the terminal and selecting the * `inet` value under `en0:`) and make sure your computer and iOS device are * on the same Wi-Fi network. */ /** * OPTION 2 * Load from pre-bundled file on disk. To re-generate the static bundle * from the root of your project directory, run * * $ react-native bundle --minify * * see http://facebook.github.io/react-native/docs/runningondevice.html */ // jsCodeLocation = [NSURL URLWithString:@"http://wapp.waptest.taobao.com/rct/jumingping/mainjsbundle.js"]; // jsCodeLocation = [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"]; jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.ios.bundle"]; RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation moduleName:@"RN_CNNode" initialProperties:nil launchOptions:launchOptions]; self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; UIViewController *rootViewController = [[UIViewController alloc] init]; rootViewController.view = rootView; self.window.rootViewController = rootViewController; [self.window makeKeyAndVisible]; // rootViewController = [NativePlayViewControllr new]; return YES; } @end
xiekw2010/Cnodejs-React-Native
0
Yet another client for https://cnodejs.org/ building on react-native
Objective-C
xiekw2010
David Tse
Alipay
ios/RN_CNNode/main.m
Objective-C
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #import <UIKit/UIKit.h> #import "AppDelegate.h" int main(int argc, char * argv[]) { @autoreleasepool { return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); } }
xiekw2010/Cnodejs-React-Native
0
Yet another client for https://cnodejs.org/ building on react-native
Objective-C
xiekw2010
David Tse
Alipay
ios/RN_CNNodeTests/RN_CNNodeTests.m
Objective-C
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #import <UIKit/UIKit.h> #import <XCTest/XCTest.h> #import "RCTLog.h" #import "RCTRootView.h" #define TIMEOUT_SECONDS 240 #define TEXT_TO_LOOK_FOR @"Welcome to React Native!" @interface RN_CNNodeTests : XCTestCase @end @implementation RN_CNNodeTests - (BOOL)findSubviewInView:(UIView *)view matching:(BOOL(^)(UIView *view))test { if (test(view)) { return YES; } for (UIView *subview in [view subviews]) { if ([self findSubviewInView:subview matching:test]) { return YES; } } return NO; } - (void)testRendersWelcomeScreen { UIViewController *vc = [[[[UIApplication sharedApplication] delegate] window] rootViewController]; NSDate *date = [NSDate dateWithTimeIntervalSinceNow:TIMEOUT_SECONDS]; BOOL foundElement = NO; __block NSString *redboxError = nil; RCTSetLogFunction(^(RCTLogLevel level, NSString *fileName, NSNumber *lineNumber, NSString *message) { if (level >= RCTLogLevelError) { redboxError = message; } }); while ([date timeIntervalSinceNow] > 0 && !foundElement && !redboxError) { [[NSRunLoop mainRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; [[NSRunLoop mainRunLoop] runMode:NSRunLoopCommonModes beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; foundElement = [self findSubviewInView:vc.view matching:^BOOL(UIView *view) { if ([view.accessibilityLabel isEqualToString:TEXT_TO_LOOK_FOR]) { return YES; } return NO; }]; } RCTSetLogFunction(RCTDefaultLogFunction); XCTAssertNil(redboxError, @"RedBox error: %@", redboxError); XCTAssertTrue(foundElement, @"Couldn't find element with text '%@' in %d seconds", TEXT_TO_LOOK_FOR, TIMEOUT_SECONDS); } @end
xiekw2010/Cnodejs-React-Native
0
Yet another client for https://cnodejs.org/ building on react-native
Objective-C
xiekw2010
David Tse
Alipay
iosComponents/AllTopicsComponent.js
JavaScript
const React = require('react-native'); const CNodeService = require('../networkService/CNodeService'); const TopicCell = require('./TopicCellComponent'); const Routes = require('./Routes'); const CommonComponents = require('../iosComponents/CommonComponents'); const DXRefreshControl = require('./DXRefreshControl'); const DXTopMessage = require('./DXTopMessage'); const { ListView, View, ActivityIndicatorIOS, } = React; const LISTVIEWREF = 'listview'; const CONTAINERREF = 'container' const AllTopicsComponent = React.createClass({ getInitialState() { return { dataSource: new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2}), loaded: false, }; }, showError(error) { console.log('reloadTopics is' + error); DXTopMessage.showTopMessage(this.refs[CONTAINERREF], error.toString(), {offset: 64.0}, () => { console.log('did Tap message'); }); }, reloadTopics() { CNodeService.reloadTopics((error, responseData) => { if (!error) { this.updateDataSourceHandler(responseData); } else { this.showError(error); } let listNode = this.refs[LISTVIEWREF]; if (listNode) { DXRefreshControl.endRefreshing(listNode); } }); }, appendTopics() { CNodeService.appendTopics((error, responseData) => { if (!error) { this.updateDataSourceHandler(responseData); } else { this.showError(error); } }); }, updateDataSourceHandler(responseData) { this.setState({ dataSource: this.state.dataSource.cloneWithRows(responseData), loaded: true }); }, componentDidMount() { this.reloadTopics(); }, componentDidUpdate(prevProps, prevState) { let node = this.refs[LISTVIEWREF]; if (!node || this.props.didAddRefreshControl) { return; } let refreshConfig = { // options: UIRefreshControl, JHSPullToRefreshControl headerViewClass: 'UIRefreshControl', // options: JHSCartoonPullToRefreshView, JHSMagicLampPullToRefreshView // contentViewClass: 'JHSCartoonPullToRefreshView', // color: '#AA00FF' }; DXRefreshControl.configureCustom(node, refreshConfig, this.reloadTopics); this.props.didAddRefreshControl = true; }, render() { if (!this.state.loaded) { return CommonComponents.renderLoadingView(); } return ( <View style={{flex: 1}} ref={CONTAINERREF}> <ListView ref={LISTVIEWREF} dataSource={this.state.dataSource} renderRow={this.renderTopic} onEndReached={this.appendTopics} scrollRenderAheadDistance={50} renderFooter={this.renderFooter} /> </View> ); }, renderFooter() { if (!CNodeService.isReachEnd) { return ( <View style={{flex: 1, alignItems: 'center', height: 40, justifyContent: 'center'}} > <ActivityIndicatorIOS size='small' /> </View> ) } }, renderTopic(topic) { return ( <TopicCell topic={topic} onCellPress={this.onCellPress} /> ); }, onCellPress(topic) { this.props.navigator.push(Routes.topic(topic)); }, }); module.exports = AllTopicsComponent;
xiekw2010/Cnodejs-React-Native
0
Yet another client for https://cnodejs.org/ building on react-native
Objective-C
xiekw2010
David Tse
Alipay
iosComponents/CommonComponents.js
JavaScript
const React = require('react-native'); const Colors = require('../commonComponents/Colors'); const CommonStyles = require('../commonComponents/CommonStyles'); const { StyleSheet, View, ActivityIndicatorIOS, Text, } = React; class CommonComponents { static renderLoadingView() { return ( <View style={CommonStyles.container}> <ActivityIndicatorIOS size="large" /> </View> ); } static renderPlaceholder(text, image, onPress) { return ( <View> </View> ) } static renderFloorHeader(floorName) { return ( <View style={CommonStyles.floorTopName}> <View style={CommonStyles.lineStyle}> </View> <Text style={CommonStyles.floorTopText}> {floorName} </Text> </View> ); } static renderKengSep() { return ( <View style={CommonStyles.bottomLine}> </View> ) } } module.exports = CommonComponents;
xiekw2010/Cnodejs-React-Native
0
Yet another client for https://cnodejs.org/ building on react-native
Objective-C
xiekw2010
David Tse
Alipay
iosComponents/DXRefreshControl.js
JavaScript
/** * @providesModule RCTRefreshControl */ 'use strict'; var React = require('react-native'); var { DeviceEventEmitter, NativeModules: { DXRefreshControl, } } = React; /** * A pull down to refresh control like the one in Apple's iOS6 Mail App. */ var DROP_VIEW_DID_BEGIN_REFRESHING_EVENT = 'dropViewDidBeginRefreshing'; var callbacks = {}; var subscription = DeviceEventEmitter.addListener( DROP_VIEW_DID_BEGIN_REFRESHING_EVENT, (reactTag) => callbacks[reactTag]() ); // subscription.remove(); var DXRNRefreshControl = { configureCustom(node, config, callback) { var nodeHandle = React.findNodeHandle(node) || 1; DXRefreshControl.configureCustom(nodeHandle, config, (error) => { if (!error) { callbacks[nodeHandle] = callback; } }); }, endRefreshing(node) { var nodeHandle = React.findNodeHandle(node) || 1; DXRefreshControl.endRefreshing(nodeHandle); }, beginRefreshing(node) { var nodeHandle = React.findNodeHandle(node) || 1; DXRefreshControl.beginRefreshing(nodeHandle); } }; module.exports = DXRNRefreshControl;
xiekw2010/Cnodejs-React-Native
0
Yet another client for https://cnodejs.org/ building on react-native
Objective-C
xiekw2010
David Tse
Alipay
iosComponents/DXTextMenu.js
JavaScript
/* @flow weak */ var React = require('react-native'); const { requireNativeComponent } = require('react-native'); const DXCategoryMenuManager = require('NativeModules').DXCategoryMenuManager; const EdgeInsetsPropType = require('EdgeInsetsPropType'); var CategoryTextMenu = React.createClass({ propTypes: { options: React.PropTypes.array, onSelectedIndexChange: React.PropTypes.func, lockStartPosition: React.PropTypes.bool, selectedColor: React.PropTypes.string, unSelectedColor: React.PropTypes.string, contentInset: EdgeInsetsPropType, spacingBetweenMenu: React.PropTypes.number, bottomLineHeight: React.PropTypes.number, selectedAnimationDuration: React.PropTypes.number, needCenterMenuOffset: React.PropTypes.bool, blur: React.PropTypes.bool, // [0, 1, 2] for [ExtraLight, light, dark] blurEffectStyle: React.PropTypes.number, }, _onChange(event) { if (!this.props.onSelectedIndexChange) { return; } const ne = event.nativeEvent; this.props.onSelectedIndexChange(ne.from, ne.to); }, updateSelectedIndex(node, selectedIndex) { var nodeHandle = React.findNodeHandle(node) || 1; DXCategoryMenuManager.updateSelectedIndex(nodeHandle, selectedIndex); }, render() { return ( <DXTextCategoryMenu {...this.props} onChange={this._onChange} /> ) } }); const DXTextCategoryMenu = requireNativeComponent('DXCategoryMenu', DXTextCategoryMenu); module.exports = CategoryTextMenu;
xiekw2010/Cnodejs-React-Native
0
Yet another client for https://cnodejs.org/ building on react-native
Objective-C
xiekw2010
David Tse
Alipay
iosComponents/DXTopMessage.js
JavaScript
/** * @providesModule DXTopMessageManager * @flow */ 'use strict'; var React = require('react-native'); var { DeviceEventEmitter, NativeModules: { DXTopMessageManager, } } = React; /** * A pull down to refresh control like the one in Apple's iOS6 Mail App. */ var MESSAGE_TAPPED = 'messageTapped'; var callbacks = {}; var subscription = DeviceEventEmitter.addListener( MESSAGE_TAPPED, (reactTag) => callbacks[reactTag]() ); // subscription.remove(); var DXRNTopMessage = { showTopMessage(node, message, config, callback) { var nodeHandle = React.findNodeHandle(node) || 1; DXTopMessageManager.showTopMessage(nodeHandle, message, config, () => { callbacks[nodeHandle] = callback; }); }, // showTopMessage(node, message, config, callback) { // var nodeHandle = React.findNodeHandle(node) || 1; // DXTopMessageManager.showTopMessage(node, message, config, () => { // callbacks[nodeHandle] = callback; // }); // } }; module.exports = DXRNTopMessage;
xiekw2010/Cnodejs-React-Native
0
Yet another client for https://cnodejs.org/ building on react-native
Objective-C
xiekw2010
David Tse
Alipay
iosComponents/MessageComponent.js
JavaScript
const React = require('react-native'); const DXTextMenu = require('./DXTextMenu'); const OPTIONS = ['你好', '问号', '狗带', '好玩', '你好', '问号', '狗带', '好玩', '你好', '问号', '狗带', '好玩']; const MessageComponent = React.createClass({ render() { return ( <DXTextMenu ref={(textMenu) => this.textMenu = textMenu} style={{height: 38, marginTop: 100}} options={OPTIONS} selectedColor={'blue'} blur={true} blurEffectStyle={2} contentInset={{top: 0, left: 0, bottom: 0, right: 0}} /> ); }, }); module.exports = MessageComponent;
xiekw2010/Cnodejs-React-Native
0
Yet another client for https://cnodejs.org/ building on react-native
Objective-C
xiekw2010
David Tse
Alipay
iosComponents/PersonalComponent.js
JavaScript
const React = require('react-native'); const CNodeService = require('../networkService/CNodeService'); const TopicCell = require('./TopicCellComponent'); const Routes = require('./Routes'); const CommonComponents = require('../iosComponents/CommonComponents'); const DXRefreshControl = require('./DXRefreshControl'); const DXTopMessage = require('./DXTopMessage'); const { ListView, View, } = React; const LISTVIEWREF = 'listview'; const CONTAINERREF = 'container' const Personal = React.createClass({ getInitialState() { return { dataSource: new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2}), loaded: false, }; }, showError(error) { console.log('reloadTopics is' + error); DXTopMessage.showTopMessage(this.refs[CONTAINERREF], error.toString(), {offset: 64.0}, () => { console.log('did Tap message'); }); }, reloadTopics() { CNodeService.reloadTopics((error, responseData) => { if (!error) { this.updateDataSourceHandler(responseData); } else { this.showError(error); } let listNode = this.refs[LISTVIEWREF]; if (listNode) { DXRefreshControl.endRefreshing(listNode); } }); }, appendTopics() { CNodeService.appendTopics((error, responseData) => { if (!error) { this.updateDataSourceHandler(responseData); } else { this.showError(error); } }); }, updateDataSourceHandler(responseData) { this.setState({ dataSource: this.state.dataSource.cloneWithRows(responseData), loaded: true }); }, componentDidMount() { this.reloadTopics(); }, componentDidUpdate(prevProps, prevState) { let node = this.refs[LISTVIEWREF]; if (!node || this.props.didAddRefreshControl) { return; } console.log('node is' + node); let refreshConfig = { // options: UIRefreshControl, JHSPullToRefreshControl headerViewClass: 'JHSPullToRefreshControl', // options: JHSCartoonPullToRefreshView, JHSMagicLampPullToRefreshView contentViewClass: 'JHSCartoonPullToRefreshView', color: '#AA00FF' }; DXRefreshControl.configureCustom(node, refreshConfig, this.reloadTopics); this.props.didAddRefreshControl = true; }, render() { if (!this.state.loaded) { return CommonComponents.renderLoadingView(); } return ( <View style={{flex: 1}} ref={CONTAINERREF}> <ListView ref={LISTVIEWREF} dataSource={this.state.dataSource} renderRow={this.renderTopic} onEndReached={this.appendTopics} scrollRenderAheadDistance={50} /> </View> ); }, renderTopic(topic) { return ( <TopicCell topic={topic} onCellPress={this.onCellPress} /> ); }, onCellPress(topic) { this.props.navigator.push(Routes.topic(topic)); }, }); module.exports = Personal;
xiekw2010/Cnodejs-React-Native
0
Yet another client for https://cnodejs.org/ building on react-native
Objective-C
xiekw2010
David Tse
Alipay
iosComponents/PostComponent.js
JavaScript
const React = require('react-native'); const CNodeService = require('../networkService/CNodeService'); const TopicCell = require('./TopicCellComponent'); const Routes = require('./Routes'); const CommonComponents = require('../iosComponents/CommonComponents'); const DXRefreshControl = require('./DXRefreshControl'); const DXTopMessage = require('./DXTopMessage'); const { ListView, View, ActivityIndicatorIOS, } = React; const LISTVIEWREF = 'listview'; const CONTAINERREF = 'container' const PostComponent = React.createClass({ getInitialState() { return { dataSource: new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2}), loaded: false, }; }, showError(error) { console.log('reloadTopics is' + error); DXTopMessage.showTopMessage(this.refs[CONTAINERREF], error.toString(), {offset: 64.0}, () => { console.log('did Tap message'); }); }, reloadTopics() { CNodeService.reloadTopics((error, responseData) => { if (!error) { this.updateDataSourceHandler(responseData); } else { this.showError(error); } let listNode = this.refs[LISTVIEWREF]; if (listNode) { DXRefreshControl.endRefreshing(listNode); } }); }, appendTopics() { CNodeService.appendTopics((error, responseData) => { if (!error) { this.updateDataSourceHandler(responseData); } else { this.showError(error); } }); }, updateDataSourceHandler(responseData) { this.setState({ dataSource: this.state.dataSource.cloneWithRows(responseData), loaded: true }); }, componentDidMount() { this.reloadTopics(); }, componentDidUpdate(prevProps, prevState) { let node = this.refs[LISTVIEWREF]; if (!node || this.props.didAddRefreshControl) { return; } let refreshConfig = { // options: UIRefreshControl, JHSPullToRefreshControl headerViewClass: 'JHSPullToRefreshControl', // options: JHSCartoonPullToRefreshView, JHSMagicLampPullToRefreshView contentViewClass: 'JHSCartoonPullToRefreshView', color: '#AA00FF' }; DXRefreshControl.configureCustom(node, refreshConfig, this.reloadTopics); this.props.didAddRefreshControl = true; }, render() { if (!this.state.loaded) { return CommonComponents.renderLoadingView(); } return ( <View style={{flex: 1}} ref={CONTAINERREF}> <ListView ref={LISTVIEWREF} dataSource={this.state.dataSource} renderRow={this.renderTopic} onEndReached={this.appendTopics} scrollRenderAheadDistance={50} renderFooter={this.renderFooter} /> </View> ); }, renderFooter() { if (!CNodeService.isReachEnd) { return ( <View style={{flex: 1, alignItems: 'center', height: 40, justifyContent: 'center'}} > <ActivityIndicatorIOS size='small' /> </View> ) } }, renderTopic(topic) { return ( <TopicCell topic={topic} onCellPress={this.onCellPress} /> ); }, onCellPress(topic) { this.props.navigator.push(Routes.topic(topic)); }, }); module.exports = PostComponent;
xiekw2010/Cnodejs-React-Native
0
Yet another client for https://cnodejs.org/ building on react-native
Objective-C
xiekw2010
David Tse
Alipay
iosComponents/Routes.js
JavaScript
class Routes { static allTopics() { return { component: require('./AllTopicsComponent'), title: 'cnodejs', }; } static topic(topic) { return { component: require('./TopicDetailComponent'), title: topic.title, passProps: {topic: topic} } } static search() { return { component: require('./SearchComponent'), title: '搜索' } } static personal() { return { component: require('./PersonalComponent'), title: '我' } } static post() { return { component: require('./PostComponent'), title: '发布' } } static message() { return { component: require('./MessageComponent'), title: '消息' } } } module.exports = Routes;
xiekw2010/Cnodejs-React-Native
0
Yet another client for https://cnodejs.org/ building on react-native
Objective-C
xiekw2010
David Tse
Alipay
iosComponents/SearchComponent.js
JavaScript
const React = require('react-native'); const CNodeService = require('../networkService/CNodeService'); const TopicCell = require('./TopicCellComponent'); const Routes = require('./Routes'); const CommonComponents = require('../iosComponents/CommonComponents'); const DXRefreshControl = require('./DXRefreshControl'); const DXTopMessage = require('./DXTopMessage'); const DXTextMenu = require('./DXTextMenu'); const OPTIONS = ['你好', '问号', '狗带', '好玩', '你好', '问号', '狗带', '好玩', '你好', '问号', '狗带', '好玩']; const { ListView, View, Text, } = React; const LISTVIEWREF = 'listview'; const CONTAINERREF = 'container'; const sectionIDs = ['精华', '置顶', '其他']; const SearchComponent = React.createClass({ getInitialState() { const dataSourceParam = { rowHasChanged: (row1, row2) => row1 !== row2, sectionHeaderHasChanged: (section1, section2) => section1 !== section2, } return { dataSource: new ListView.DataSource(dataSourceParam), loaded: false, }; }, showError(error) { console.log('reloadTopics is' + error); DXTopMessage.showTopMessage(this.refs[CONTAINERREF], error.toString(), {offset: 64.0}, () => { console.log('did Tap message'); }); }, reloadTopics() { CNodeService.reloadTopics((error, responseData) => { if (!error) { this.updateDataSourceHandler(responseData); } else { this.showError(error); } let listNode = this.refs[LISTVIEWREF]; if (listNode) { DXRefreshControl.endRefreshing(listNode); } }); }, appendTopics() { CNodeService.appendTopics((error, responseData) => { if (!error) { this.updateDataSourceHandler(responseData); } else { this.showError(error); } }); }, updateDataSourceHandler(responseData) { console.log('responseData is' + responseData); const goodTopics = []; const topTopics = []; const otherTopics = []; responseData.forEach((topic, index) => { if (topic.good) { goodTopics.push(topic); } else if (topic.top) { topTopics.push(topic); } else { otherTopics.push(topic); } }); const sectionData = {'精华': goodTopics, '置顶': topTopics, '其他': otherTopics}; this.setState({ dataSource: this.state.dataSource.cloneWithRowsAndSections(sectionData, sectionIDs), loaded: true }); }, componentDidMount() { this.reloadTopics(); }, componentDidUpdate(prevProps, prevState) { let node = this.refs[LISTVIEWREF]; if (!node || this.props.didAddRefreshControl) { return; } let refreshConfig = { // options: UIRefreshControl, JHSPullToRefreshControl headerViewClass: 'UIRefreshControl', // options: JHSCartoonPullToRefreshView, JHSMagicLampPullToRefreshView contentViewClass: 'JHSCartoonPullToRefreshView', color: '#AA00FF' }; DXRefreshControl.configureCustom(node, refreshConfig, this.reloadTopics); this.props.didAddRefreshControl = true; }, render() { if (!this.state.loaded) { return CommonComponents.renderLoadingView(); } return ( <View style={{flex: 1}} ref={CONTAINERREF}> <ListView ref={LISTVIEWREF} dataSource={this.state.dataSource} renderRow={this.renderTopic} onEndReached={this.appendTopics} scrollRenderAheadDistance={50} renderSectionHeader={this.renderTopicsTabHeader} /> </View> ); }, renderTopicsTabHeader(sectionData, sectionID) { return ( <DXTextMenu options={OPTIONS} style={{height: 38, backgroundColor:'red',flex: 0, position: 'absolute', top: 100}} selectedColor={'blue'} blur={true} blurEffectStyle={2} contentInset={{top: 0, left: 0, bottom: 0, right: 0}} /> ) }, renderTopic(topic, sectionID, rowID, highlightRow) { return ( <TopicCell topic={topic} onCellPress={this.onCellPress} /> ); }, onCellPress(topic) { this.props.navigator.push(Routes.topic(topic)); }, }); module.exports = SearchComponent;
xiekw2010/Cnodejs-React-Native
0
Yet another client for https://cnodejs.org/ building on react-native
Objective-C
xiekw2010
David Tse
Alipay
iosComponents/TopicCellComponent.js
JavaScript
const React = require('react-native'); const Colors = require('../commonComponents/Colors'); const TopicTab = require('./TopicTabComponent'); const { StyleSheet, View, Text, Image, TouchableHighlight, } = React; const styles = StyleSheet.create({ cellContentView: { flexDirection: 'column', flex: 1, alignItems: 'stretch' }, cellUp: { margin: 10, height: 40, flexDirection: 'column', flexWrap: 'wrap', alignItems: 'flex-start', justifyContent: 'flex-start' }, avatar: { width: 40, height: 40, backgroundColor: Colors.backGray }, username: { marginLeft: 10, height: 19, fontSize: 13, color: Colors.textGray }, createAt: { marginLeft: 10, marginTop: 5, height: 14, fontSize: 11, color: Colors.textGray }, cellDown: { color: Colors.textBlack, fontSize: 18, marginLeft: 20, marginRight: 20, marginBottom: 3, flex: 1 }, sepLine: { backgroundColor: Colors.lineGray, height: 1, marginLeft: 5 }, cellFooter: { alignSelf: 'flex-end', height: 16, marginRight: 10, marginBottom: 5 }, replyCount: { fontSize: 15, color: Colors.purple, }, visitCount: { fontSize: 12, color: Colors.textGray, } }); const TopicCellComponent = React.createClass({ propTypes: { topic: React.PropTypes.object, onCellPress: React.PropTypes.func, }, handleCellPress() { this.props.onCellPress(this.props.topic) }, render() { const topic = this.props.topic; return ( <TouchableHighlight onPress={this.handleCellPress} underlayColor={Colors.backGray}> <View style={styles.cellContentView}> <View style={styles.cellUp}> <Image source={{uri: topic.author.avatar_url}} style={styles.avatar} /> <Text style={styles.username}>{topic.author.loginname}</Text> <Text style={styles.createAt}>{topic.create_at}</Text> <TopicTab topic={topic} /> </View> <Text style={styles.cellDown}>{topic.title}</Text> <View style={styles.cellFooter}> <Text style={styles.replyCount}> {topic.reply_count} <Text style={style={fontSize:12, color:Colors.textBlack}}>{'/'}</Text> <Text style={styles.visitCount}>{topic.visit_count}</Text> </Text> </View> <View style={styles.sepLine}></View> </View> </TouchableHighlight> ); }, }); module.exports = TopicCellComponent
xiekw2010/Cnodejs-React-Native
0
Yet another client for https://cnodejs.org/ building on react-native
Objective-C
xiekw2010
David Tse
Alipay
iosComponents/TopicDetailComponent.js
JavaScript
const React = require('react-native'); const Colors = require('../commonComponents/Colors'); const Configs = require('../config'); const CommonStyles = require('../commonComponents/CommonStyles'); const CommonComponents = require('./CommonComponents'); const DXRefreshControl = require('./DXRefreshControl'); const { StyleSheet, WebView, ActivityIndicatorIOS, View, Text, TouchableHighlight, } = React; const styles = StyleSheet.create({ }); const WEBVIEWREF = 'webview'; const TopicDetailComponent = React.createClass({ propTypes: { topic: React.PropTypes.object, }, getTopicUrl() { return Configs.topicPath + this.props.topic.id; }, render() { return ( <WebView ref={WEBVIEWREF} renderError={this.renderError} renderLoading={CommonComponents.renderLoadingView} url={this.getTopicUrl()} /> ); }, }); module.exports = TopicDetailComponent
xiekw2010/Cnodejs-React-Native
0
Yet another client for https://cnodejs.org/ building on react-native
Objective-C
xiekw2010
David Tse
Alipay
iosComponents/TopicTabComponent.js
JavaScript
const React = require('react-native'); const Colors = require('../commonComponents/Colors'); const { StyleSheet, Text, } = React; const styles = StyleSheet.create({ base: { position: 'absolute', right: 10, top: 0, borderRadius: 2, width: 40, fontSize: 16, height: 18, textAlign: 'center', }, }); const TopicTabComponent = React.createClass({ propTypes: { topic: React.PropTypes.object, }, getInitialState() { return { highlight: false, }; }, componentWillMount() { this.setState({ highlight: this.props.topic.top || this.props.topic.good, }); }, getTabText() { if (this.props.topic.top) { return '置顶'; } if (this.props.topic.good) { return '精华'; } switch (this.props.topic.tab) { case 'ask': return '问答'; case 'share': return '分享'; case 'job': return '招聘'; default: } return null; }, render() { let appendStyle = {backgroundColor: Colors.backGray, color: Colors.textGray}; if (this.state.highlight) { appendStyle = {backgroundColor: Colors.green, color: '#FFFFFF'}; } const tabText = this.getTabText(); if (tabText === null) { return null; } return ( <Text style={[styles.base, appendStyle]}>{tabText}</Text> ); }, }); module.exports = TopicTabComponent;
xiekw2010/Cnodejs-React-Native
0
Yet another client for https://cnodejs.org/ building on react-native
Objective-C
xiekw2010
David Tse
Alipay
networkService/CNodeService.js
JavaScript
const _ = require('underscore'); const config = require('../config'); const {EventEmitter} = require('events'); const TOPICS_API_PATH = config.apiHost + '/topics' + '?limit=' + config.loadPerPage; const MAX_PAGE = config.loadMaxPages; class CNodeService extends EventEmitter { url(append) { let page = 1; if (append) { this.topicsCurrentPage += 1; page = this.topicsCurrentPage; } else { this.topicsCurrentPage = 1; this.topics = []; this.isReachEnd = false; } const url = TOPICS_API_PATH + '&page=' + this.topicsCurrentPage; return url; } reloadTopics(handler) { return fetch(this.url(false)) .then(response => response.json()) .then(responseData => { this.topics = responseData.data; handler(null, this.topics); }) .catch(error => handler(error, null)); } appendTopics(handler) { if (this.topicsCurrentPage >= MAX_PAGE || this.topics.length == 0) { this.isReachEnd = true; return; } return fetch(this.url(true)) .then(response => response.json()) .then(responseData => { this.topics = this.topics; this.topics.push(...responseData.data); handler(null, this.topics); }) .catch(error => handler(error, null)); } constructor() { super(); this.topics = []; this.topicsCurrentPage = 1; this.isReachEnd = false; } } module.exports = new CNodeService
xiekw2010/Cnodejs-React-Native
0
Yet another client for https://cnodejs.org/ building on react-native
Objective-C
xiekw2010
David Tse
Alipay
Example/DXPhotoBrowser/DXAppDelegate.h
C/C++ Header
// // DXAppDelegate.h // DXPhotoBrowser // // Created by kaiwei.xkw on 09/16/2015. // Copyright (c) 2015 kaiwei.xkw. All rights reserved. // @import UIKit; @interface DXAppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/DXPhotoBrowser/DXAppDelegate.m
Objective-C
// // DXAppDelegate.m // DXPhotoBrowser // // Created by kaiwei.xkw on 09/16/2015. // Copyright (c) 2015 kaiwei.xkw. All rights reserved. // #import "DXAppDelegate.h" @implementation DXAppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. return YES; } - (void)applicationWillResignActive:(UIApplication *)application { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } - (void)applicationDidEnterBackground:(UIApplication *)application { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } - (void)applicationWillEnterForeground:(UIApplication *)application { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } - (void)applicationDidBecomeActive:(UIApplication *)application { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } - (void)applicationWillTerminate:(UIApplication *)application { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/DXPhotoBrowser/DXViewController.h
C/C++ Header
// // DXViewController.h // DXPhotoBrowser // // Created by kaiwei.xkw on 09/16/2015. // Copyright (c) 2015 kaiwei.xkw. All rights reserved. // #import <Nimbus/NimbusCollections.h> @import UIKit; @interface DXViewController : UIViewController @end @interface SimplePhotoCell : UICollectionViewCell<NICollectionViewCell> @property (nonatomic, strong) UIImageView *imageView; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/DXPhotoBrowser/DXViewController.m
Objective-C
// // DXViewController.m // DXPhotoBrowser // // Created by kaiwei.xkw on 09/16/2015. // Copyright (c) 2015 kaiwei.xkw. All rights reserved. // #import "DXViewController.h" #import <DXPhotoBrowser/DXPhoto.h> #import <DXPhotoBrowser/DXPhotoBrowser.h> #import <SDWebImage/SDWebImageManager.h> #import <UIScrollView+DXRefresh.h> #import <Placeholder.h> #import <Nimbus/NimbusCollections.h> #import <SDWebImage/UIImageView+WebCache.h> #import <DXPhotoBrowser/DXPullToDetailView.h> @interface HRDemoSimplePhoto : NSObject<DXPhoto> @property (nonatomic, strong, readonly) NSString *imageURL; + (instancetype)photoWithImageURL:(NSString *)imageURL imageSize:(CGSize)imageSize; @end @implementation HRDemoSimplePhoto { UIImage *_placeholder; NSString *_imageURL; id<SDWebImageOperation> _operation; CGSize _imageSize; } + (instancetype)photoWithImageURL:(NSString *)imageURL imageSize:(CGSize)imageSize { HRDemoSimplePhoto *photo = [HRDemoSimplePhoto new]; photo->_imageURL = imageURL; photo->_imageSize = imageSize; return photo; } - (UIImage *)placeholder { return _placeholder; } - (void)loadImageWithProgressBlock:(DXPhotoProgressBlock)progressBlock completionBlock:(DXPhotoCompletionBlock)completionBlock { __weak typeof(self) wself = self; SDWebImageCompletionWithFinishedBlock finishBlock = ^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { if (!error && image) { _placeholder = image; if (completionBlock) { completionBlock(wself, image); } } }; _operation = [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:_imageURL] options:1 progress:nil completed:finishBlock]; } - (CGSize)expectImageSize { return _imageSize; } - (void)cancelLoadImage { [_operation cancel]; _operation = nil; } @end @interface DXViewController ()<DXPhotoBrowserDelegate, UICollectionViewDelegate> @property (nonatomic, strong) DXPhotoBrowser *simplePhotoBrowser; @property (nonatomic, strong) NSArray *photos; @property (nonatomic, strong) NSArray *imageSizeArray; @property (nonatomic, strong) UICollectionView *collectionView; @property (nonatomic, strong) NICollectionViewModel *model; @property (nonatomic, strong) NSMutableArray *cellObjs; @end @implementation DXViewController - (DXPhotoBrowser *)simplePhotoBrowser { _simplePhotoBrowser = [[DXPhotoBrowser alloc] initWithPhotosArray:[self.cellObjs valueForKey:@"userInfo"]]; _simplePhotoBrowser.delegate = self; return _simplePhotoBrowser; } - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath { SimplePhotoCell *cell = (SimplePhotoCell *)[collectionView cellForItemAtIndexPath:indexPath]; [self.simplePhotoBrowser showPhotoAtIndex:indexPath.item withThumbnailImageView:cell]; // [self.simplePhotoBrowser showPhotoAtIndex:indexPath.item withThumbnailImageView:nil]; } // change status bar style check -> http://stackoverflow.com/questions/19447137/changing-status-bar-style-ios-7 - (void)simplePhotoBrowserWillShow:(DXPhotoBrowser *)photoBrowser { [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO]; } - (void)simplePhotoBrowserDidHide:(DXPhotoBrowser *)photoBrowser { [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:NO]; } - (void)simplePhotoBrowserDidTriggerPullToRightEnd:(DXPhotoBrowser *)photoBrowser { NSLog(@"trigger something"); [DXPhotoBrowser new]; } - (void)viewDidLoad { [super viewDidLoad]; [self setNeedsStatusBarAppearanceUpdate]; CGFloat const inset = 3.0; CGFloat const eachLineCount = 3; UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init]; flowLayout.minimumInteritemSpacing = inset; flowLayout.minimumLineSpacing = inset; flowLayout.sectionInset = UIEdgeInsetsMake(inset, inset, inset, inset); CGFloat width = (CGRectGetWidth(self.view.bounds)-(eachLineCount+1)*inset)/eachLineCount; flowLayout.itemSize = CGSizeMake(width, width); self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowLayout]; self.collectionView.autoresizingMask = UIViewAutoresizingFlexibleDimensions; self.collectionView.backgroundColor = [UIColor whiteColor]; [self.view addSubview:self.collectionView]; self.imageSizeArray = @[ [NSValue valueWithCGSize:CGSizeMake(320.0, 200.0)], [NSValue valueWithCGSize:CGSizeMake(320.0, 200.0)], [NSValue valueWithCGSize:CGSizeMake(CGRectGetWidth(self.view.bounds), 200.0)], [NSValue valueWithCGSize:self.view.bounds.size] ]; [self.collectionView addHeaderWithTarget:self action:@selector(refresh)]; [self refresh]; } - (void)refresh { NSMutableArray *result = [NSMutableArray array]; for (NSUInteger i = 0; i < 100; i ++) { HRDemoSimplePhoto *simplePhoto = [HRDemoSimplePhoto photoWithImageURL:[Placeholder imageURL] imageSize:CGSizeZero]; NICollectionViewCellObject *obj = [[NICollectionViewCellObject alloc] initWithCellClass:[SimplePhotoCell class] userInfo:simplePhoto] ; [result addObject:obj]; } self.cellObjs = result; NICollectionViewModel *model= [[NICollectionViewModel alloc] initWithListArray:result delegate:(id)[NICollectionViewCellFactory class]]; self.model = model; self.collectionView.delegate = self; self.collectionView.dataSource = self.model; [self.collectionView headerEndRefreshing]; [self.collectionView reloadData]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end @implementation SimplePhotoCell - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { _imageView = [[UIImageView alloc] initWithFrame:self.bounds]; _imageView.autoresizingMask = UIViewAutoresizingFlexibleDimensions; _imageView.contentMode = UIViewContentModeScaleAspectFill; _imageView.clipsToBounds = YES; [self addSubview:_imageView]; } return self; } - (BOOL)shouldUpdateCellWithObject:(id)object { HRDemoSimplePhoto *item = [object userInfo]; [_imageView sd_setImageWithURL:[NSURL URLWithString:item.imageURL] placeholderImage:[Placeholder imageWithSize:CGSizeMake(100, 100)]]; return YES; } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/DXPhotoBrowser/main.m
Objective-C
// // main.m // DXPhotoBrowser // // Created by kaiwei.xkw on 09/16/2015. // Copyright (c) 2015 kaiwei.xkw. All rights reserved. // @import UIKit; #import "DXAppDelegate.h" int main(int argc, char * argv[]) { @autoreleasepool { return UIApplicationMain(argc, argv, nil, NSStringFromClass([DXAppDelegate class])); } }
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperation.h
C/C++ Header
// AFHTTPRequestOperation.h // Copyright (c) 2011–2015 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 "AFURLConnectionOperation.h" NS_ASSUME_NONNULL_BEGIN /** `AFHTTPRequestOperation` is a subclass of `AFURLConnectionOperation` for requests using the HTTP or HTTPS protocols. It encapsulates the concept of acceptable status codes and content types, which determine the success or failure of a request. */ @interface AFHTTPRequestOperation : AFURLConnectionOperation ///------------------------------------------------ /// @name Getting HTTP URL Connection Information ///------------------------------------------------ /** The last HTTP response received by the operation's connection. */ @property (readonly, nonatomic, strong, nullable) NSHTTPURLResponse *response; /** 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 AFHTTPResponse serializer, which uses the raw data as its response object. The serializer validates the status code to be in the `2XX` range, denoting success. If the response serializer generates an error in `-responseObjectForResponse:data:error:`, the `failure` callback of the session task or request operation will be executed; otherwise, the `success` callback will be executed. @warning `responseSerializer` must not be `nil`. Setting a response serializer will clear out any cached value */ @property (nonatomic, strong) AFHTTPResponseSerializer <AFURLResponseSerialization> * responseSerializer; /** An object constructed by the `responseSerializer` from the response and response data. Returns `nil` unless the operation `isFinished`, has a `response`, and has `responseData` with non-zero content length. If an error occurs during serialization, `nil` will be returned, and the `error` property will be populated with the serialization error. */ @property (readonly, nonatomic, strong, nullable) id responseObject; ///----------------------------------------------------------- /// @name Setting Completion Block Success / Failure Callbacks ///----------------------------------------------------------- /** Sets the `completionBlock` property with a block that executes either the specified success or failure block, depending on the state of the request on completion. If `error` returns a value, which can be caused by an unacceptable status code or content type, then `failure` is executed. Otherwise, `success` is executed. This method should be overridden in subclasses in order to specify the response object passed into the success block. @param success The block to be executed on the completion of a successful request. This block has no return value and takes two arguments: the receiver operation and the object constructed from the response data of the request. @param failure The block to be executed on the completion of an unsuccessful request. This block has no return value and takes two arguments: the receiver operation and the error that occurred during the request. */ - (void)setCompletionBlockWithSuccess:(nullable void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(nullable void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; @end NS_ASSUME_NONNULL_END
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperation.m
Objective-C
// AFHTTPRequestOperation.m // Copyright (c) 2011–2015 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 "AFHTTPRequestOperation.h" static dispatch_queue_t http_request_operation_processing_queue() { static dispatch_queue_t af_http_request_operation_processing_queue; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ af_http_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.http-request.processing", DISPATCH_QUEUE_CONCURRENT); }); return af_http_request_operation_processing_queue; } static dispatch_group_t http_request_operation_completion_group() { static dispatch_group_t af_http_request_operation_completion_group; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ af_http_request_operation_completion_group = dispatch_group_create(); }); return af_http_request_operation_completion_group; } #pragma mark - @interface AFURLConnectionOperation () @property (readwrite, nonatomic, strong) NSURLRequest *request; @property (readwrite, nonatomic, strong) NSURLResponse *response; @end @interface AFHTTPRequestOperation () @property (readwrite, nonatomic, strong) NSHTTPURLResponse *response; @property (readwrite, nonatomic, strong) id responseObject; @property (readwrite, nonatomic, strong) NSError *responseSerializationError; @property (readwrite, nonatomic, strong) NSRecursiveLock *lock; @end @implementation AFHTTPRequestOperation @dynamic response; @dynamic lock; - (instancetype)initWithRequest:(NSURLRequest *)urlRequest { self = [super initWithRequest:urlRequest]; if (!self) { return nil; } self.responseSerializer = [AFHTTPResponseSerializer serializer]; return self; } - (void)setResponseSerializer:(AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer { NSParameterAssert(responseSerializer); [self.lock lock]; _responseSerializer = responseSerializer; self.responseObject = nil; self.responseSerializationError = nil; [self.lock unlock]; } - (id)responseObject { [self.lock lock]; if (!_responseObject && [self isFinished] && !self.error) { NSError *error = nil; self.responseObject = [self.responseSerializer responseObjectForResponse:self.response data:self.responseData error:&error]; if (error) { self.responseSerializationError = error; } } [self.lock unlock]; return _responseObject; } - (NSError *)error { if (_responseSerializationError) { return _responseSerializationError; } else { return [super error]; } } #pragma mark - AFHTTPRequestOperation - (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure { // completionBlock is manually nilled out in AFURLConnectionOperation to break the retain cycle. #pragma clang diagnostic push #pragma clang diagnostic ignored "-Warc-retain-cycles" #pragma clang diagnostic ignored "-Wgnu" self.completionBlock = ^{ if (self.completionGroup) { dispatch_group_enter(self.completionGroup); } dispatch_async(http_request_operation_processing_queue(), ^{ if (self.error) { if (failure) { dispatch_group_async(self.completionGroup ?: http_request_operation_completion_group(), self.completionQueue ?: dispatch_get_main_queue(), ^{ failure(self, self.error); }); } } else { id responseObject = self.responseObject; if (self.error) { if (failure) { dispatch_group_async(self.completionGroup ?: http_request_operation_completion_group(), self.completionQueue ?: dispatch_get_main_queue(), ^{ failure(self, self.error); }); } } else { if (success) { dispatch_group_async(self.completionGroup ?: http_request_operation_completion_group(), self.completionQueue ?: dispatch_get_main_queue(), ^{ success(self, responseObject); }); } } } if (self.completionGroup) { dispatch_group_leave(self.completionGroup); } }); }; #pragma clang diagnostic pop } #pragma mark - AFURLRequestOperation - (void)pause { [super pause]; u_int64_t offset = 0; if ([self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey]) { offset = [(NSNumber *)[self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey] unsignedLongLongValue]; } else { offset = [(NSData *)[self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey] length]; } NSMutableURLRequest *mutableURLRequest = [self.request mutableCopy]; if ([self.response respondsToSelector:@selector(allHeaderFields)] && [[self.response allHeaderFields] valueForKey:@"ETag"]) { [mutableURLRequest setValue:[[self.response allHeaderFields] valueForKey:@"ETag"] forHTTPHeaderField:@"If-Range"]; } [mutableURLRequest setValue:[NSString stringWithFormat:@"bytes=%llu-", offset] forHTTPHeaderField:@"Range"]; self.request = mutableURLRequest; } #pragma mark - NSSecureCoding + (BOOL)supportsSecureCoding { return YES; } - (id)initWithCoder:(NSCoder *)decoder { self = [super initWithCoder:decoder]; if (!self) { return nil; } self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))]; return self; } - (void)encodeWithCoder:(NSCoder *)coder { [super encodeWithCoder:coder]; [coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))]; } #pragma mark - NSCopying - (id)copyWithZone:(NSZone *)zone { AFHTTPRequestOperation *operation = [super copyWithZone:zone]; operation.responseSerializer = [self.responseSerializer copyWithZone:zone]; operation.completionQueue = self.completionQueue; operation.completionGroup = self.completionGroup; return operation; } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperationManager.h
C/C++ Header
// AFHTTPRequestOperationManager.h // Copyright (c) 2011–2015 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 <SystemConfiguration/SystemConfiguration.h> #import <Availability.h> #if __IPHONE_OS_VERSION_MIN_REQUIRED #import <MobileCoreServices/MobileCoreServices.h> #else #import <CoreServices/CoreServices.h> #endif #import "AFHTTPRequestOperation.h" #import "AFURLResponseSerialization.h" #import "AFURLRequestSerialization.h" #import "AFSecurityPolicy.h" #import "AFNetworkReachabilityManager.h" #ifndef NS_DESIGNATED_INITIALIZER #if __has_attribute(objc_designated_initializer) #define NS_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer)) #else #define NS_DESIGNATED_INITIALIZER #endif #endif NS_ASSUME_NONNULL_BEGIN /** `AFHTTPRequestOperationManager` encapsulates the common patterns of communicating with a web application over HTTP, including request creation, response serialization, network reachability monitoring, and security, as well as request operation management. ## 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. For developers targeting iOS 6 or Mac OS X 10.8 or earlier, `AFHTTPRequestOperationManager` may be used to similar effect. ## Methods to Override To change the behavior of all request operation construction for an `AFHTTPRequestOperationManager` subclass, override `HTTPRequestOperationWithRequest:success:failure`. ## 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. ## 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. ## NSSecureCoding & NSCopying Caveats `AFHTTPRequestOperationManager` conforms to the `NSSecureCoding` and `NSCopying` protocols, allowing operations to be archived to disk, and copied in memory, respectively. There are a few minor caveats to keep in mind, however: - Archives and copies of HTTP clients will be initialized with an empty operation queue. - NSSecureCoding cannot serialize / deserialize block properties, so an archive of an HTTP client will not include any reachability callback block that may be set. */ @interface AFHTTPRequestOperationManager : NSObject <NSSecureCoding, NSCopying> /** The URL used to monitor reachability, and 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 a JSON serializer, which serializes data from responses with a `application/json` MIME type, and falls back to the raw data object. The serializer validates the status code to be in the `2XX` range, denoting success. If the response serializer generates an error in `-responseObjectForResponse:data:error:`, the `failure` callback of the session task or request operation will be executed; otherwise, the `success` callback will be executed. @warning `responseSerializer` must not be `nil`. */ @property (nonatomic, strong) AFHTTPResponseSerializer <AFURLResponseSerialization> * responseSerializer; /** The operation queue on which request operations are scheduled and run. */ @property (nonatomic, strong) NSOperationQueue *operationQueue; ///------------------------------- /// @name Managing URL Credentials ///------------------------------- /** Whether request operations should consult the credential storage for authenticating the connection. `YES` by default. @see AFURLConnectionOperation -shouldUseCredentialStorage */ @property (nonatomic, assign) BOOL shouldUseCredentialStorage; /** The credential used by request operations for authentication challenges. @see AFURLConnectionOperation -credential */ @property (nonatomic, strong, nullable) NSURLCredential *credential; ///------------------------------- /// @name Managing Security Policy ///------------------------------- /** The security policy used by created request operations to evaluate server trust for secure connections. `AFHTTPRequestOperationManager` uses the `defaultPolicy` unless otherwise specified. */ @property (nonatomic, strong) AFSecurityPolicy *securityPolicy; ///------------------------------------ /// @name Managing Network Reachability ///------------------------------------ /** The network reachability manager. `AFHTTPRequestOperationManager` uses the `sharedManager` by default. */ @property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager; ///------------------------------- /// @name Managing Callback Queues ///------------------------------- /** The dispatch queue for the `completionBlock` of request operations. If `NULL` (default), the main queue is used. */ #if OS_OBJECT_HAVE_OBJC_SUPPORT @property (nonatomic, strong, nullable) dispatch_queue_t completionQueue; #else @property (nonatomic, assign, nullable) dispatch_queue_t completionQueue; #endif /** The dispatch group for the `completionBlock` of request operations. If `NULL` (default), a private dispatch group is used. */ #if OS_OBJECT_HAVE_OBJC_SUPPORT @property (nonatomic, strong, nullable) dispatch_group_t completionGroup; #else @property (nonatomic, assign, nullable) dispatch_group_t completionGroup; #endif ///--------------------------------------------- /// @name Creating and Initializing HTTP Clients ///--------------------------------------------- /** Creates and returns an `AFHTTPRequestOperationManager` object. */ + (instancetype)manager; /** Initializes an `AFHTTPRequestOperationManager` object with the specified base URL. This is the designated initializer. @param url The base URL for the HTTP client. @return The newly-initialized HTTP client */ - (instancetype)initWithBaseURL:(nullable NSURL *)url NS_DESIGNATED_INITIALIZER; ///--------------------------------------- /// @name Managing HTTP Request Operations ///--------------------------------------- /** Creates an `AFHTTPRequestOperation`, and sets the response serializers to that of the HTTP client. @param request The request object to be loaded asynchronously during execution of the operation. @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request. @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments:, the created request operation and the `NSError` object describing the network or parsing error that occurred. */ - (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)request success:(nullable void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(nullable void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; ///--------------------------- /// @name Making HTTP Requests ///--------------------------- /** Creates and runs an `AFHTTPRequestOperation` 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 success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer. @param failure A block object to be executed when the request operation 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 request operation and the error describing the network or parsing error that occurred. @see -HTTPRequestOperationWithRequest:success:failure: */ - (nullable AFHTTPRequestOperation *)GET:(NSString *)URLString parameters:(nullable id)parameters success:(nullable void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(nullable void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; /** Creates and runs an `AFHTTPRequestOperation` 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 success A block object to be executed when the request operation finishes successfully. This block has no return value and takes a single arguments: the request operation. @param failure A block object to be executed when the request operation 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 request operation and the error describing the network or parsing error that occurred. @see -HTTPRequestOperationWithRequest:success:failure: */ - (nullable AFHTTPRequestOperation *)HEAD:(NSString *)URLString parameters:(nullable id)parameters success:(nullable void (^)(AFHTTPRequestOperation *operation))success failure:(nullable void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; /** Creates and runs an `AFHTTPRequestOperation` 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 success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer. @param failure A block object to be executed when the request operation 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 request operation and the error describing the network or parsing error that occurred. @see -HTTPRequestOperationWithRequest:success:failure: */ - (nullable AFHTTPRequestOperation *)POST:(NSString *)URLString parameters:(nullable id)parameters success:(nullable void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(nullable void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; /** Creates and runs an `AFHTTPRequestOperation` 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 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 success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer. @param failure A block object to be executed when the request operation 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 request operation and the error describing the network or parsing error that occurred. @see -HTTPRequestOperationWithRequest:success:failure: */ - (nullable AFHTTPRequestOperation *)POST:(NSString *)URLString parameters:(nullable id)parameters constructingBodyWithBlock:(nullable void (^)(id <AFMultipartFormData> formData))block success:(nullable void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(nullable void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; /** Creates and runs an `AFHTTPRequestOperation` 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 success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer. @param failure A block object to be executed when the request operation 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 request operation and the error describing the network or parsing error that occurred. @see -HTTPRequestOperationWithRequest:success:failure: */ - (nullable AFHTTPRequestOperation *)PUT:(NSString *)URLString parameters:(nullable id)parameters success:(nullable void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(nullable void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; /** Creates and runs an `AFHTTPRequestOperation` 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 success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer. @param failure A block object to be executed when the request operation 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 request operation and the error describing the network or parsing error that occurred. @see -HTTPRequestOperationWithRequest:success:failure: */ - (nullable AFHTTPRequestOperation *)PATCH:(NSString *)URLString parameters:(nullable id)parameters success:(nullable void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(nullable void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; /** Creates and runs an `AFHTTPRequestOperation` 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 success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer. @param failure A block object to be executed when the request operation 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 request operation and the error describing the network or parsing error that occurred. @see -HTTPRequestOperationWithRequest:success:failure: */ - (nullable AFHTTPRequestOperation *)DELETE:(NSString *)URLString parameters:(nullable id)parameters success:(nullable void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(nullable void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; @end NS_ASSUME_NONNULL_END
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperationManager.m
Objective-C
// AFHTTPRequestOperationManager.m // Copyright (c) 2011–2015 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 "AFHTTPRequestOperationManager.h" #import "AFHTTPRequestOperation.h" #import <Availability.h> #import <Security/Security.h> #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #import <UIKit/UIKit.h> #endif @interface AFHTTPRequestOperationManager () @property (readwrite, nonatomic, strong) NSURL *baseURL; @end @implementation AFHTTPRequestOperationManager + (instancetype)manager { return [[self alloc] initWithBaseURL:nil]; } - (instancetype)init { return [self initWithBaseURL:nil]; } - (instancetype)initWithBaseURL:(NSURL *)url { self = [super init]; 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]; self.securityPolicy = [AFSecurityPolicy defaultPolicy]; self.reachabilityManager = [AFNetworkReachabilityManager sharedManager]; self.operationQueue = [[NSOperationQueue alloc] init]; self.shouldUseCredentialStorage = YES; return self; } #pragma mark - #ifdef _SYSTEMCONFIGURATION_H #endif - (void)setRequestSerializer:(AFHTTPRequestSerializer <AFURLRequestSerialization> *)requestSerializer { NSParameterAssert(requestSerializer); _requestSerializer = requestSerializer; } - (void)setResponseSerializer:(AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer { NSParameterAssert(responseSerializer); _responseSerializer = responseSerializer; } #pragma mark - - (AFHTTPRequestOperation *)HTTPRequestOperationWithHTTPMethod:(NSString *)method URLString:(NSString *)URLString parameters:(id)parameters success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure { NSError *serializationError = nil; NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError]; if (serializationError) { if (failure) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wgnu" dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{ failure(nil, serializationError); }); #pragma clang diagnostic pop } return nil; } return [self HTTPRequestOperationWithRequest:request success:success failure:failure]; } - (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)request success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure { AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; operation.responseSerializer = self.responseSerializer; operation.shouldUseCredentialStorage = self.shouldUseCredentialStorage; operation.credential = self.credential; operation.securityPolicy = self.securityPolicy; [operation setCompletionBlockWithSuccess:success failure:failure]; operation.completionQueue = self.completionQueue; operation.completionGroup = self.completionGroup; return operation; } #pragma mark - - (AFHTTPRequestOperation *)GET:(NSString *)URLString parameters:(id)parameters success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure { AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithHTTPMethod:@"GET" URLString:URLString parameters:parameters success:success failure:failure]; [self.operationQueue addOperation:operation]; return operation; } - (AFHTTPRequestOperation *)HEAD:(NSString *)URLString parameters:(id)parameters success:(void (^)(AFHTTPRequestOperation *operation))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure { AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithHTTPMethod:@"HEAD" URLString:URLString parameters:parameters success:^(AFHTTPRequestOperation *requestOperation, __unused id responseObject) { if (success) { success(requestOperation); } } failure:failure]; [self.operationQueue addOperation:operation]; return operation; } - (AFHTTPRequestOperation *)POST:(NSString *)URLString parameters:(id)parameters success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure { AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithHTTPMethod:@"POST" URLString:URLString parameters:parameters success:success failure:failure]; [self.operationQueue addOperation:operation]; return operation; } - (AFHTTPRequestOperation *)POST:(NSString *)URLString parameters:(id)parameters constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure { NSError *serializationError = nil; NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError]; if (serializationError) { if (failure) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wgnu" dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{ failure(nil, serializationError); }); #pragma clang diagnostic pop } return nil; } AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure]; [self.operationQueue addOperation:operation]; return operation; } - (AFHTTPRequestOperation *)PUT:(NSString *)URLString parameters:(id)parameters success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure { AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithHTTPMethod:@"PUT" URLString:URLString parameters:parameters success:success failure:failure]; [self.operationQueue addOperation:operation]; return operation; } - (AFHTTPRequestOperation *)PATCH:(NSString *)URLString parameters:(id)parameters success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure { AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithHTTPMethod:@"PATCH" URLString:URLString parameters:parameters success:success failure:failure]; [self.operationQueue addOperation:operation]; return operation; } - (AFHTTPRequestOperation *)DELETE:(NSString *)URLString parameters:(id)parameters success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure { AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithHTTPMethod:@"DELETE" URLString:URLString parameters:parameters success:success failure:failure]; [self.operationQueue addOperation:operation]; return operation; } #pragma mark - NSObject - (NSString *)description { return [NSString stringWithFormat:@"<%@: %p, baseURL: %@, operationQueue: %@>", NSStringFromClass([self class]), self, [self.baseURL absoluteString], self.operationQueue]; } #pragma mark - NSSecureCoding + (BOOL)supportsSecureCoding { return YES; } - (id)initWithCoder:(NSCoder *)decoder { NSURL *baseURL = [decoder decodeObjectForKey:NSStringFromSelector(@selector(baseURL))]; self = [self initWithBaseURL:baseURL]; if (!self) { return nil; } self.requestSerializer = [decoder decodeObjectOfClass:[AFHTTPRequestSerializer class] forKey:NSStringFromSelector(@selector(requestSerializer))]; self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))]; return self; } - (void)encodeWithCoder:(NSCoder *)coder { [coder encodeObject:self.baseURL forKey:NSStringFromSelector(@selector(baseURL))]; [coder encodeObject:self.requestSerializer forKey:NSStringFromSelector(@selector(requestSerializer))]; [coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))]; } #pragma mark - NSCopying - (id)copyWithZone:(NSZone *)zone { AFHTTPRequestOperationManager *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL]; HTTPClient.requestSerializer = [self.requestSerializer copyWithZone:zone]; HTTPClient.responseSerializer = [self.responseSerializer copyWithZone:zone]; return HTTPClient; } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.h
C/C++ Header
// AFHTTPSessionManager.h // Copyright (c) 2011–2015 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 <Availability.h> #if __IPHONE_OS_VERSION_MIN_REQUIRED #import <MobileCoreServices/MobileCoreServices.h> #else #import <CoreServices/CoreServices.h> #endif #import "AFURLSessionManager.h" #ifndef NS_DESIGNATED_INITIALIZER #if __has_attribute(objc_designated_initializer) #define NS_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer)) #else #define NS_DESIGNATED_INITIALIZER #endif #endif /** `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. For developers targeting iOS 6 or Mac OS X 10.8 or earlier, `AFHTTPRequestOperationManager` may be used to similar effect. ## 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: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. */ #if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) || TARGET_OS_WATCH 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 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 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 *)GET:(NSString *)URLString parameters:(nullable id)parameters success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success failure:(nullable void (^)(NSURLSessionDataTask *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 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 success:(nullable void (^)(NSURLSessionDataTask *task))success failure:(nullable void (^)(NSURLSessionDataTask *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 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 *)POST:(NSString *)URLString parameters:(nullable id)parameters success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success failure:(nullable void (^)(NSURLSessionDataTask *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 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 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 *)POST:(NSString *)URLString parameters:(nullable id)parameters constructingBodyWithBlock:(nullable void (^)(id <AFMultipartFormData> formData))block success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success failure:(nullable void (^)(NSURLSessionDataTask *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 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 success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success failure:(nullable void (^)(NSURLSessionDataTask *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 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 success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success failure:(nullable void (^)(NSURLSessionDataTask *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 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 success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success failure:(nullable void (^)(NSURLSessionDataTask *task, NSError *error))failure; @end NS_ASSUME_NONNULL_END #endif
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.m
Objective-C
// AFHTTPSessionManager.m // Copyright (c) 2011–2015 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" #if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) || TARGET_WATCH_OS #import "AFURLRequestSerialization.h" #import "AFURLResponseSerialization.h" #import <Availability.h> #import <Security/Security.h> #ifdef _SYSTEMCONFIGURATION_H #import <netinet/in.h> #import <netinet6/in6.h> #import <arpa/inet.h> #import <ifaddrs.h> #import <netdb.h> #endif #if TARGET_OS_IOS #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 - #ifdef _SYSTEMCONFIGURATION_H #endif - (void)setRequestSerializer:(AFHTTPRequestSerializer <AFURLRequestSerialization> *)requestSerializer { NSParameterAssert(requestSerializer); _requestSerializer = requestSerializer; } - (void)setResponseSerializer:(AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer { NSParameterAssert(responseSerializer); [super setResponseSerializer:responseSerializer]; } #pragma mark - - (NSURLSessionDataTask *)GET:(NSString *)URLString parameters:(id)parameters success:(void (^)(NSURLSessionDataTask *task, id responseObject))success failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure { NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"GET" URLString:URLString parameters:parameters success:success failure:failure]; [dataTask resume]; return dataTask; } - (NSURLSessionDataTask *)HEAD:(NSString *)URLString parameters:(id)parameters success:(void (^)(NSURLSessionDataTask *task))success failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure { NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"HEAD" URLString:URLString parameters:parameters success:^(NSURLSessionDataTask *task, __unused id responseObject) { if (success) { success(task); } } failure:failure]; [dataTask resume]; return dataTask; } - (NSURLSessionDataTask *)POST:(NSString *)URLString parameters:(id)parameters success:(void (^)(NSURLSessionDataTask *task, id responseObject))success failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure { NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"POST" URLString:URLString parameters:parameters success:success failure:failure]; [dataTask resume]; return dataTask; } - (NSURLSessionDataTask *)POST:(NSString *)URLString parameters:(id)parameters constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block success:(void (^)(NSURLSessionDataTask *task, id responseObject))success failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure { NSError *serializationError = nil; NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError]; if (serializationError) { if (failure) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wgnu" dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{ failure(nil, serializationError); }); #pragma clang diagnostic pop } return nil; } __block NSURLSessionDataTask *task = [self uploadTaskWithStreamedRequest:request progress:nil 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:(id)parameters success:(void (^)(NSURLSessionDataTask *task, id responseObject))success failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure { NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PUT" URLString:URLString parameters:parameters success:success failure:failure]; [dataTask resume]; return dataTask; } - (NSURLSessionDataTask *)PATCH:(NSString *)URLString parameters:(id)parameters success:(void (^)(NSURLSessionDataTask *task, id responseObject))success failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure { NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PATCH" URLString:URLString parameters:parameters success:success failure:failure]; [dataTask resume]; return dataTask; } - (NSURLSessionDataTask *)DELETE:(NSString *)URLString parameters:(id)parameters success:(void (^)(NSURLSessionDataTask *task, id responseObject))success failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure { NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"DELETE" URLString:URLString parameters:parameters success:success failure:failure]; [dataTask resume]; return dataTask; } - (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method URLString:(NSString *)URLString parameters:(id)parameters success:(void (^)(NSURLSessionDataTask *, id))success failure:(void (^)(NSURLSessionDataTask *, NSError *))failure { NSError *serializationError = nil; NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError]; if (serializationError) { if (failure) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wgnu" dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{ failure(nil, serializationError); }); #pragma clang diagnostic pop } return nil; } __block NSURLSessionDataTask *dataTask = nil; dataTask = [self dataTaskWithRequest:request 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; } - (id)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) { #if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1100) configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:configurationIdentifier]; #else configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:configurationIdentifier]; #endif } } 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))]; 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))]; } #pragma mark - NSCopying - (id)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]; return HTTPClient; } @end #endif
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.h
C/C++ Header
// AFNetworkReachabilityManager.h // Copyright (c) 2011–2015 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> #ifndef NS_DESIGNATED_INITIALIZER #if __has_attribute(objc_designated_initializer) #define NS_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer)) #else #define NS_DESIGNATED_INITIALIZER #endif #endif 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 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_in`) 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; ///-------------------------------------------------- /// @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`). */ extern NSString * const AFNetworkingReachabilityDidChangeNotification; extern NSString * const AFNetworkingReachabilityNotificationStatusItem; ///-------------------- /// @name Functions ///-------------------- /** Returns a localized string representation of an `AFNetworkReachabilityStatus` value. */ extern NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status); NS_ASSUME_NONNULL_END #endif
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.m
Objective-C
// AFNetworkReachabilityManager.m // Copyright (c) 2011–2015 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 NS_ENUM(NSUInteger, AFNetworkReachabilityAssociation) { AFNetworkReachabilityForAddress = 1, AFNetworkReachabilityForAddressPair = 2, AFNetworkReachabilityForName = 3, }; 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; } static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkReachabilityFlags flags, void *info) { AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags); AFNetworkReachabilityStatusBlock block = (__bridge AFNetworkReachabilityStatusBlock)info; if (block) { block(status); } dispatch_async(dispatch_get_main_queue(), ^{ NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; NSDictionary *userInfo = @{ AFNetworkingReachabilityNotificationStatusItem: @(status) }; [notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:userInfo]; }); } 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 (readwrite, nonatomic, strong) id networkReachability; @property (readwrite, nonatomic, assign) AFNetworkReachabilityAssociation networkReachabilityAssociation; @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, ^{ struct sockaddr_in address; bzero(&address, sizeof(address)); address.sin_len = sizeof(address); address.sin_family = AF_INET; _sharedManager = [self managerForAddress:&address]; }); return _sharedManager; } + (instancetype)managerForDomain:(NSString *)domain { SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [domain UTF8String]); AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability]; manager.networkReachabilityAssociation = AFNetworkReachabilityForName; return manager; } + (instancetype)managerForAddress:(const void *)address { SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)address); AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability]; manager.networkReachabilityAssociation = AFNetworkReachabilityForAddress; return manager; } - (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability { self = [super init]; if (!self) { return nil; } self.networkReachability = CFBridgingRelease(reachability); self.networkReachabilityStatus = AFNetworkReachabilityStatusUnknown; return self; } - (instancetype)init NS_UNAVAILABLE { return nil; } - (void)dealloc { [self stopMonitoring]; } #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; AFNetworkReachabilityStatusBlock callback = ^(AFNetworkReachabilityStatus status) { __strong __typeof(weakSelf)strongSelf = weakSelf; strongSelf.networkReachabilityStatus = status; if (strongSelf.networkReachabilityStatusBlock) { strongSelf.networkReachabilityStatusBlock(status); } }; id networkReachability = self.networkReachability; SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL}; SCNetworkReachabilitySetCallback((__bridge SCNetworkReachabilityRef)networkReachability, AFNetworkReachabilityCallback, &context); SCNetworkReachabilityScheduleWithRunLoop((__bridge SCNetworkReachabilityRef)networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes); switch (self.networkReachabilityAssociation) { case AFNetworkReachabilityForName: break; case AFNetworkReachabilityForAddress: case AFNetworkReachabilityForAddressPair: default: { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),^{ SCNetworkReachabilityFlags flags; SCNetworkReachabilityGetFlags((__bridge SCNetworkReachabilityRef)networkReachability, &flags); AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags); dispatch_async(dispatch_get_main_queue(), ^{ callback(status); NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; [notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:@{ AFNetworkingReachabilityNotificationStatusItem: @(status) }]; }); }); } break; } } - (void)stopMonitoring { if (!self.networkReachability) { return; } SCNetworkReachabilityUnscheduleFromRunLoop((__bridge SCNetworkReachabilityRef)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
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/AFNetworking/AFNetworking/AFNetworking.h
C/C++ Header
// 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> #ifndef _AFNETWORKING_ #define _AFNETWORKING_ #import "AFURLRequestSerialization.h" #import "AFURLResponseSerialization.h" #import "AFSecurityPolicy.h" #if !TARGET_OS_WATCH #import "AFNetworkReachabilityManager.h" #import "AFURLConnectionOperation.h" #import "AFHTTPRequestOperation.h" #import "AFHTTPRequestOperationManager.h" #endif #if ( ( defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) || \ ( defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000 ) || \ TARGET_OS_WATCH ) #import "AFURLSessionManager.h" #import "AFHTTPSessionManager.h" #endif #endif /* _AFNETWORKING_ */
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/AFNetworking/AFNetworking/AFSecurityPolicy.h
C/C++ Header
// AFSecurityPolicy.h // Copyright (c) 2011–2015 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 /** 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. By default, this property is set to any (`.cer`) certificates included in the app bundle. Note that if you create an array with duplicate certificates, the duplicate certificates will be removed. Note that if pinning is enabled, `evaluateServerTrust:forDomain:` will return true if any pinned certificate matches. */ @property (nonatomic, strong, nullable) NSArray *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 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. @param pinningMode The SSL pinning mode. @return A new security policy. */ + (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode; ///------------------------------ /// @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. @return Whether or not to trust the server. @warning This method has been deprecated in favor of `-evaluateServerTrust:forDomain:`. */ - (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust DEPRECATED_ATTRIBUTE; /** 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. */
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/AFNetworking/AFNetworking/AFSecurityPolicy.m
Objective-C
// AFSecurityPolicy.m // Copyright (c) 2011–2015 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 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 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; SecCertificateRef allowedCertificates[1]; CFArrayRef tempCertificates = nil; SecPolicyRef policy = nil; SecTrustRef allowedTrust = nil; SecTrustResultType result; allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificate); __Require_Quiet(allowedCertificate != NULL, _out); allowedCertificates[0] = allowedCertificate; tempCertificates = CFArrayCreate(NULL, (const void **)allowedCertificates, 1, NULL); policy = SecPolicyCreateBasicX509(); __Require_noErr_Quiet(SecTrustCreateWithCertificates(tempCertificates, policy, &allowedTrust), _out); __Require_noErr_Quiet(SecTrustEvaluate(allowedTrust, &result), _out); allowedPublicKey = (__bridge_transfer id)SecTrustCopyPublicKey(allowedTrust); _out: if (allowedTrust) { CFRelease(allowedTrust); } if (policy) { CFRelease(policy); } if (tempCertificates) { CFRelease(tempCertificates); } if (allowedCertificate) { CFRelease(allowedCertificate); } return allowedPublicKey; } static BOOL AFServerTrustIsValid(SecTrustRef serverTrust) { BOOL isValid = NO; SecTrustResultType result; __Require_noErr_Quiet(SecTrustEvaluate(serverTrust, &result), _out); 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; __Require_noErr_Quiet(SecTrustEvaluate(trust, &result), _out); [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) NSArray *pinnedPublicKeys; @end @implementation AFSecurityPolicy + (NSArray *)defaultPinnedCertificates { static NSArray *_defaultPinnedCertificates = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ NSBundle *bundle = [NSBundle bundleForClass:[self class]]; NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."]; NSMutableArray *certificates = [NSMutableArray arrayWithCapacity:[paths count]]; for (NSString *path in paths) { NSData *certificateData = [NSData dataWithContentsOfFile:path]; [certificates addObject:certificateData]; } _defaultPinnedCertificates = [[NSArray alloc] initWithArray:certificates]; }); return _defaultPinnedCertificates; } + (instancetype)defaultPolicy { AFSecurityPolicy *securityPolicy = [[self alloc] init]; securityPolicy.SSLPinningMode = AFSSLPinningModeNone; return securityPolicy; } + (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode { AFSecurityPolicy *securityPolicy = [[self alloc] init]; securityPolicy.SSLPinningMode = pinningMode; [securityPolicy setPinnedCertificates:[self defaultPinnedCertificates]]; return securityPolicy; } - (id)init { self = [super init]; if (!self) { return nil; } self.validatesDomainName = YES; return self; } - (void)setPinnedCertificates:(NSArray *)pinnedCertificates { _pinnedCertificates = [[NSOrderedSet orderedSetWithArray:pinnedCertificates] array]; if (self.pinnedCertificates) { NSMutableArray *mutablePinnedPublicKeys = [NSMutableArray arrayWithCapacity:[self.pinnedCertificates count]]; for (NSData *certificate in self.pinnedCertificates) { id publicKey = AFPublicKeyForCertificate(certificate); if (!publicKey) { continue; } [mutablePinnedPublicKeys addObject:publicKey]; } self.pinnedPublicKeys = [NSArray arrayWithArray:mutablePinnedPublicKeys]; } else { self.pinnedPublicKeys = nil; } } #pragma mark - - (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust { return [self evaluateServerTrust:serverTrust forDomain:nil]; } - (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) { if (self.allowInvalidCertificates || AFServerTrustIsValid(serverTrust)){ return YES; } else { return NO; } } else if (!AFServerTrustIsValid(serverTrust) && !self.allowInvalidCertificates) { return NO; } NSArray *serverCertificates = AFCertificateTrustChainForServerTrust(serverTrust); switch (self.SSLPinningMode) { case AFSSLPinningModeNone: default: return NO; 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; } NSUInteger trustedCertificateCount = 0; for (NSData *trustChainCertificate in serverCertificates) { if ([self.pinnedCertificates containsObject:trustChainCertificate]) { trustedCertificateCount++; } } return trustedCertificateCount > 0; } 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; } } return NO; } #pragma mark - NSKeyValueObserving + (NSSet *)keyPathsForValuesAffectingPinnedPublicKeys { return [NSSet setWithObject:@"pinnedCertificates"]; } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/AFNetworking/AFNetworking/AFURLConnectionOperation.h
C/C++ Header
// AFURLConnectionOperation.h // Copyright (c) 2011–2015 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 <Availability.h> #import "AFURLRequestSerialization.h" #import "AFURLResponseSerialization.h" #import "AFSecurityPolicy.h" #ifndef NS_DESIGNATED_INITIALIZER #if __has_attribute(objc_designated_initializer) #define NS_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer)) #else #define NS_DESIGNATED_INITIALIZER #endif #endif /** `AFURLConnectionOperation` is a subclass of `NSOperation` that implements `NSURLConnection` delegate methods. ## Subclassing Notes This is the base class of all network request operations. You may wish to create your own subclass in order to implement additional `NSURLConnection` delegate methods (see "`NSURLConnection` Delegate Methods" below), or to provide additional properties and/or class constructors. If you are creating a subclass that communicates over the HTTP or HTTPS protocols, you may want to consider subclassing `AFHTTPRequestOperation` instead, as it supports specifying acceptable content types or status codes. ## NSURLConnection Delegate Methods `AFURLConnectionOperation` implements the following `NSURLConnection` delegate methods: - `connection:didReceiveResponse:` - `connection:didReceiveData:` - `connectionDidFinishLoading:` - `connection:didFailWithError:` - `connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:` - `connection:willCacheResponse:` - `connectionShouldUseCredentialStorage:` - `connection:needNewBodyStream:` - `connection:willSendRequestForAuthenticationChallenge:` If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first. ## Callbacks and Completion Blocks The built-in `completionBlock` provided by `NSOperation` allows for custom behavior to be executed after the request finishes. It is a common pattern for class constructors in subclasses to take callback block parameters, and execute them conditionally in the body of its `completionBlock`. Make sure to handle cancelled operations appropriately when setting a `completionBlock` (i.e. returning early before parsing response data). See the implementation of any of the `AFHTTPRequestOperation` subclasses for an example of this. Subclasses are strongly discouraged from overriding `setCompletionBlock:`, as `AFURLConnectionOperation`'s implementation includes a workaround to mitigate retain cycles, and what Apple rather ominously refers to as ["The Deallocation Problem"](http://developer.apple.com/library/ios/#technotes/tn2109/). ## SSL Pinning Relying on the CA trust model to validate SSL certificates exposes your app to security vulnerabilities, such as man-in-the-middle attacks. For applications that connect to known servers, SSL certificate pinning provides an increased level of security, by checking server certificate validity against those specified in the app bundle. SSL with certificate pinning is strongly recommended for any application that transmits sensitive information to an external webservice. Connections will be validated on all matching certificates with a `.cer` extension in the bundle root. ## NSCoding & NSCopying Conformance `AFURLConnectionOperation` conforms to the `NSCoding` and `NSCopying` protocols, allowing operations to be archived to disk, and copied in memory, respectively. However, because of the intrinsic limitations of capturing the exact state of an operation at a particular moment, there are some important caveats to keep in mind: ### NSCoding Caveats - Encoded operations do not include any block or stream properties. Be sure to set `completionBlock`, `outputStream`, and any callback blocks as necessary when using `-initWithCoder:` or `NSKeyedUnarchiver`. - Operations are paused on `encodeWithCoder:`. If the operation was encoded while paused or still executing, its archived state will return `YES` for `isReady`. Otherwise, the state of an operation when encoding will remain unchanged. ### NSCopying Caveats - `-copy` and `-copyWithZone:` return a new operation with the `NSURLRequest` of the original. So rather than an exact copy of the operation at that particular instant, the copying mechanism returns a completely new instance, which can be useful for retrying operations. - A copy of an operation will not include the `outputStream` of the original. - Operation copies do not include `completionBlock`, as it often strongly captures a reference to `self`, which would otherwise have the unintuitive side-effect of pointing to the _original_ operation when copied. */ NS_ASSUME_NONNULL_BEGIN @interface AFURLConnectionOperation : NSOperation <NSURLConnectionDelegate, NSURLConnectionDataDelegate, NSSecureCoding, NSCopying> ///------------------------------- /// @name Accessing Run Loop Modes ///------------------------------- /** The run loop modes in which the operation will run on the network thread. By default, this is a single-member set containing `NSRunLoopCommonModes`. */ @property (nonatomic, strong) NSSet *runLoopModes; ///----------------------------------------- /// @name Getting URL Connection Information ///----------------------------------------- /** The request used by the operation's connection. */ @property (readonly, nonatomic, strong) NSURLRequest *request; /** The last response received by the operation's connection. */ @property (readonly, nonatomic, strong, nullable) NSURLResponse *response; /** The error, if any, that occurred in the lifecycle of the request. */ @property (readonly, nonatomic, strong, nullable) NSError *error; ///---------------------------- /// @name Getting Response Data ///---------------------------- /** The data received during the request. */ @property (readonly, nonatomic, strong, nullable) NSData *responseData; /** The string representation of the response data. */ @property (readonly, nonatomic, copy, nullable) NSString *responseString; /** The string encoding of the response. If the response does not specify a valid string encoding, `responseStringEncoding` will return `NSUTF8StringEncoding`. */ @property (readonly, nonatomic, assign) NSStringEncoding responseStringEncoding; ///------------------------------- /// @name Managing URL Credentials ///------------------------------- /** Whether the URL connection should consult the credential storage for authenticating the connection. `YES` by default. This is the value that is returned in the `NSURLConnectionDelegate` method `-connectionShouldUseCredentialStorage:`. */ @property (nonatomic, assign) BOOL shouldUseCredentialStorage; /** The credential used for authentication challenges in `-connection:didReceiveAuthenticationChallenge:`. This will be overridden by any shared credentials that exist for the username or password of the request URL, if present. */ @property (nonatomic, strong, nullable) NSURLCredential *credential; ///------------------------------- /// @name Managing Security Policy ///------------------------------- /** The security policy used to evaluate server trust for secure connections. */ @property (nonatomic, strong) AFSecurityPolicy *securityPolicy; ///------------------------ /// @name Accessing Streams ///------------------------ /** The input stream used to read data to be sent during the request. This property acts as a proxy to the `HTTPBodyStream` property of `request`. */ @property (nonatomic, strong) NSInputStream *inputStream; /** The output stream that is used to write data received until the request is finished. By default, data is accumulated into a buffer that is stored into `responseData` upon completion of the request, with the intermediary `outputStream` property set to `nil`. When `outputStream` is set, the data will not be accumulated into an internal buffer, and as a result, the `responseData` property of the completed request will be `nil`. The output stream will be scheduled in the network thread runloop upon being set. */ @property (nonatomic, strong, nullable) NSOutputStream *outputStream; ///--------------------------------- /// @name Managing Callback Queues ///--------------------------------- /** The dispatch queue for `completionBlock`. If `NULL` (default), the main queue is used. */ #if OS_OBJECT_HAVE_OBJC_SUPPORT @property (nonatomic, strong, nullable) dispatch_queue_t completionQueue; #else @property (nonatomic, assign, nullable) dispatch_queue_t completionQueue; #endif /** The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used. */ #if OS_OBJECT_HAVE_OBJC_SUPPORT @property (nonatomic, strong, nullable) dispatch_group_t completionGroup; #else @property (nonatomic, assign, nullable) dispatch_group_t completionGroup; #endif ///--------------------------------------------- /// @name Managing Request Operation Information ///--------------------------------------------- /** The user info dictionary for the receiver. */ @property (nonatomic, strong) NSDictionary *userInfo; // FIXME: It doesn't seem that this userInfo is used anywhere in the implementation. ///------------------------------------------------------ /// @name Initializing an AFURLConnectionOperation Object ///------------------------------------------------------ /** Initializes and returns a newly allocated operation object with a url connection configured with the specified url request. This is the designated initializer. @param urlRequest The request object to be used by the operation connection. */ - (instancetype)initWithRequest:(NSURLRequest *)urlRequest NS_DESIGNATED_INITIALIZER; ///---------------------------------- /// @name Pausing / Resuming Requests ///---------------------------------- /** Pauses the execution of the request operation. A paused operation returns `NO` for `-isReady`, `-isExecuting`, and `-isFinished`. As such, it will remain in an `NSOperationQueue` until it is either cancelled or resumed. Pausing a finished, cancelled, or paused operation has no effect. */ - (void)pause; /** Whether the request operation is currently paused. @return `YES` if the operation is currently paused, otherwise `NO`. */ - (BOOL)isPaused; /** Resumes the execution of the paused request operation. Pause/Resume behavior varies depending on the underlying implementation for the operation class. In its base implementation, resuming a paused requests restarts the original request. However, since HTTP defines a specification for how to request a specific content range, `AFHTTPRequestOperation` will resume downloading the request from where it left off, instead of restarting the original request. */ - (void)resume; ///---------------------------------------------- /// @name Configuring Backgrounding Task Behavior ///---------------------------------------------- /** Specifies that the operation should continue execution after the app has entered the background, and the expiration handler for that background task. @param handler A handler to be called shortly before the application’s remaining background time reaches 0. The handler is wrapped in a block that cancels the operation, and cleans up and marks the end of execution, unlike the `handler` parameter in `UIApplication -beginBackgroundTaskWithExpirationHandler:`, which expects this to be done in the handler itself. The handler is called synchronously on the main thread, thus blocking the application’s suspension momentarily while the application is notified. */ #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) - (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(nullable void (^)(void))handler NS_EXTENSION_UNAVAILABLE_IOS("Not available in app extensions."); #endif ///--------------------------------- /// @name Setting Progress Callbacks ///--------------------------------- /** Sets a callback to be called when an undetermined number of bytes have been uploaded to the server. @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 three arguments: 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)setUploadProgressBlock:(nullable void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block; /** Sets a callback to be called when an undetermined number of bytes have been downloaded from the server. @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 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 main thread. */ - (void)setDownloadProgressBlock:(nullable void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))block; ///------------------------------------------------- /// @name Setting NSURLConnection Delegate Callbacks ///------------------------------------------------- /** Sets a block to be executed when the connection will authenticate a challenge in order to download its request, as handled by the `NSURLConnectionDelegate` method `connection:willSendRequestForAuthenticationChallenge:`. @param block A block object to be executed when the connection will authenticate a challenge in order to download its request. The block has no return type and takes two arguments: the URL connection object, and the challenge that must be authenticated. This block must invoke one of the challenge-responder methods (NSURLAuthenticationChallengeSender protocol). If `allowsInvalidSSLCertificate` is set to YES, `connection:willSendRequestForAuthenticationChallenge:` will attempt to have the challenge sender use credentials with invalid SSL certificates. */ - (void)setWillSendRequestForAuthenticationChallengeBlock:(nullable void (^)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge))block; /** Sets a block to be executed when the server redirects the request from one URL to another URL, or when the request URL changed by the `NSURLProtocol` subclass handling the request in order to standardize its format, as handled by the `NSURLConnectionDataDelegate` method `connection:willSendRequest:redirectResponse:`. @param block A block object to be executed when the request URL was changed. The block returns an `NSURLRequest` object, the URL request to redirect, and takes three arguments: the URL connection object, the the proposed redirected request, and the URL response that caused the redirect. */ - (void)setRedirectResponseBlock:(nullable NSURLRequest * (^)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse))block; /** Sets a block to be executed to modify the response a connection will cache, if any, as handled by the `NSURLConnectionDelegate` method `connection:willCacheResponse:`. @param block A block object to be executed to determine what response a connection will cache, if any. The block returns an `NSCachedURLResponse` object, the cached response to store in memory or `nil` to prevent the response from being cached, and takes two arguments: the URL connection object, and the cached response provided for the request. */ - (void)setCacheResponseBlock:(nullable NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block; /// /** */ + (NSArray *)batchOfRequestOperations:(nullable NSArray *)operations progressBlock:(nullable void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock completionBlock:(nullable void (^)(NSArray *operations))completionBlock; @end ///-------------------- /// @name Notifications ///-------------------- /** Posted when an operation begins executing. */ extern NSString * const AFNetworkingOperationDidStartNotification; /** Posted when an operation finishes. */ extern NSString * const AFNetworkingOperationDidFinishNotification; NS_ASSUME_NONNULL_END
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/AFNetworking/AFNetworking/AFURLConnectionOperation.m
Objective-C
// AFURLConnectionOperation.m // Copyright (c) 2011–2015 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 "AFURLConnectionOperation.h" #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #import <UIKit/UIKit.h> #endif #if !__has_feature(objc_arc) #error AFNetworking must be built with ARC. // You can turn on ARC for only AFNetworking files by adding -fobjc-arc to the build phase for each of its files. #endif typedef NS_ENUM(NSInteger, AFOperationState) { AFOperationPausedState = -1, AFOperationReadyState = 1, AFOperationExecutingState = 2, AFOperationFinishedState = 3, }; static dispatch_group_t url_request_operation_completion_group() { static dispatch_group_t af_url_request_operation_completion_group; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ af_url_request_operation_completion_group = dispatch_group_create(); }); return af_url_request_operation_completion_group; } static dispatch_queue_t url_request_operation_completion_queue() { static dispatch_queue_t af_url_request_operation_completion_queue; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ af_url_request_operation_completion_queue = dispatch_queue_create("com.alamofire.networking.operation.queue", DISPATCH_QUEUE_CONCURRENT ); }); return af_url_request_operation_completion_queue; } static NSString * const kAFNetworkingLockName = @"com.alamofire.networking.operation.lock"; NSString * const AFNetworkingOperationDidStartNotification = @"com.alamofire.networking.operation.start"; NSString * const AFNetworkingOperationDidFinishNotification = @"com.alamofire.networking.operation.finish"; typedef void (^AFURLConnectionOperationProgressBlock)(NSUInteger bytes, long long totalBytes, long long totalBytesExpected); typedef void (^AFURLConnectionOperationAuthenticationChallengeBlock)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge); typedef NSCachedURLResponse * (^AFURLConnectionOperationCacheResponseBlock)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse); typedef NSURLRequest * (^AFURLConnectionOperationRedirectResponseBlock)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse); typedef void (^AFURLConnectionOperationBackgroundTaskCleanupBlock)(); static inline NSString * AFKeyPathFromOperationState(AFOperationState state) { switch (state) { case AFOperationReadyState: return @"isReady"; case AFOperationExecutingState: return @"isExecuting"; case AFOperationFinishedState: return @"isFinished"; case AFOperationPausedState: return @"isPaused"; default: { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunreachable-code" return @"state"; #pragma clang diagnostic pop } } } static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperationState toState, BOOL isCancelled) { switch (fromState) { case AFOperationReadyState: switch (toState) { case AFOperationPausedState: case AFOperationExecutingState: return YES; case AFOperationFinishedState: return isCancelled; default: return NO; } case AFOperationExecutingState: switch (toState) { case AFOperationPausedState: case AFOperationFinishedState: return YES; default: return NO; } case AFOperationFinishedState: return NO; case AFOperationPausedState: return toState == AFOperationReadyState; default: { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunreachable-code" switch (toState) { case AFOperationPausedState: case AFOperationReadyState: case AFOperationExecutingState: case AFOperationFinishedState: return YES; default: return NO; } } #pragma clang diagnostic pop } } @interface AFURLConnectionOperation () @property (readwrite, nonatomic, assign) AFOperationState state; @property (readwrite, nonatomic, strong) NSRecursiveLock *lock; @property (readwrite, nonatomic, strong) NSURLConnection *connection; @property (readwrite, nonatomic, strong) NSURLRequest *request; @property (readwrite, nonatomic, strong) NSURLResponse *response; @property (readwrite, nonatomic, strong) NSError *error; @property (readwrite, nonatomic, strong) NSData *responseData; @property (readwrite, nonatomic, copy) NSString *responseString; @property (readwrite, nonatomic, assign) NSStringEncoding responseStringEncoding; @property (readwrite, nonatomic, assign) long long totalBytesRead; @property (readwrite, nonatomic, copy) AFURLConnectionOperationBackgroundTaskCleanupBlock backgroundTaskCleanup; @property (readwrite, nonatomic, copy) AFURLConnectionOperationProgressBlock uploadProgress; @property (readwrite, nonatomic, copy) AFURLConnectionOperationProgressBlock downloadProgress; @property (readwrite, nonatomic, copy) AFURLConnectionOperationAuthenticationChallengeBlock authenticationChallenge; @property (readwrite, nonatomic, copy) AFURLConnectionOperationCacheResponseBlock cacheResponse; @property (readwrite, nonatomic, copy) AFURLConnectionOperationRedirectResponseBlock redirectResponse; - (void)operationDidStart; - (void)finish; - (void)cancelConnection; @end @implementation AFURLConnectionOperation @synthesize outputStream = _outputStream; + (void)networkRequestThreadEntryPoint:(id)__unused object { @autoreleasepool { [[NSThread currentThread] setName:@"AFNetworking"]; NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode]; [runLoop run]; } } + (NSThread *)networkRequestThread { static NSThread *_networkRequestThread = nil; static dispatch_once_t oncePredicate; dispatch_once(&oncePredicate, ^{ _networkRequestThread = [[NSThread alloc] initWithTarget:self selector:@selector(networkRequestThreadEntryPoint:) object:nil]; [_networkRequestThread start]; }); return _networkRequestThread; } - (instancetype)initWithRequest:(NSURLRequest *)urlRequest { NSParameterAssert(urlRequest); self = [super init]; if (!self) { return nil; } _state = AFOperationReadyState; self.lock = [[NSRecursiveLock alloc] init]; self.lock.name = kAFNetworkingLockName; self.runLoopModes = [NSSet setWithObject:NSRunLoopCommonModes]; self.request = urlRequest; self.shouldUseCredentialStorage = YES; self.securityPolicy = [AFSecurityPolicy defaultPolicy]; return self; } - (instancetype)init NS_UNAVAILABLE { return nil; } - (void)dealloc { if (_outputStream) { [_outputStream close]; _outputStream = nil; } if (_backgroundTaskCleanup) { _backgroundTaskCleanup(); } } #pragma mark - - (void)setResponseData:(NSData *)responseData { [self.lock lock]; if (!responseData) { _responseData = nil; } else { _responseData = [NSData dataWithBytes:responseData.bytes length:responseData.length]; } [self.lock unlock]; } - (NSString *)responseString { [self.lock lock]; if (!_responseString && self.response && self.responseData) { self.responseString = [[NSString alloc] initWithData:self.responseData encoding:self.responseStringEncoding]; } [self.lock unlock]; return _responseString; } - (NSStringEncoding)responseStringEncoding { [self.lock lock]; if (!_responseStringEncoding && self.response) { NSStringEncoding stringEncoding = NSUTF8StringEncoding; if (self.response.textEncodingName) { CFStringEncoding IANAEncoding = CFStringConvertIANACharSetNameToEncoding((__bridge CFStringRef)self.response.textEncodingName); if (IANAEncoding != kCFStringEncodingInvalidId) { stringEncoding = CFStringConvertEncodingToNSStringEncoding(IANAEncoding); } } self.responseStringEncoding = stringEncoding; } [self.lock unlock]; return _responseStringEncoding; } - (NSInputStream *)inputStream { return self.request.HTTPBodyStream; } - (void)setInputStream:(NSInputStream *)inputStream { NSMutableURLRequest *mutableRequest = [self.request mutableCopy]; mutableRequest.HTTPBodyStream = inputStream; self.request = mutableRequest; } - (NSOutputStream *)outputStream { if (!_outputStream) { self.outputStream = [NSOutputStream outputStreamToMemory]; } return _outputStream; } - (void)setOutputStream:(NSOutputStream *)outputStream { [self.lock lock]; if (outputStream != _outputStream) { if (_outputStream) { [_outputStream close]; } _outputStream = outputStream; } [self.lock unlock]; } #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) - (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler { [self.lock lock]; if (!self.backgroundTaskCleanup) { UIApplication *application = [UIApplication sharedApplication]; UIBackgroundTaskIdentifier __block backgroundTaskIdentifier = UIBackgroundTaskInvalid; __weak __typeof(self)weakSelf = self; self.backgroundTaskCleanup = ^(){ if (backgroundTaskIdentifier != UIBackgroundTaskInvalid) { [[UIApplication sharedApplication] endBackgroundTask:backgroundTaskIdentifier]; backgroundTaskIdentifier = UIBackgroundTaskInvalid; } }; backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{ __strong __typeof(weakSelf)strongSelf = weakSelf; if (handler) { handler(); } if (strongSelf) { [strongSelf cancel]; strongSelf.backgroundTaskCleanup(); } }]; } [self.lock unlock]; } #endif #pragma mark - - (void)setState:(AFOperationState)state { if (!AFStateTransitionIsValid(self.state, state, [self isCancelled])) { return; } [self.lock lock]; NSString *oldStateKey = AFKeyPathFromOperationState(self.state); NSString *newStateKey = AFKeyPathFromOperationState(state); [self willChangeValueForKey:newStateKey]; [self willChangeValueForKey:oldStateKey]; _state = state; [self didChangeValueForKey:oldStateKey]; [self didChangeValueForKey:newStateKey]; [self.lock unlock]; } - (void)pause { if ([self isPaused] || [self isFinished] || [self isCancelled]) { return; } [self.lock lock]; if ([self isExecuting]) { [self performSelector:@selector(operationDidPause) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]]; dispatch_async(dispatch_get_main_queue(), ^{ NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; [notificationCenter postNotificationName:AFNetworkingOperationDidFinishNotification object:self]; }); } self.state = AFOperationPausedState; [self.lock unlock]; } - (void)operationDidPause { [self.lock lock]; [self.connection cancel]; [self.lock unlock]; } - (BOOL)isPaused { return self.state == AFOperationPausedState; } - (void)resume { if (![self isPaused]) { return; } [self.lock lock]; self.state = AFOperationReadyState; [self start]; [self.lock unlock]; } #pragma mark - - (void)setUploadProgressBlock:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block { self.uploadProgress = block; } - (void)setDownloadProgressBlock:(void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))block { self.downloadProgress = block; } - (void)setWillSendRequestForAuthenticationChallengeBlock:(void (^)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge))block { self.authenticationChallenge = block; } - (void)setCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block { self.cacheResponse = block; } - (void)setRedirectResponseBlock:(NSURLRequest * (^)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse))block { self.redirectResponse = block; } #pragma mark - NSOperation - (void)setCompletionBlock:(void (^)(void))block { [self.lock lock]; if (!block) { [super setCompletionBlock:nil]; } else { __weak __typeof(self)weakSelf = self; [super setCompletionBlock:^ { __strong __typeof(weakSelf)strongSelf = weakSelf; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wgnu" dispatch_group_t group = strongSelf.completionGroup ?: url_request_operation_completion_group(); dispatch_queue_t queue = strongSelf.completionQueue ?: dispatch_get_main_queue(); #pragma clang diagnostic pop dispatch_group_async(group, queue, ^{ block(); }); dispatch_group_notify(group, url_request_operation_completion_queue(), ^{ [strongSelf setCompletionBlock:nil]; }); }]; } [self.lock unlock]; } - (BOOL)isReady { return self.state == AFOperationReadyState && [super isReady]; } - (BOOL)isExecuting { return self.state == AFOperationExecutingState; } - (BOOL)isFinished { return self.state == AFOperationFinishedState; } - (BOOL)isConcurrent { return YES; } - (void)start { [self.lock lock]; if ([self isCancelled]) { [self performSelector:@selector(cancelConnection) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]]; } else if ([self isReady]) { self.state = AFOperationExecutingState; [self performSelector:@selector(operationDidStart) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]]; } [self.lock unlock]; } - (void)operationDidStart { [self.lock lock]; if (![self isCancelled]) { self.connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO]; NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; for (NSString *runLoopMode in self.runLoopModes) { [self.connection scheduleInRunLoop:runLoop forMode:runLoopMode]; [self.outputStream scheduleInRunLoop:runLoop forMode:runLoopMode]; } [self.outputStream open]; [self.connection start]; } [self.lock unlock]; dispatch_async(dispatch_get_main_queue(), ^{ [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidStartNotification object:self]; }); } - (void)finish { [self.lock lock]; self.state = AFOperationFinishedState; [self.lock unlock]; dispatch_async(dispatch_get_main_queue(), ^{ [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidFinishNotification object:self]; }); } - (void)cancel { [self.lock lock]; if (![self isFinished] && ![self isCancelled]) { [super cancel]; if ([self isExecuting]) { [self performSelector:@selector(cancelConnection) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]]; } } [self.lock unlock]; } - (void)cancelConnection { NSDictionary *userInfo = nil; if ([self.request URL]) { userInfo = @{NSURLErrorFailingURLErrorKey : [self.request URL]}; } NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo]; if (![self isFinished]) { if (self.connection) { [self.connection cancel]; [self performSelector:@selector(connection:didFailWithError:) withObject:self.connection withObject:error]; } else { // Accommodate race condition where `self.connection` has not yet been set before cancellation self.error = error; [self finish]; } } } #pragma mark - + (NSArray *)batchOfRequestOperations:(NSArray *)operations progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock completionBlock:(void (^)(NSArray *operations))completionBlock { if (!operations || [operations count] == 0) { return @[[NSBlockOperation blockOperationWithBlock:^{ dispatch_async(dispatch_get_main_queue(), ^{ if (completionBlock) { completionBlock(@[]); } }); }]]; } __block dispatch_group_t group = dispatch_group_create(); NSBlockOperation *batchedOperation = [NSBlockOperation blockOperationWithBlock:^{ dispatch_group_notify(group, dispatch_get_main_queue(), ^{ if (completionBlock) { completionBlock(operations); } }); }]; for (AFURLConnectionOperation *operation in operations) { operation.completionGroup = group; void (^originalCompletionBlock)(void) = [operation.completionBlock copy]; __weak __typeof(operation)weakOperation = operation; operation.completionBlock = ^{ __strong __typeof(weakOperation)strongOperation = weakOperation; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wgnu" dispatch_queue_t queue = strongOperation.completionQueue ?: dispatch_get_main_queue(); #pragma clang diagnostic pop dispatch_group_async(group, queue, ^{ if (originalCompletionBlock) { originalCompletionBlock(); } NSUInteger numberOfFinishedOperations = [[operations indexesOfObjectsPassingTest:^BOOL(id op, NSUInteger __unused idx, BOOL __unused *stop) { return [op isFinished]; }] count]; if (progressBlock) { progressBlock(numberOfFinishedOperations, [operations count]); } dispatch_group_leave(group); }); }; dispatch_group_enter(group); [batchedOperation addDependency:operation]; } return [operations arrayByAddingObject:batchedOperation]; } #pragma mark - NSObject - (NSString *)description { [self.lock lock]; NSString *description = [NSString stringWithFormat:@"<%@: %p, state: %@, cancelled: %@ request: %@, response: %@>", NSStringFromClass([self class]), self, AFKeyPathFromOperationState(self.state), ([self isCancelled] ? @"YES" : @"NO"), self.request, self.response]; [self.lock unlock]; return description; } #pragma mark - NSURLConnectionDelegate - (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { if (self.authenticationChallenge) { self.authenticationChallenge(connection, challenge); return; } if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) { NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; } else { [[challenge sender] cancelAuthenticationChallenge:challenge]; } } else { if ([challenge previousFailureCount] == 0) { if (self.credential) { [[challenge sender] useCredential:self.credential forAuthenticationChallenge:challenge]; } else { [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge]; } } else { [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge]; } } } - (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection __unused *)connection { return self.shouldUseCredentialStorage; } - (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse { if (self.redirectResponse) { return self.redirectResponse(connection, request, redirectResponse); } else { return request; } } - (void)connection:(NSURLConnection __unused *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite { dispatch_async(dispatch_get_main_queue(), ^{ if (self.uploadProgress) { self.uploadProgress((NSUInteger)bytesWritten, totalBytesWritten, totalBytesExpectedToWrite); } }); } - (void)connection:(NSURLConnection __unused *)connection didReceiveResponse:(NSURLResponse *)response { self.response = response; } - (void)connection:(NSURLConnection __unused *)connection didReceiveData:(NSData *)data { NSUInteger length = [data length]; while (YES) { NSInteger totalNumberOfBytesWritten = 0; if ([self.outputStream hasSpaceAvailable]) { const uint8_t *dataBuffer = (uint8_t *)[data bytes]; NSInteger numberOfBytesWritten = 0; while (totalNumberOfBytesWritten < (NSInteger)length) { numberOfBytesWritten = [self.outputStream write:&dataBuffer[(NSUInteger)totalNumberOfBytesWritten] maxLength:(length - (NSUInteger)totalNumberOfBytesWritten)]; if (numberOfBytesWritten == -1) { break; } totalNumberOfBytesWritten += numberOfBytesWritten; } break; } if (self.outputStream.streamError) { [self.connection cancel]; [self performSelector:@selector(connection:didFailWithError:) withObject:self.connection withObject:self.outputStream.streamError]; return; } } dispatch_async(dispatch_get_main_queue(), ^{ self.totalBytesRead += (long long)length; if (self.downloadProgress) { self.downloadProgress(length, self.totalBytesRead, self.response.expectedContentLength); } }); } - (void)connectionDidFinishLoading:(NSURLConnection __unused *)connection { self.responseData = [self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey]; [self.outputStream close]; if (self.responseData) { self.outputStream = nil; } self.connection = nil; [self finish]; } - (void)connection:(NSURLConnection __unused *)connection didFailWithError:(NSError *)error { self.error = error; [self.outputStream close]; if (self.responseData) { self.outputStream = nil; } self.connection = nil; [self finish]; } - (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse { if (self.cacheResponse) { return self.cacheResponse(connection, cachedResponse); } else { if ([self isCancelled]) { return nil; } return cachedResponse; } } #pragma mark - NSSecureCoding + (BOOL)supportsSecureCoding { return YES; } - (id)initWithCoder:(NSCoder *)decoder { NSURLRequest *request = [decoder decodeObjectOfClass:[NSURLRequest class] forKey:NSStringFromSelector(@selector(request))]; self = [self initWithRequest:request]; if (!self) { return nil; } self.state = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(state))] integerValue]; self.response = [decoder decodeObjectOfClass:[NSHTTPURLResponse class] forKey:NSStringFromSelector(@selector(response))]; self.error = [decoder decodeObjectOfClass:[NSError class] forKey:NSStringFromSelector(@selector(error))]; self.responseData = [decoder decodeObjectOfClass:[NSData class] forKey:NSStringFromSelector(@selector(responseData))]; self.totalBytesRead = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(totalBytesRead))] longLongValue]; return self; } - (void)encodeWithCoder:(NSCoder *)coder { [self pause]; [coder encodeObject:self.request forKey:NSStringFromSelector(@selector(request))]; switch (self.state) { case AFOperationExecutingState: case AFOperationPausedState: [coder encodeInteger:AFOperationReadyState forKey:NSStringFromSelector(@selector(state))]; break; default: [coder encodeInteger:self.state forKey:NSStringFromSelector(@selector(state))]; break; } [coder encodeObject:self.response forKey:NSStringFromSelector(@selector(response))]; [coder encodeObject:self.error forKey:NSStringFromSelector(@selector(error))]; [coder encodeObject:self.responseData forKey:NSStringFromSelector(@selector(responseData))]; [coder encodeInt64:self.totalBytesRead forKey:NSStringFromSelector(@selector(totalBytesRead))]; } #pragma mark - NSCopying - (id)copyWithZone:(NSZone *)zone { AFURLConnectionOperation *operation = [(AFURLConnectionOperation *)[[self class] allocWithZone:zone] initWithRequest:self.request]; operation.uploadProgress = self.uploadProgress; operation.downloadProgress = self.downloadProgress; operation.authenticationChallenge = self.authenticationChallenge; operation.cacheResponse = self.cacheResponse; operation.redirectResponse = self.redirectResponse; operation.completionQueue = self.completionQueue; operation.completionGroup = self.completionGroup; return operation; } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.h
C/C++ Header
// AFURLRequestSerialization.h // Copyright (c) 2011–2015 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_IOS #import <UIKit/UIKit.h> #elif TARGET_OS_WATCH #import <WatchKit/WatchKit.h> #endif NS_ASSUME_NONNULL_BEGIN /** 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; @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 *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; /** @deprecated This method has been deprecated. Use -setValue:forHTTPHeaderField: instead. */ - (void)setAuthorizationHeaderFieldWithToken:(NSString *)token DEPRECATED_ATTRIBUTE; /** 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 *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 * (^)(NSURLRequest *request, id parameters, NSError * __autoreleasing *error))block; ///------------------------------- /// @name Creating Request Objects ///------------------------------- /** @deprecated This method has been deprecated. Use -requestWithMethod:URLString:parameters:error: instead. */ - (NSMutableURLRequest *)requestWithMethod:(NSString *)method URLString:(NSString *)URLString parameters:(id)parameters DEPRECATED_ATTRIBUTE; /** 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. */ - (NSMutableURLRequest *)requestWithMethod:(NSString *)method URLString:(NSString *)URLString parameters:(nullable id)parameters error:(NSError * __nullable __autoreleasing *)error; /** @deprecated This method has been deprecated. Use -multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:error: instead. */ - (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method URLString:(NSString *)URLString parameters:(NSDictionary *)parameters constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block DEPRECATED_ATTRIBUTE; /** 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 *)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 *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 *)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`. */ extern 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`. */ extern 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. */ extern NSUInteger const kAFUploadStream3GSuggestedPacketSize; extern NSTimeInterval const kAFUploadStream3GSuggestedDelay; NS_ASSUME_NONNULL_END
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.m
Objective-C
// AFURLRequestSerialization.m // Copyright (c) 2011–2015 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 "AFURLRequestSerialization.h" #if __IPHONE_OS_VERSION_MIN_REQUIRED #import <MobileCoreServices/MobileCoreServices.h> #else #import <CoreServices/CoreServices.h> #endif NSString * const AFURLRequestSerializationErrorDomain = @"com.alamofire.error.serialization.request"; NSString * const AFNetworkingOperationFailingURLRequestErrorKey = @"com.alamofire.serialization.request.error.response"; typedef NSString * (^AFQueryStringSerializationBlock)(NSURLRequest *request, id parameters, NSError *__autoreleasing *error); static NSString * AFBase64EncodedStringFromString(NSString *string) { NSData *data = [NSData dataWithBytes:[string UTF8String] length:[string lengthOfBytesUsingEncoding:NSUTF8StringEncoding]]; NSUInteger length = [data length]; NSMutableData *mutableData = [NSMutableData dataWithLength:((length + 2) / 3) * 4]; uint8_t *input = (uint8_t *)[data bytes]; uint8_t *output = (uint8_t *)[mutableData mutableBytes]; for (NSUInteger i = 0; i < length; i += 3) { NSUInteger value = 0; for (NSUInteger j = i; j < (i + 3); j++) { value <<= 8; if (j < length) { value |= (0xFF & input[j]); } } static uint8_t const kAFBase64EncodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; NSUInteger idx = (i / 3) * 4; output[idx + 0] = kAFBase64EncodingTable[(value >> 18) & 0x3F]; output[idx + 1] = kAFBase64EncodingTable[(value >> 12) & 0x3F]; output[idx + 2] = (i + 1) < length ? kAFBase64EncodingTable[(value >> 6) & 0x3F] : '='; output[idx + 3] = (i + 2) < length ? kAFBase64EncodingTable[(value >> 0) & 0x3F] : '='; } return [[NSString alloc] initWithData:mutableData encoding:NSASCIIStringEncoding]; } /** 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. - parameter string: The string to be percent-escaped. - returns: The percent-escaped string. */ static NSString * AFPercentEscapedStringFromString(NSString *string) { static NSString * const kAFCharactersGeneralDelimitersToEncode = @":#[]@"; // does not include "?" or "/" due to RFC 3986 - Section 3.4 static NSString * const kAFCharactersSubDelimitersToEncode = @"!$&'()*+,;="; NSMutableCharacterSet * allowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy]; [allowedCharacterSet removeCharactersInString:[kAFCharactersGeneralDelimitersToEncode stringByAppendingString:kAFCharactersSubDelimitersToEncode]]; return [string stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet]; } #pragma mark - @interface AFQueryStringPair : NSObject @property (readwrite, nonatomic, strong) id field; @property (readwrite, nonatomic, strong) id value; - (id)initWithField:(id)field value:(id)value; - (NSString *)URLEncodedStringValue; @end @implementation AFQueryStringPair - (id)initWithField:(id)field value:(id)value { self = [super init]; if (!self) { return nil; } self.field = field; self.value = value; return self; } - (NSString *)URLEncodedStringValue { if (!self.value || [self.value isEqual:[NSNull null]]) { return AFPercentEscapedStringFromString([self.field description]); } else { return [NSString stringWithFormat:@"%@=%@", AFPercentEscapedStringFromString([self.field description]), AFPercentEscapedStringFromString([self.value description])]; } } @end #pragma mark - extern NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary); extern NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value); static NSString * AFQueryStringFromParameters(NSDictionary *parameters) { NSMutableArray *mutablePairs = [NSMutableArray array]; for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) { [mutablePairs addObject:[pair URLEncodedStringValue]]; } return [mutablePairs componentsJoinedByString:@"&"]; } NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary) { return AFQueryStringPairsFromKeyAndValue(nil, dictionary); } NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value) { NSMutableArray *mutableQueryStringComponents = [NSMutableArray array]; NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES selector:@selector(compare:)]; if ([value isKindOfClass:[NSDictionary class]]) { NSDictionary *dictionary = value; // Sort dictionary keys to ensure consistent ordering in query string, which is important when deserializing potentially ambiguous sequences, such as an array of dictionaries for (id nestedKey in [dictionary.allKeys sortedArrayUsingDescriptors:@[ sortDescriptor ]]) { id nestedValue = dictionary[nestedKey]; if (nestedValue) { [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue((key ? [NSString stringWithFormat:@"%@[%@]", key, nestedKey] : nestedKey), nestedValue)]; } } } else if ([value isKindOfClass:[NSArray class]]) { NSArray *array = value; for (id nestedValue in array) { [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue([NSString stringWithFormat:@"%@[]", key], nestedValue)]; } } else if ([value isKindOfClass:[NSSet class]]) { NSSet *set = value; for (id obj in [set sortedArrayUsingDescriptors:@[ sortDescriptor ]]) { [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue(key, obj)]; } } else { [mutableQueryStringComponents addObject:[[AFQueryStringPair alloc] initWithField:key value:value]]; } return mutableQueryStringComponents; } #pragma mark - @interface AFStreamingMultipartFormData : NSObject <AFMultipartFormData> - (instancetype)initWithURLRequest:(NSMutableURLRequest *)urlRequest stringEncoding:(NSStringEncoding)encoding; - (NSMutableURLRequest *)requestByFinalizingMultipartFormData; @end #pragma mark - static NSArray * AFHTTPRequestSerializerObservedKeyPaths() { static NSArray *_AFHTTPRequestSerializerObservedKeyPaths = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _AFHTTPRequestSerializerObservedKeyPaths = @[NSStringFromSelector(@selector(allowsCellularAccess)), NSStringFromSelector(@selector(cachePolicy)), NSStringFromSelector(@selector(HTTPShouldHandleCookies)), NSStringFromSelector(@selector(HTTPShouldUsePipelining)), NSStringFromSelector(@selector(networkServiceType)), NSStringFromSelector(@selector(timeoutInterval))]; }); return _AFHTTPRequestSerializerObservedKeyPaths; } static void *AFHTTPRequestSerializerObserverContext = &AFHTTPRequestSerializerObserverContext; @interface AFHTTPRequestSerializer () @property (readwrite, nonatomic, strong) NSMutableSet *mutableObservedChangedKeyPaths; @property (readwrite, nonatomic, strong) NSMutableDictionary *mutableHTTPRequestHeaders; @property (readwrite, nonatomic, assign) AFHTTPRequestQueryStringSerializationStyle queryStringSerializationStyle; @property (readwrite, nonatomic, copy) AFQueryStringSerializationBlock queryStringSerialization; @end @implementation AFHTTPRequestSerializer + (instancetype)serializer { return [[self alloc] init]; } - (instancetype)init { self = [super init]; if (!self) { return nil; } self.stringEncoding = NSUTF8StringEncoding; self.mutableHTTPRequestHeaders = [NSMutableDictionary dictionary]; // Accept-Language HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 NSMutableArray *acceptLanguagesComponents = [NSMutableArray array]; [[NSLocale preferredLanguages] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { float q = 1.0f - (idx * 0.1f); [acceptLanguagesComponents addObject:[NSString stringWithFormat:@"%@;q=%0.1g", obj, q]]; *stop = q <= 0.5f; }]; [self setValue:[acceptLanguagesComponents componentsJoinedByString:@", "] forHTTPHeaderField:@"Accept-Language"]; NSString *userAgent = nil; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wgnu" #if TARGET_OS_IOS // User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43 userAgent = [NSString stringWithFormat:@"%@/%@ (%@; iOS %@; Scale/%0.2f)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]]; #elif TARGET_OS_WATCH // User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43 userAgent = [NSString stringWithFormat:@"%@/%@ (%@; watchOS %@; Scale/%0.2f)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[WKInterfaceDevice currentDevice] model], [[WKInterfaceDevice currentDevice] systemVersion], [[WKInterfaceDevice currentDevice] screenScale]]; #elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) userAgent = [NSString stringWithFormat:@"%@/%@ (Mac OS X %@)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[NSProcessInfo processInfo] operatingSystemVersionString]]; #endif #pragma clang diagnostic pop if (userAgent) { if (![userAgent canBeConvertedToEncoding:NSASCIIStringEncoding]) { NSMutableString *mutableUserAgent = [userAgent mutableCopy]; if (CFStringTransform((__bridge CFMutableStringRef)(mutableUserAgent), NULL, (__bridge CFStringRef)@"Any-Latin; Latin-ASCII; [:^ASCII:] Remove", false)) { userAgent = mutableUserAgent; } } [self setValue:userAgent forHTTPHeaderField:@"User-Agent"]; } // HTTP Method Definitions; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html self.HTTPMethodsEncodingParametersInURI = [NSSet setWithObjects:@"GET", @"HEAD", @"DELETE", nil]; self.mutableObservedChangedKeyPaths = [NSMutableSet set]; for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) { if ([self respondsToSelector:NSSelectorFromString(keyPath)]) { [self addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:AFHTTPRequestSerializerObserverContext]; } } return self; } - (void)dealloc { for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) { if ([self respondsToSelector:NSSelectorFromString(keyPath)]) { [self removeObserver:self forKeyPath:keyPath context:AFHTTPRequestSerializerObserverContext]; } } } #pragma mark - // Workarounds for crashing behavior using Key-Value Observing with XCTest // See https://github.com/AFNetworking/AFNetworking/issues/2523 - (void)setAllowsCellularAccess:(BOOL)allowsCellularAccess { [self willChangeValueForKey:NSStringFromSelector(@selector(allowsCellularAccess))]; _allowsCellularAccess = allowsCellularAccess; [self didChangeValueForKey:NSStringFromSelector(@selector(allowsCellularAccess))]; } - (void)setCachePolicy:(NSURLRequestCachePolicy)cachePolicy { [self willChangeValueForKey:NSStringFromSelector(@selector(cachePolicy))]; _cachePolicy = cachePolicy; [self didChangeValueForKey:NSStringFromSelector(@selector(cachePolicy))]; } - (void)setHTTPShouldHandleCookies:(BOOL)HTTPShouldHandleCookies { [self willChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldHandleCookies))]; _HTTPShouldHandleCookies = HTTPShouldHandleCookies; [self didChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldHandleCookies))]; } - (void)setHTTPShouldUsePipelining:(BOOL)HTTPShouldUsePipelining { [self willChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldUsePipelining))]; _HTTPShouldUsePipelining = HTTPShouldUsePipelining; [self didChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldUsePipelining))]; } - (void)setNetworkServiceType:(NSURLRequestNetworkServiceType)networkServiceType { [self willChangeValueForKey:NSStringFromSelector(@selector(networkServiceType))]; _networkServiceType = networkServiceType; [self didChangeValueForKey:NSStringFromSelector(@selector(networkServiceType))]; } - (void)setTimeoutInterval:(NSTimeInterval)timeoutInterval { [self willChangeValueForKey:NSStringFromSelector(@selector(timeoutInterval))]; _timeoutInterval = timeoutInterval; [self didChangeValueForKey:NSStringFromSelector(@selector(timeoutInterval))]; } #pragma mark - - (NSDictionary *)HTTPRequestHeaders { return [NSDictionary dictionaryWithDictionary:self.mutableHTTPRequestHeaders]; } - (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field { [self.mutableHTTPRequestHeaders setValue:value forKey:field]; } - (NSString *)valueForHTTPHeaderField:(NSString *)field { return [self.mutableHTTPRequestHeaders valueForKey:field]; } - (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username password:(NSString *)password { NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", username, password]; [self setValue:[NSString stringWithFormat:@"Basic %@", AFBase64EncodedStringFromString(basicAuthCredentials)] forHTTPHeaderField:@"Authorization"]; } - (void)setAuthorizationHeaderFieldWithToken:(NSString *)token { [self setValue:[NSString stringWithFormat:@"Token token=\"%@\"", token] forHTTPHeaderField:@"Authorization"]; } - (void)clearAuthorizationHeader { [self.mutableHTTPRequestHeaders removeObjectForKey:@"Authorization"]; } #pragma mark - - (void)setQueryStringSerializationWithStyle:(AFHTTPRequestQueryStringSerializationStyle)style { self.queryStringSerializationStyle = style; self.queryStringSerialization = nil; } - (void)setQueryStringSerializationWithBlock:(NSString *(^)(NSURLRequest *, id, NSError *__autoreleasing *))block { self.queryStringSerialization = block; } #pragma mark - - (NSMutableURLRequest *)requestWithMethod:(NSString *)method URLString:(NSString *)URLString parameters:(id)parameters { return [self requestWithMethod:method URLString:URLString parameters:parameters error:nil]; } - (NSMutableURLRequest *)requestWithMethod:(NSString *)method URLString:(NSString *)URLString parameters:(id)parameters error:(NSError *__autoreleasing *)error { NSParameterAssert(method); NSParameterAssert(URLString); NSURL *url = [NSURL URLWithString:URLString]; NSParameterAssert(url); NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc] initWithURL:url]; mutableRequest.HTTPMethod = method; for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) { if ([self.mutableObservedChangedKeyPaths containsObject:keyPath]) { [mutableRequest setValue:[self valueForKeyPath:keyPath] forKey:keyPath]; } } mutableRequest = [[self requestBySerializingRequest:mutableRequest withParameters:parameters error:error] mutableCopy]; return mutableRequest; } - (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method URLString:(NSString *)URLString parameters:(NSDictionary *)parameters constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block { return [self multipartFormRequestWithMethod:method URLString:URLString parameters:parameters constructingBodyWithBlock:block error:nil]; } - (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method URLString:(NSString *)URLString parameters:(NSDictionary *)parameters constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block error:(NSError *__autoreleasing *)error { NSParameterAssert(method); NSParameterAssert(![method isEqualToString:@"GET"] && ![method isEqualToString:@"HEAD"]); NSMutableURLRequest *mutableRequest = [self requestWithMethod:method URLString:URLString parameters:nil error:error]; __block AFStreamingMultipartFormData *formData = [[AFStreamingMultipartFormData alloc] initWithURLRequest:mutableRequest stringEncoding:NSUTF8StringEncoding]; if (parameters) { for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) { NSData *data = nil; if ([pair.value isKindOfClass:[NSData class]]) { data = pair.value; } else if ([pair.value isEqual:[NSNull null]]) { data = [NSData data]; } else { data = [[pair.value description] dataUsingEncoding:self.stringEncoding]; } if (data) { [formData appendPartWithFormData:data name:[pair.field description]]; } } } if (block) { block(formData); } return [formData requestByFinalizingMultipartFormData]; } - (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request writingStreamContentsToFile:(NSURL *)fileURL completionHandler:(void (^)(NSError *error))handler { NSParameterAssert(request.HTTPBodyStream); NSParameterAssert([fileURL isFileURL]); NSInputStream *inputStream = request.HTTPBodyStream; NSOutputStream *outputStream = [[NSOutputStream alloc] initWithURL:fileURL append:NO]; __block NSError *error = nil; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [inputStream open]; [outputStream open]; while ([inputStream hasBytesAvailable] && [outputStream hasSpaceAvailable]) { uint8_t buffer[1024]; NSInteger bytesRead = [inputStream read:buffer maxLength:1024]; if (inputStream.streamError || bytesRead < 0) { error = inputStream.streamError; break; } NSInteger bytesWritten = [outputStream write:buffer maxLength:(NSUInteger)bytesRead]; if (outputStream.streamError || bytesWritten < 0) { error = outputStream.streamError; break; } if (bytesRead == 0 && bytesWritten == 0) { break; } } [outputStream close]; [inputStream close]; if (handler) { dispatch_async(dispatch_get_main_queue(), ^{ handler(error); }); } }); NSMutableURLRequest *mutableRequest = [request mutableCopy]; mutableRequest.HTTPBodyStream = nil; return mutableRequest; } #pragma mark - AFURLRequestSerialization - (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request withParameters:(id)parameters error:(NSError *__autoreleasing *)error { NSParameterAssert(request); NSMutableURLRequest *mutableRequest = [request mutableCopy]; [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) { if (![request valueForHTTPHeaderField:field]) { [mutableRequest setValue:value forHTTPHeaderField:field]; } }]; if (parameters) { NSString *query = nil; if (self.queryStringSerialization) { NSError *serializationError; query = self.queryStringSerialization(request, parameters, &serializationError); if (serializationError) { if (error) { *error = serializationError; } return nil; } } else { switch (self.queryStringSerializationStyle) { case AFHTTPRequestQueryStringDefaultStyle: query = AFQueryStringFromParameters(parameters); break; } } if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) { mutableRequest.URL = [NSURL URLWithString:[[mutableRequest.URL absoluteString] stringByAppendingFormat:mutableRequest.URL.query ? @"&%@" : @"?%@", query]]; } else { if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) { [mutableRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; } [mutableRequest setHTTPBody:[query dataUsingEncoding:self.stringEncoding]]; } } return mutableRequest; } #pragma mark - NSKeyValueObserving + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key { if ([AFHTTPRequestSerializerObservedKeyPaths() containsObject:key]) { return NO; } return [super automaticallyNotifiesObserversForKey:key]; } - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(__unused id)object change:(NSDictionary *)change context:(void *)context { if (context == AFHTTPRequestSerializerObserverContext) { if ([change[NSKeyValueChangeNewKey] isEqual:[NSNull null]]) { [self.mutableObservedChangedKeyPaths removeObject:keyPath]; } else { [self.mutableObservedChangedKeyPaths addObject:keyPath]; } } } #pragma mark - NSSecureCoding + (BOOL)supportsSecureCoding { return YES; } - (id)initWithCoder:(NSCoder *)decoder { self = [self init]; if (!self) { return nil; } self.mutableHTTPRequestHeaders = [[decoder decodeObjectOfClass:[NSDictionary class] forKey:NSStringFromSelector(@selector(mutableHTTPRequestHeaders))] mutableCopy]; self.queryStringSerializationStyle = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))] unsignedIntegerValue]; return self; } - (void)encodeWithCoder:(NSCoder *)coder { [coder encodeObject:self.mutableHTTPRequestHeaders forKey:NSStringFromSelector(@selector(mutableHTTPRequestHeaders))]; [coder encodeInteger:self.queryStringSerializationStyle forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))]; } #pragma mark - NSCopying - (id)copyWithZone:(NSZone *)zone { AFHTTPRequestSerializer *serializer = [[[self class] allocWithZone:zone] init]; serializer.mutableHTTPRequestHeaders = [self.mutableHTTPRequestHeaders mutableCopyWithZone:zone]; serializer.queryStringSerializationStyle = self.queryStringSerializationStyle; serializer.queryStringSerialization = self.queryStringSerialization; return serializer; } @end #pragma mark - static NSString * AFCreateMultipartFormBoundary() { return [NSString stringWithFormat:@"Boundary+%08X%08X", arc4random(), arc4random()]; } static NSString * const kAFMultipartFormCRLF = @"\r\n"; static inline NSString * AFMultipartFormInitialBoundary(NSString *boundary) { return [NSString stringWithFormat:@"--%@%@", boundary, kAFMultipartFormCRLF]; } static inline NSString * AFMultipartFormEncapsulationBoundary(NSString *boundary) { return [NSString stringWithFormat:@"%@--%@%@", kAFMultipartFormCRLF, boundary, kAFMultipartFormCRLF]; } static inline NSString * AFMultipartFormFinalBoundary(NSString *boundary) { return [NSString stringWithFormat:@"%@--%@--%@", kAFMultipartFormCRLF, boundary, kAFMultipartFormCRLF]; } static inline NSString * AFContentTypeForPathExtension(NSString *extension) { #ifdef __UTTYPE__ NSString *UTI = (__bridge_transfer NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)extension, NULL); NSString *contentType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)UTI, kUTTagClassMIMEType); if (!contentType) { return @"application/octet-stream"; } else { return contentType; } #else #pragma unused (extension) return @"application/octet-stream"; #endif } NSUInteger const kAFUploadStream3GSuggestedPacketSize = 1024 * 16; NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2; @interface AFHTTPBodyPart : NSObject @property (nonatomic, assign) NSStringEncoding stringEncoding; @property (nonatomic, strong) NSDictionary *headers; @property (nonatomic, copy) NSString *boundary; @property (nonatomic, strong) id body; @property (nonatomic, assign) unsigned long long bodyContentLength; @property (nonatomic, strong) NSInputStream *inputStream; @property (nonatomic, assign) BOOL hasInitialBoundary; @property (nonatomic, assign) BOOL hasFinalBoundary; @property (readonly, nonatomic, assign, getter = hasBytesAvailable) BOOL bytesAvailable; @property (readonly, nonatomic, assign) unsigned long long contentLength; - (NSInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)length; @end @interface AFMultipartBodyStream : NSInputStream <NSStreamDelegate> @property (nonatomic, assign) NSUInteger numberOfBytesInPacket; @property (nonatomic, assign) NSTimeInterval delay; @property (nonatomic, strong) NSInputStream *inputStream; @property (readonly, nonatomic, assign) unsigned long long contentLength; @property (readonly, nonatomic, assign, getter = isEmpty) BOOL empty; - (id)initWithStringEncoding:(NSStringEncoding)encoding; - (void)setInitialAndFinalBoundaries; - (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart; @end #pragma mark - @interface AFStreamingMultipartFormData () @property (readwrite, nonatomic, copy) NSMutableURLRequest *request; @property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding; @property (readwrite, nonatomic, copy) NSString *boundary; @property (readwrite, nonatomic, strong) AFMultipartBodyStream *bodyStream; @end @implementation AFStreamingMultipartFormData - (id)initWithURLRequest:(NSMutableURLRequest *)urlRequest stringEncoding:(NSStringEncoding)encoding { self = [super init]; if (!self) { return nil; } self.request = urlRequest; self.stringEncoding = encoding; self.boundary = AFCreateMultipartFormBoundary(); self.bodyStream = [[AFMultipartBodyStream alloc] initWithStringEncoding:encoding]; return self; } - (BOOL)appendPartWithFileURL:(NSURL *)fileURL name:(NSString *)name error:(NSError * __autoreleasing *)error { NSParameterAssert(fileURL); NSParameterAssert(name); NSString *fileName = [fileURL lastPathComponent]; NSString *mimeType = AFContentTypeForPathExtension([fileURL pathExtension]); return [self appendPartWithFileURL:fileURL name:name fileName:fileName mimeType:mimeType error:error]; } - (BOOL)appendPartWithFileURL:(NSURL *)fileURL name:(NSString *)name fileName:(NSString *)fileName mimeType:(NSString *)mimeType error:(NSError * __autoreleasing *)error { NSParameterAssert(fileURL); NSParameterAssert(name); NSParameterAssert(fileName); NSParameterAssert(mimeType); if (![fileURL isFileURL]) { NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"Expected URL to be a file URL", @"AFNetworking", nil)}; if (error) { *error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorBadURL userInfo:userInfo]; } return NO; } else if ([fileURL checkResourceIsReachableAndReturnError:error] == NO) { NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"File URL not reachable.", @"AFNetworking", nil)}; if (error) { *error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorBadURL userInfo:userInfo]; } return NO; } NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[fileURL path] error:error]; if (!fileAttributes) { return NO; } NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"]; [mutableHeaders setValue:mimeType forKey:@"Content-Type"]; AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init]; bodyPart.stringEncoding = self.stringEncoding; bodyPart.headers = mutableHeaders; bodyPart.boundary = self.boundary; bodyPart.body = fileURL; bodyPart.bodyContentLength = [fileAttributes[NSFileSize] unsignedLongLongValue]; [self.bodyStream appendHTTPBodyPart:bodyPart]; return YES; } - (void)appendPartWithInputStream:(NSInputStream *)inputStream name:(NSString *)name fileName:(NSString *)fileName length:(int64_t)length mimeType:(NSString *)mimeType { NSParameterAssert(name); NSParameterAssert(fileName); NSParameterAssert(mimeType); NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"]; [mutableHeaders setValue:mimeType forKey:@"Content-Type"]; AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init]; bodyPart.stringEncoding = self.stringEncoding; bodyPart.headers = mutableHeaders; bodyPart.boundary = self.boundary; bodyPart.body = inputStream; bodyPart.bodyContentLength = (unsigned long long)length; [self.bodyStream appendHTTPBodyPart:bodyPart]; } - (void)appendPartWithFileData:(NSData *)data name:(NSString *)name fileName:(NSString *)fileName mimeType:(NSString *)mimeType { NSParameterAssert(name); NSParameterAssert(fileName); NSParameterAssert(mimeType); NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"]; [mutableHeaders setValue:mimeType forKey:@"Content-Type"]; [self appendPartWithHeaders:mutableHeaders body:data]; } - (void)appendPartWithFormData:(NSData *)data name:(NSString *)name { NSParameterAssert(name); NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"", name] forKey:@"Content-Disposition"]; [self appendPartWithHeaders:mutableHeaders body:data]; } - (void)appendPartWithHeaders:(NSDictionary *)headers body:(NSData *)body { NSParameterAssert(body); AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init]; bodyPart.stringEncoding = self.stringEncoding; bodyPart.headers = headers; bodyPart.boundary = self.boundary; bodyPart.bodyContentLength = [body length]; bodyPart.body = body; [self.bodyStream appendHTTPBodyPart:bodyPart]; } - (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes delay:(NSTimeInterval)delay { self.bodyStream.numberOfBytesInPacket = numberOfBytes; self.bodyStream.delay = delay; } - (NSMutableURLRequest *)requestByFinalizingMultipartFormData { if ([self.bodyStream isEmpty]) { return self.request; } // Reset the initial and final boundaries to ensure correct Content-Length [self.bodyStream setInitialAndFinalBoundaries]; [self.request setHTTPBodyStream:self.bodyStream]; [self.request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", self.boundary] forHTTPHeaderField:@"Content-Type"]; [self.request setValue:[NSString stringWithFormat:@"%llu", [self.bodyStream contentLength]] forHTTPHeaderField:@"Content-Length"]; return self.request; } @end #pragma mark - @interface NSStream () @property (readwrite) NSStreamStatus streamStatus; @property (readwrite, copy) NSError *streamError; @end @interface AFMultipartBodyStream () <NSCopying> @property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding; @property (readwrite, nonatomic, strong) NSMutableArray *HTTPBodyParts; @property (readwrite, nonatomic, strong) NSEnumerator *HTTPBodyPartEnumerator; @property (readwrite, nonatomic, strong) AFHTTPBodyPart *currentHTTPBodyPart; @property (readwrite, nonatomic, strong) NSOutputStream *outputStream; @property (readwrite, nonatomic, strong) NSMutableData *buffer; @end @implementation AFMultipartBodyStream #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wimplicit-atomic-properties" #if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1100) @synthesize delegate; #endif @synthesize streamStatus; @synthesize streamError; #pragma clang diagnostic pop - (id)initWithStringEncoding:(NSStringEncoding)encoding { self = [super init]; if (!self) { return nil; } self.stringEncoding = encoding; self.HTTPBodyParts = [NSMutableArray array]; self.numberOfBytesInPacket = NSIntegerMax; return self; } - (void)setInitialAndFinalBoundaries { if ([self.HTTPBodyParts count] > 0) { for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) { bodyPart.hasInitialBoundary = NO; bodyPart.hasFinalBoundary = NO; } [[self.HTTPBodyParts firstObject] setHasInitialBoundary:YES]; [[self.HTTPBodyParts lastObject] setHasFinalBoundary:YES]; } } - (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart { [self.HTTPBodyParts addObject:bodyPart]; } - (BOOL)isEmpty { return [self.HTTPBodyParts count] == 0; } #pragma mark - NSInputStream - (NSInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)length { if ([self streamStatus] == NSStreamStatusClosed) { return 0; } NSInteger totalNumberOfBytesRead = 0; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wgnu" while ((NSUInteger)totalNumberOfBytesRead < MIN(length, self.numberOfBytesInPacket)) { if (!self.currentHTTPBodyPart || ![self.currentHTTPBodyPart hasBytesAvailable]) { if (!(self.currentHTTPBodyPart = [self.HTTPBodyPartEnumerator nextObject])) { break; } } else { NSUInteger maxLength = length - (NSUInteger)totalNumberOfBytesRead; NSInteger numberOfBytesRead = [self.currentHTTPBodyPart read:&buffer[totalNumberOfBytesRead] maxLength:maxLength]; if (numberOfBytesRead == -1) { self.streamError = self.currentHTTPBodyPart.inputStream.streamError; break; } else { totalNumberOfBytesRead += numberOfBytesRead; if (self.delay > 0.0f) { [NSThread sleepForTimeInterval:self.delay]; } } } } #pragma clang diagnostic pop return totalNumberOfBytesRead; } - (BOOL)getBuffer:(__unused uint8_t **)buffer length:(__unused NSUInteger *)len { return NO; } - (BOOL)hasBytesAvailable { return [self streamStatus] == NSStreamStatusOpen; } #pragma mark - NSStream - (void)open { if (self.streamStatus == NSStreamStatusOpen) { return; } self.streamStatus = NSStreamStatusOpen; [self setInitialAndFinalBoundaries]; self.HTTPBodyPartEnumerator = [self.HTTPBodyParts objectEnumerator]; } - (void)close { self.streamStatus = NSStreamStatusClosed; } - (id)propertyForKey:(__unused NSString *)key { return nil; } - (BOOL)setProperty:(__unused id)property forKey:(__unused NSString *)key { return NO; } - (void)scheduleInRunLoop:(__unused NSRunLoop *)aRunLoop forMode:(__unused NSString *)mode {} - (void)removeFromRunLoop:(__unused NSRunLoop *)aRunLoop forMode:(__unused NSString *)mode {} - (unsigned long long)contentLength { unsigned long long length = 0; for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) { length += [bodyPart contentLength]; } return length; } #pragma mark - Undocumented CFReadStream Bridged Methods - (void)_scheduleInCFRunLoop:(__unused CFRunLoopRef)aRunLoop forMode:(__unused CFStringRef)aMode {} - (void)_unscheduleFromCFRunLoop:(__unused CFRunLoopRef)aRunLoop forMode:(__unused CFStringRef)aMode {} - (BOOL)_setCFClientFlags:(__unused CFOptionFlags)inFlags callback:(__unused CFReadStreamClientCallBack)inCallback context:(__unused CFStreamClientContext *)inContext { return NO; } #pragma mark - NSCopying -(id)copyWithZone:(NSZone *)zone { AFMultipartBodyStream *bodyStreamCopy = [[[self class] allocWithZone:zone] initWithStringEncoding:self.stringEncoding]; for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) { [bodyStreamCopy appendHTTPBodyPart:[bodyPart copy]]; } [bodyStreamCopy setInitialAndFinalBoundaries]; return bodyStreamCopy; } @end #pragma mark - typedef enum { AFEncapsulationBoundaryPhase = 1, AFHeaderPhase = 2, AFBodyPhase = 3, AFFinalBoundaryPhase = 4, } AFHTTPBodyPartReadPhase; @interface AFHTTPBodyPart () <NSCopying> { AFHTTPBodyPartReadPhase _phase; NSInputStream *_inputStream; unsigned long long _phaseReadOffset; } - (BOOL)transitionToNextPhase; - (NSInteger)readData:(NSData *)data intoBuffer:(uint8_t *)buffer maxLength:(NSUInteger)length; @end @implementation AFHTTPBodyPart - (id)init { self = [super init]; if (!self) { return nil; } [self transitionToNextPhase]; return self; } - (void)dealloc { if (_inputStream) { [_inputStream close]; _inputStream = nil; } } - (NSInputStream *)inputStream { if (!_inputStream) { if ([self.body isKindOfClass:[NSData class]]) { _inputStream = [NSInputStream inputStreamWithData:self.body]; } else if ([self.body isKindOfClass:[NSURL class]]) { _inputStream = [NSInputStream inputStreamWithURL:self.body]; } else if ([self.body isKindOfClass:[NSInputStream class]]) { _inputStream = self.body; } else { _inputStream = [NSInputStream inputStreamWithData:[NSData data]]; } } return _inputStream; } - (NSString *)stringForHeaders { NSMutableString *headerString = [NSMutableString string]; for (NSString *field in [self.headers allKeys]) { [headerString appendString:[NSString stringWithFormat:@"%@: %@%@", field, [self.headers valueForKey:field], kAFMultipartFormCRLF]]; } [headerString appendString:kAFMultipartFormCRLF]; return [NSString stringWithString:headerString]; } - (unsigned long long)contentLength { unsigned long long length = 0; NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? AFMultipartFormInitialBoundary(self.boundary) : AFMultipartFormEncapsulationBoundary(self.boundary)) dataUsingEncoding:self.stringEncoding]; length += [encapsulationBoundaryData length]; NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding]; length += [headersData length]; length += _bodyContentLength; NSData *closingBoundaryData = ([self hasFinalBoundary] ? [AFMultipartFormFinalBoundary(self.boundary) dataUsingEncoding:self.stringEncoding] : [NSData data]); length += [closingBoundaryData length]; return length; } - (BOOL)hasBytesAvailable { // Allows `read:maxLength:` to be called again if `AFMultipartFormFinalBoundary` doesn't fit into the available buffer if (_phase == AFFinalBoundaryPhase) { return YES; } #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wcovered-switch-default" switch (self.inputStream.streamStatus) { case NSStreamStatusNotOpen: case NSStreamStatusOpening: case NSStreamStatusOpen: case NSStreamStatusReading: case NSStreamStatusWriting: return YES; case NSStreamStatusAtEnd: case NSStreamStatusClosed: case NSStreamStatusError: default: return NO; } #pragma clang diagnostic pop } - (NSInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)length { NSInteger totalNumberOfBytesRead = 0; if (_phase == AFEncapsulationBoundaryPhase) { NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? AFMultipartFormInitialBoundary(self.boundary) : AFMultipartFormEncapsulationBoundary(self.boundary)) dataUsingEncoding:self.stringEncoding]; totalNumberOfBytesRead += [self readData:encapsulationBoundaryData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; } if (_phase == AFHeaderPhase) { NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding]; totalNumberOfBytesRead += [self readData:headersData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; } if (_phase == AFBodyPhase) { NSInteger numberOfBytesRead = 0; numberOfBytesRead = [self.inputStream read:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; if (numberOfBytesRead == -1) { return -1; } else { totalNumberOfBytesRead += numberOfBytesRead; if ([self.inputStream streamStatus] >= NSStreamStatusAtEnd) { [self transitionToNextPhase]; } } } if (_phase == AFFinalBoundaryPhase) { NSData *closingBoundaryData = ([self hasFinalBoundary] ? [AFMultipartFormFinalBoundary(self.boundary) dataUsingEncoding:self.stringEncoding] : [NSData data]); totalNumberOfBytesRead += [self readData:closingBoundaryData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; } return totalNumberOfBytesRead; } - (NSInteger)readData:(NSData *)data intoBuffer:(uint8_t *)buffer maxLength:(NSUInteger)length { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wgnu" NSRange range = NSMakeRange((NSUInteger)_phaseReadOffset, MIN([data length] - ((NSUInteger)_phaseReadOffset), length)); [data getBytes:buffer range:range]; #pragma clang diagnostic pop _phaseReadOffset += range.length; if (((NSUInteger)_phaseReadOffset) >= [data length]) { [self transitionToNextPhase]; } return (NSInteger)range.length; } - (BOOL)transitionToNextPhase { if (![[NSThread currentThread] isMainThread]) { dispatch_sync(dispatch_get_main_queue(), ^{ [self transitionToNextPhase]; }); return YES; } #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wcovered-switch-default" switch (_phase) { case AFEncapsulationBoundaryPhase: _phase = AFHeaderPhase; break; case AFHeaderPhase: [self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes]; [self.inputStream open]; _phase = AFBodyPhase; break; case AFBodyPhase: [self.inputStream close]; _phase = AFFinalBoundaryPhase; break; case AFFinalBoundaryPhase: default: _phase = AFEncapsulationBoundaryPhase; break; } _phaseReadOffset = 0; #pragma clang diagnostic pop return YES; } #pragma mark - NSCopying - (id)copyWithZone:(NSZone *)zone { AFHTTPBodyPart *bodyPart = [[[self class] allocWithZone:zone] init]; bodyPart.stringEncoding = self.stringEncoding; bodyPart.headers = self.headers; bodyPart.bodyContentLength = self.bodyContentLength; bodyPart.body = self.body; bodyPart.boundary = self.boundary; return bodyPart; } @end #pragma mark - @implementation AFJSONRequestSerializer + (instancetype)serializer { return [self serializerWithWritingOptions:(NSJSONWritingOptions)0]; } + (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions { AFJSONRequestSerializer *serializer = [[self alloc] init]; serializer.writingOptions = writingOptions; return serializer; } #pragma mark - AFURLRequestSerialization - (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request withParameters:(id)parameters error:(NSError *__autoreleasing *)error { NSParameterAssert(request); if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) { return [super requestBySerializingRequest:request withParameters:parameters error:error]; } NSMutableURLRequest *mutableRequest = [request mutableCopy]; [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) { if (![request valueForHTTPHeaderField:field]) { [mutableRequest setValue:value forHTTPHeaderField:field]; } }]; if (parameters) { if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) { [mutableRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; } [mutableRequest setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error]]; } return mutableRequest; } #pragma mark - NSSecureCoding - (id)initWithCoder:(NSCoder *)decoder { self = [super initWithCoder:decoder]; if (!self) { return nil; } self.writingOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(writingOptions))] unsignedIntegerValue]; return self; } - (void)encodeWithCoder:(NSCoder *)coder { [super encodeWithCoder:coder]; [coder encodeInteger:self.writingOptions forKey:NSStringFromSelector(@selector(writingOptions))]; } #pragma mark - NSCopying - (id)copyWithZone:(NSZone *)zone { AFJSONRequestSerializer *serializer = [super copyWithZone:zone]; serializer.writingOptions = self.writingOptions; return serializer; } @end #pragma mark - @implementation AFPropertyListRequestSerializer + (instancetype)serializer { return [self serializerWithFormat:NSPropertyListXMLFormat_v1_0 writeOptions:0]; } + (instancetype)serializerWithFormat:(NSPropertyListFormat)format writeOptions:(NSPropertyListWriteOptions)writeOptions { AFPropertyListRequestSerializer *serializer = [[self alloc] init]; serializer.format = format; serializer.writeOptions = writeOptions; return serializer; } #pragma mark - AFURLRequestSerializer - (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request withParameters:(id)parameters error:(NSError *__autoreleasing *)error { NSParameterAssert(request); if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) { return [super requestBySerializingRequest:request withParameters:parameters error:error]; } NSMutableURLRequest *mutableRequest = [request mutableCopy]; [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) { if (![request valueForHTTPHeaderField:field]) { [mutableRequest setValue:value forHTTPHeaderField:field]; } }]; if (parameters) { if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) { [mutableRequest setValue:@"application/x-plist" forHTTPHeaderField:@"Content-Type"]; } [mutableRequest setHTTPBody:[NSPropertyListSerialization dataWithPropertyList:parameters format:self.format options:self.writeOptions error:error]]; } return mutableRequest; } #pragma mark - NSSecureCoding - (id)initWithCoder:(NSCoder *)decoder { self = [super initWithCoder:decoder]; if (!self) { return nil; } self.format = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue]; self.writeOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(writeOptions))] unsignedIntegerValue]; return self; } - (void)encodeWithCoder:(NSCoder *)coder { [super encodeWithCoder:coder]; [coder encodeInteger:self.format forKey:NSStringFromSelector(@selector(format))]; [coder encodeObject:@(self.writeOptions) forKey:NSStringFromSelector(@selector(writeOptions))]; } #pragma mark - NSCopying - (id)copyWithZone:(NSZone *)zone { AFPropertyListRequestSerializer *serializer = [super copyWithZone:zone]; serializer.format = self.format; serializer.writeOptions = self.writeOptions; return serializer; } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.h
C/C++ Header
// AFURLResponseSerialization.h // Copyright (c) 2011–2015 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 /** 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; @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; /** The string encoding used to serialize data received from the server, when no string encoding is specified by the response. `NSUTF8StringEncoding` by default. */ @property (nonatomic, assign) NSStringEncoding stringEncoding; /** 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 *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` */ @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 `NSJSONSerialization` documentation section "NSJSONReadingOptions". `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 defined(__IPHONE_OS_VERSION_MIN_REQUIRED) /** 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 *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 *)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`. */ extern 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`. */ extern NSString * const AFNetworkingOperationFailingURLResponseErrorKey; extern NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey; NS_ASSUME_NONNULL_END
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.m
Objective-C
// AFURLResponseSerialization.m // Copyright (c) 2011–2015 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" #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; } static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingOptions readingOptions) { if ([JSONObject isKindOfClass:[NSArray class]]) { NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:[(NSArray *)JSONObject count]]; for (id value in (NSArray *)JSONObject) { [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.stringEncoding = NSUTF8StringEncoding; 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 && [response isKindOfClass:[NSHTTPURLResponse class]]) { if (self.acceptableContentTypes && ![self.acceptableContentTypes containsObject:[response MIMEType]]) { 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; } - (id)initWithCoder:(NSCoder *)decoder { self = [self init]; if (!self) { return nil; } self.acceptableStatusCodes = [decoder decodeObjectOfClass:[NSIndexSet class] forKey:NSStringFromSelector(@selector(acceptableStatusCodes))]; self.acceptableContentTypes = [decoder decodeObjectOfClass:[NSIndexSet 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 - (id)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 NSStringEncoding stringEncoding = self.stringEncoding; if (response.textEncodingName) { CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)response.textEncodingName); if (encoding != kCFStringEncodingInvalidId) { stringEncoding = CFStringConvertEncodingToNSStringEncoding(encoding); } } id responseObject = nil; NSError *serializationError = nil; @autoreleasepool { NSString *responseString = [[NSString alloc] initWithData:data encoding:stringEncoding]; if (responseString && ![responseString isEqualToString:@" "]) { // Workaround for a bug in NSJSONSerialization when Unicode character escape codes are used instead of the actual character // See http://stackoverflow.com/a/12843465/157142 data = [responseString dataUsingEncoding:NSUTF8StringEncoding]; if (data) { if ([data length] > 0) { responseObject = [NSJSONSerialization JSONObjectWithData:data options:self.readingOptions error:&serializationError]; } else { return nil; } } else { NSDictionary *userInfo = @{ NSLocalizedDescriptionKey: NSLocalizedStringFromTable(@"Data failed decoding as a UTF-8 string", @"AFNetworking", nil), NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Could not decode string: %@", @"AFNetworking", nil), responseString] }; serializationError = [NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo]; } } } if (self.removesKeysWithNullValues && responseObject) { responseObject = AFJSONObjectByRemovingKeysWithNullValues(responseObject, self.readingOptions); } if (error) { *error = AFErrorWithUnderlyingError(serializationError, *error); } return responseObject; } #pragma mark - NSSecureCoding - (id)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 - (id)copyWithZone:(NSZone *)zone { AFJSONResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; 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 (error) { *error = AFErrorWithUnderlyingError(serializationError, *error); } return document; } #pragma mark - NSSecureCoding - (id)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 - (id)copyWithZone:(NSZone *)zone { AFXMLDocumentResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; 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; } } id responseObject; NSError *serializationError = nil; if (data) { responseObject = [NSPropertyListSerialization propertyListWithData:data options:self.readOptions format:NULL error:&serializationError]; } if (error) { *error = AFErrorWithUnderlyingError(serializationError, *error); } return responseObject; } #pragma mark - NSSecureCoding - (id)initWithCoder:(NSCoder *)decoder { self = [super initWithCoder:decoder]; if (!self) { return nil; } self.format = [[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 - (id)copyWithZone:(NSZone *)zone { AFPropertyListResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; serializer.format = self.format; serializer.readOptions = self.readOptions; return serializer; } @end #pragma mark - #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #import <CoreGraphics/CoreGraphics.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 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 defined(__IPHONE_OS_VERSION_MIN_REQUIRED) if (self.automaticallyInflatesResponseImage) { return AFInflatedImageFromResponseWithDataAtScale((NSHTTPURLResponse *)response, data, self.imageScale); } else { return AFImageWithDataAtScale(data, self.imageScale); } #elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) // 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 - (id)initWithCoder:(NSCoder *)decoder { self = [super initWithCoder:decoder]; if (!self) { return nil; } #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) 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 defined(__IPHONE_OS_VERSION_MIN_REQUIRED) [coder encodeObject:@(self.imageScale) forKey:NSStringFromSelector(@selector(imageScale))]; [coder encodeBool:self.automaticallyInflatesResponseImage forKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))]; #endif } #pragma mark - NSCopying - (id)copyWithZone:(NSZone *)zone { AFImageResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) 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 - (id)initWithCoder:(NSCoder *)decoder { self = [super initWithCoder:decoder]; if (!self) { return nil; } self.responseSerializers = [decoder decodeObjectOfClass:[NSArray class] forKey:NSStringFromSelector(@selector(responseSerializers))]; return self; } - (void)encodeWithCoder:(NSCoder *)coder { [super encodeWithCoder:coder]; [coder encodeObject:self.responseSerializers forKey:NSStringFromSelector(@selector(responseSerializers))]; } #pragma mark - NSCopying - (id)copyWithZone:(NSZone *)zone { AFCompoundResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; serializer.responseSerializers = self.responseSerializers; return serializer; } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/AFNetworking/AFNetworking/AFURLSessionManager.h
C/C++ Header
// AFURLSessionManager.h // Copyright (c) 2011–2015 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" #if !TARGET_OS_WATCH #import "AFNetworkReachabilityManager.h" #endif #ifndef NS_DESIGNATED_INITIALIZER #if __has_attribute(objc_designated_initializer) #define NS_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer)) #else #define NS_DESIGNATED_INITIALIZER #endif #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:didCompleteWithError:` ### `NSURLSessionDataDelegate` - `URLSession:dataTask:didReceiveResponse:completionHandler:` - `URLSession:dataTask:didBecomeDownloadTask:` - `URLSession:dataTask:didReceiveData:` - `URLSession:dataTask:willCacheResponse:completionHandler:` ### `NSURLSessionDownloadDelegate` - `URLSession:downloadTask:didFinishDownloadingToURL:` - `URLSession:downloadTask:didWriteData:totalBytesWritten: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 #if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) || TARGET_OS_WATCH @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 request operations 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 *tasks; /** The data tasks currently run by the managed session. */ @property (readonly, nonatomic, strong) NSArray *dataTasks; /** The upload tasks currently run by the managed session. */ @property (readonly, nonatomic, strong) NSArray *uploadTasks; /** The download tasks currently run by the managed session. */ @property (readonly, nonatomic, strong) NSArray *downloadTasks; ///------------------------------- /// @name Managing Callback Queues ///------------------------------- /** The dispatch queue for `completionBlock`. If `NULL` (default), the main queue is used. */ #if OS_OBJECT_HAVE_OBJC_SUPPORT @property (nonatomic, strong, nullable) dispatch_queue_t completionQueue; #else @property (nonatomic, assign, nullable) dispatch_queue_t completionQueue; #endif /** The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used. */ #if OS_OBJECT_HAVE_OBJC_SUPPORT @property (nonatomic, strong, nullable) dispatch_group_t completionGroup; #else @property (nonatomic, assign, nullable) dispatch_group_t completionGroup; #endif ///--------------------------------- /// @name Working Around System Bugs ///--------------------------------- /** Whether to attempt to retry creation of upload tasks for background sessions when initial call returns `nil`. `NO` by default. @bug As of iOS 7.0, there is a bug where upload tasks created for background tasks are sometimes `nil`. As a workaround, if this property is `YES`, AFNetworking will follow Apple's recommendation to try creating the task again. @see https://github.com/AFNetworking/AFNetworking/issues/1675 */ @property (nonatomic, assign) BOOL attemptsToRecreateUploadTasksForBackgroundSessions; ///--------------------- /// @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. @param cancelPendingTasks Whether or not to cancel pending tasks. */ - (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks; ///------------------------- /// @name Running Data Tasks ///------------------------- /** Creates an `NSURLSessionDataTask` with the specified request. @param request The HTTP request for the request. @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 completionHandler:(nullable void (^)(NSURLResponse *response, id responseObject, NSError *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 progress A progress object monitoring the current upload progress. @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:(NSProgress * __nullable __autoreleasing * __nullable)progress completionHandler:(nullable void (^)(NSURLResponse *response, id responseObject, NSError *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 progress A progress object monitoring the current upload progress. @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:(NSProgress * __nullable __autoreleasing * __nullable)progress completionHandler:(nullable void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler; /** Creates an `NSURLSessionUploadTask` with the specified streaming request. @param request The HTTP request for the request. @param progress A progress object monitoring the current upload progress. @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:(NSProgress * __nullable __autoreleasing * __nullable)progress completionHandler:(nullable void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler; ///----------------------------- /// @name Running Download Tasks ///----------------------------- /** Creates an `NSURLSessionDownloadTask` with the specified request. @param request The HTTP request for the request. @param progress A progress object monitoring the current download progress. @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:(NSProgress * __nullable __autoreleasing * __nullable)progress destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination completionHandler:(nullable void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler; /** Creates an `NSURLSessionDownloadTask` with the specified resume data. @param resumeData The data used to resume downloading. @param progress A progress object monitoring the current download progress. @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:(NSProgress * __nullable __autoreleasing * __nullable)progress destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination completionHandler:(nullable void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler; ///--------------------------------- /// @name Getting Progress for Tasks ///--------------------------------- /** Returns the upload progress of the specified task. @param uploadTask The session upload 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:(NSURLSessionUploadTask *)uploadTask; /** Returns the download progress of the specified task. @param downloadTask The session download 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:(NSURLSessionDownloadTask *)downloadTask; ///----------------------------------------- /// @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. */ - (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 * (^)(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 block A block object to be executed when a session task has received a request specific authentication challenge. The block returns the disposition of the authentication challenge, and takes four arguments: the session, the task, the authentication challenge, and a pointer to the credential that should be used to resolve the challenge. */ - (void)setTaskDidReceiveAuthenticationChallengeBlock:(nullable NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * __nullable __autoreleasing * __nullable credential))block; /** 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 *error))block; ///------------------------------------------- /// @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; ///----------------------------------------------- /// @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 * (^)(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: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 #endif ///-------------------- /// @name Notifications ///-------------------- /** Posted when a task begins executing. @deprecated Use `AFNetworkingTaskDidResumeNotification` instead. */ extern NSString * const AFNetworkingTaskDidStartNotification DEPRECATED_ATTRIBUTE; /** Posted when a task resumes. */ extern NSString * const AFNetworkingTaskDidResumeNotification; /** Posted when a task finishes executing. Includes a userInfo dictionary with additional information about the task. @deprecated Use `AFNetworkingTaskDidCompleteNotification` instead. */ extern NSString * const AFNetworkingTaskDidFinishNotification DEPRECATED_ATTRIBUTE; /** Posted when a task finishes executing. Includes a userInfo dictionary with additional information about the task. */ extern NSString * const AFNetworkingTaskDidCompleteNotification; /** Posted when a task suspends its execution. */ extern NSString * const AFNetworkingTaskDidSuspendNotification; /** Posted when a session is invalidated. */ extern NSString * const AFURLSessionDidInvalidateNotification; /** Posted when a session download task encountered an error when moving the temporary download file to a specified destination. */ extern NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification; /** The raw response data of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if response data exists for the task. @deprecated Use `AFNetworkingTaskDidCompleteResponseDataKey` instead. */ extern NSString * const AFNetworkingTaskDidFinishResponseDataKey DEPRECATED_ATTRIBUTE; /** The raw response data of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if response data exists for the task. */ extern NSString * const AFNetworkingTaskDidCompleteResponseDataKey; /** The serialized response object of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if the response was serialized. @deprecated Use `AFNetworkingTaskDidCompleteSerializedResponseKey` instead. */ extern NSString * const AFNetworkingTaskDidFinishSerializedResponseKey DEPRECATED_ATTRIBUTE; /** The serialized response object of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if the response was serialized. */ extern NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey; /** The response serializer used to serialize the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if the task has an associated response serializer. @deprecated Use `AFNetworkingTaskDidCompleteResponseSerializerKey` instead. */ extern NSString * const AFNetworkingTaskDidFinishResponseSerializerKey DEPRECATED_ATTRIBUTE; /** The response serializer used to serialize the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if the task has an associated response serializer. */ extern NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey; /** The file path associated with the download task. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if an the response data has been stored directly to disk. @deprecated Use `AFNetworkingTaskDidCompleteAssetPathKey` instead. */ extern NSString * const AFNetworkingTaskDidFinishAssetPathKey DEPRECATED_ATTRIBUTE; /** The file path associated with the download task. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if an the response data has been stored directly to disk. */ extern NSString * const AFNetworkingTaskDidCompleteAssetPathKey; /** Any error associated with the task, or the serialization of the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if an error exists. @deprecated Use `AFNetworkingTaskDidCompleteErrorKey` instead. */ extern NSString * const AFNetworkingTaskDidFinishErrorKey DEPRECATED_ATTRIBUTE; /** Any error associated with the task, or the serialization of the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if an error exists. */ extern NSString * const AFNetworkingTaskDidCompleteErrorKey; NS_ASSUME_NONNULL_END
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/AFNetworking/AFNetworking/AFURLSessionManager.m
Objective-C
// AFURLSessionManager.m // Copyright (c) 2011–2015 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 "AFURLSessionManager.h" #import <objc/runtime.h> #if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) static dispatch_queue_t url_session_manager_creation_queue() { static dispatch_queue_t af_url_session_manager_creation_queue; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ af_url_session_manager_creation_queue = dispatch_queue_create("com.alamofire.networking.session.manager.creation", DISPATCH_QUEUE_SERIAL); }); return af_url_session_manager_creation_queue; } static dispatch_queue_t url_session_manager_processing_queue() { static dispatch_queue_t af_url_session_manager_processing_queue; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ af_url_session_manager_processing_queue = dispatch_queue_create("com.alamofire.networking.session.manager.processing", DISPATCH_QUEUE_CONCURRENT); }); return af_url_session_manager_processing_queue; } static dispatch_group_t url_session_manager_completion_group() { static dispatch_group_t af_url_session_manager_completion_group; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ af_url_session_manager_completion_group = dispatch_group_create(); }); return af_url_session_manager_completion_group; } NSString * const AFNetworkingTaskDidResumeNotification = @"com.alamofire.networking.task.resume"; NSString * const AFNetworkingTaskDidCompleteNotification = @"com.alamofire.networking.task.complete"; NSString * const AFNetworkingTaskDidSuspendNotification = @"com.alamofire.networking.task.suspend"; NSString * const AFURLSessionDidInvalidateNotification = @"com.alamofire.networking.session.invalidate"; NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification = @"com.alamofire.networking.session.download.file-manager-error"; NSString * const AFNetworkingTaskDidStartNotification = @"com.alamofire.networking.task.resume"; // Deprecated NSString * const AFNetworkingTaskDidFinishNotification = @"com.alamofire.networking.task.complete"; // Deprecated NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey = @"com.alamofire.networking.task.complete.serializedresponse"; NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey = @"com.alamofire.networking.task.complete.responseserializer"; NSString * const AFNetworkingTaskDidCompleteResponseDataKey = @"com.alamofire.networking.complete.finish.responsedata"; NSString * const AFNetworkingTaskDidCompleteErrorKey = @"com.alamofire.networking.task.complete.error"; NSString * const AFNetworkingTaskDidCompleteAssetPathKey = @"com.alamofire.networking.task.complete.assetpath"; NSString * const AFNetworkingTaskDidFinishSerializedResponseKey = @"com.alamofire.networking.task.complete.serializedresponse"; // Deprecated NSString * const AFNetworkingTaskDidFinishResponseSerializerKey = @"com.alamofire.networking.task.complete.responseserializer"; // Deprecated NSString * const AFNetworkingTaskDidFinishResponseDataKey = @"com.alamofire.networking.complete.finish.responsedata"; // Deprecated NSString * const AFNetworkingTaskDidFinishErrorKey = @"com.alamofire.networking.task.complete.error"; // Deprecated NSString * const AFNetworkingTaskDidFinishAssetPathKey = @"com.alamofire.networking.task.complete.assetpath"; // Deprecated static NSString * const AFURLSessionManagerLockName = @"com.alamofire.networking.session.manager.lock"; static NSUInteger const AFMaximumNumberOfAttemptsToRecreateBackgroundSessionUploadTask = 3; static void * AFTaskStateChangedContext = &AFTaskStateChangedContext; typedef void (^AFURLSessionDidBecomeInvalidBlock)(NSURLSession *session, NSError *error); typedef NSURLSessionAuthChallengeDisposition (^AFURLSessionDidReceiveAuthenticationChallengeBlock)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential); typedef NSURLRequest * (^AFURLSessionTaskWillPerformHTTPRedirectionBlock)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request); typedef NSURLSessionAuthChallengeDisposition (^AFURLSessionTaskDidReceiveAuthenticationChallengeBlock)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential); typedef void (^AFURLSessionDidFinishEventsForBackgroundURLSessionBlock)(NSURLSession *session); typedef NSInputStream * (^AFURLSessionTaskNeedNewBodyStreamBlock)(NSURLSession *session, NSURLSessionTask *task); typedef void (^AFURLSessionTaskDidSendBodyDataBlock)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend); typedef void (^AFURLSessionTaskDidCompleteBlock)(NSURLSession *session, NSURLSessionTask *task, NSError *error); typedef NSURLSessionResponseDisposition (^AFURLSessionDataTaskDidReceiveResponseBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response); typedef void (^AFURLSessionDataTaskDidBecomeDownloadTaskBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask); typedef void (^AFURLSessionDataTaskDidReceiveDataBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data); typedef NSCachedURLResponse * (^AFURLSessionDataTaskWillCacheResponseBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse); typedef NSURL * (^AFURLSessionDownloadTaskDidFinishDownloadingBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location); typedef void (^AFURLSessionDownloadTaskDidWriteDataBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite); typedef void (^AFURLSessionDownloadTaskDidResumeBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes); typedef void (^AFURLSessionTaskCompletionHandler)(NSURLResponse *response, id responseObject, NSError *error); #pragma mark - @interface AFURLSessionManagerTaskDelegate : NSObject <NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate> @property (nonatomic, weak) AFURLSessionManager *manager; @property (nonatomic, strong) NSMutableData *mutableData; @property (nonatomic, strong) NSProgress *progress; @property (nonatomic, copy) NSURL *downloadFileURL; @property (nonatomic, copy) AFURLSessionDownloadTaskDidFinishDownloadingBlock downloadTaskDidFinishDownloading; @property (nonatomic, copy) AFURLSessionTaskCompletionHandler completionHandler; @end @implementation AFURLSessionManagerTaskDelegate - (instancetype)init { self = [super init]; if (!self) { return nil; } self.mutableData = [NSMutableData data]; self.progress = [NSProgress progressWithTotalUnitCount:0]; return self; } #pragma mark - NSURLSessionTaskDelegate - (void)URLSession:(__unused NSURLSession *)session task:(__unused NSURLSessionTask *)task didSendBodyData:(__unused int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend { self.progress.totalUnitCount = totalBytesExpectedToSend; self.progress.completedUnitCount = totalBytesSent; } - (void)URLSession:(__unused NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wgnu" __strong AFURLSessionManager *manager = self.manager; __block id responseObject = nil; __block NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; userInfo[AFNetworkingTaskDidCompleteResponseSerializerKey] = manager.responseSerializer; //Performance Improvement from #2672 NSData *data = nil; if (self.mutableData) { data = [self.mutableData copy]; //We no longer need the reference, so nil it out to gain back some memory. self.mutableData = nil; } if (self.downloadFileURL) { userInfo[AFNetworkingTaskDidCompleteAssetPathKey] = self.downloadFileURL; } else if (data) { userInfo[AFNetworkingTaskDidCompleteResponseDataKey] = data; } if (error) { userInfo[AFNetworkingTaskDidCompleteErrorKey] = error; dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{ if (self.completionHandler) { self.completionHandler(task.response, responseObject, error); } dispatch_async(dispatch_get_main_queue(), ^{ [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo]; }); }); } else { dispatch_async(url_session_manager_processing_queue(), ^{ NSError *serializationError = nil; responseObject = [manager.responseSerializer responseObjectForResponse:task.response data:data error:&serializationError]; if (self.downloadFileURL) { responseObject = self.downloadFileURL; } if (responseObject) { userInfo[AFNetworkingTaskDidCompleteSerializedResponseKey] = responseObject; } if (serializationError) { userInfo[AFNetworkingTaskDidCompleteErrorKey] = serializationError; } dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{ if (self.completionHandler) { self.completionHandler(task.response, responseObject, serializationError); } dispatch_async(dispatch_get_main_queue(), ^{ [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo]; }); }); }); } #pragma clang diagnostic pop } #pragma mark - NSURLSessionDataTaskDelegate - (void)URLSession:(__unused NSURLSession *)session dataTask:(__unused NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { [self.mutableData appendData:data]; } #pragma mark - NSURLSessionDownloadTaskDelegate - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location { NSError *fileManagerError = nil; self.downloadFileURL = nil; if (self.downloadTaskDidFinishDownloading) { self.downloadFileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location); if (self.downloadFileURL) { [[NSFileManager defaultManager] moveItemAtURL:location toURL:self.downloadFileURL error:&fileManagerError]; if (fileManagerError) { [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:fileManagerError.userInfo]; } } } } - (void)URLSession:(__unused NSURLSession *)session downloadTask:(__unused NSURLSessionDownloadTask *)downloadTask didWriteData:(__unused int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite { self.progress.totalUnitCount = totalBytesExpectedToWrite; self.progress.completedUnitCount = totalBytesWritten; } - (void)URLSession:(__unused NSURLSession *)session downloadTask:(__unused NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes { self.progress.totalUnitCount = expectedTotalBytes; self.progress.completedUnitCount = fileOffset; } @end #pragma mark - /** * A workaround for issues related to key-value observing the `state` of an `NSURLSessionTask`. * * See: * - https://github.com/AFNetworking/AFNetworking/issues/1477 * - https://github.com/AFNetworking/AFNetworking/issues/2638 * - https://github.com/AFNetworking/AFNetworking/pull/2702 */ static inline void af_swizzleSelector(Class class, SEL originalSelector, SEL swizzledSelector) { Method originalMethod = class_getInstanceMethod(class, originalSelector); Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector); method_exchangeImplementations(originalMethod, swizzledMethod); } static inline BOOL af_addMethod(Class class, SEL selector, Method method) { return class_addMethod(class, selector, method_getImplementation(method), method_getTypeEncoding(method)); } static NSString * const AFNSURLSessionTaskDidResumeNotification = @"com.alamofire.networking.nsurlsessiontask.resume"; static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofire.networking.nsurlsessiontask.suspend"; @interface _AFURLSessionTaskSwizzling : NSObject @end @implementation _AFURLSessionTaskSwizzling + (void)load { /** WARNING: Trouble Ahead https://github.com/AFNetworking/AFNetworking/pull/2702 */ if (NSClassFromString(@"NSURLSessionTask")) { /** iOS 7 and iOS 8 differ in NSURLSessionTask implementation, which makes the next bit of code a bit tricky. Many Unit Tests have been built to validate as much of this behavior has possible. Here is what we know: - NSURLSessionTasks are implemented with class clusters, meaning the class you request from the API isn't actually the type of class you will get back. - Simply referencing `[NSURLSessionTask class]` will not work. You need to ask an `NSURLSession` to actually create an object, and grab the class from there. - On iOS 7, `localDataTask` is a `__NSCFLocalDataTask`, which inherits from `__NSCFLocalSessionTask`, which inherits from `__NSCFURLSessionTask`. - On iOS 8, `localDataTask` is a `__NSCFLocalDataTask`, which inherits from `__NSCFLocalSessionTask`, which inherits from `NSURLSessionTask`. - On iOS 7, `__NSCFLocalSessionTask` and `__NSCFURLSessionTask` are the only two classes that have their own implementations of `resume` and `suspend`, and `__NSCFLocalSessionTask` DOES NOT CALL SUPER. This means both classes need to be swizzled. - On iOS 8, `NSURLSessionTask` is the only class that implements `resume` and `suspend`. This means this is the only class that needs to be swizzled. - Because `NSURLSessionTask` is not involved in the class hierarchy for every version of iOS, its easier to add the swizzled methods to a dummy class and manage them there. Some Assumptions: - No implementations of `resume` or `suspend` call super. If this were to change in a future version of iOS, we'd need to handle it. - No background task classes override `resume` or `suspend` The current solution: 1) Grab an instance of `__NSCFLocalDataTask` by asking an instance of `NSURLSession` for a data task. 2) Grab a pointer to the original implementation of `af_resume` 3) Check to see if the current class has an implementation of resume. If so, continue to step 4. 4) Grab the super class of the current class. 5) Grab a pointer for the current class to the current implementation of `resume`. 6) Grab a pointer for the super class to the current implementation of `resume`. 7) If the current class implementation of `resume` is not equal to the super class implementation of `resume` AND the current implementation of `resume` is not equal to the original implementation of `af_resume`, THEN swizzle the methods 8) Set the current class to the super class, and repeat steps 3-8 */ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wnonnull" NSURLSessionDataTask *localDataTask = [[NSURLSession sessionWithConfiguration:nil] dataTaskWithURL:nil]; #pragma clang diagnostic pop IMP originalAFResumeIMP = method_getImplementation(class_getInstanceMethod([_AFURLSessionTaskSwizzling class], @selector(af_resume))); Class currentClass = [localDataTask class]; while (class_getInstanceMethod(currentClass, @selector(resume))) { Class superClass = [currentClass superclass]; IMP classResumeIMP = method_getImplementation(class_getInstanceMethod(currentClass, @selector(resume))); IMP superclassResumeIMP = method_getImplementation(class_getInstanceMethod(superClass, @selector(resume))); if (classResumeIMP != superclassResumeIMP && originalAFResumeIMP != classResumeIMP) { [self swizzleResumeAndSuspendMethodForClass:currentClass]; } currentClass = [currentClass superclass]; } [localDataTask cancel]; } } + (void)swizzleResumeAndSuspendMethodForClass:(Class)class { Method afResumeMethod = class_getInstanceMethod(self, @selector(af_resume)); Method afSuspendMethod = class_getInstanceMethod(self, @selector(af_suspend)); af_addMethod(class, @selector(af_resume), afResumeMethod); af_addMethod(class, @selector(af_suspend), afSuspendMethod); af_swizzleSelector(class, @selector(resume), @selector(af_resume)); af_swizzleSelector(class, @selector(suspend), @selector(af_suspend)); } - (NSURLSessionTaskState)state { NSAssert(NO, @"State method should never be called in the actual dummy class"); return NSURLSessionTaskStateCanceling; } - (void)af_resume { NSAssert([self respondsToSelector:@selector(state)], @"Does not respond to state"); NSURLSessionTaskState state = [self state]; [self af_resume]; if (state != NSURLSessionTaskStateRunning) { [[NSNotificationCenter defaultCenter] postNotificationName:AFNSURLSessionTaskDidResumeNotification object:self]; } } - (void)af_suspend { NSAssert([self respondsToSelector:@selector(state)], @"Does not respond to state"); NSURLSessionTaskState state = [self state]; [self af_suspend]; if (state != NSURLSessionTaskStateSuspended) { [[NSNotificationCenter defaultCenter] postNotificationName:AFNSURLSessionTaskDidSuspendNotification object:self]; } } @end #pragma mark - @interface AFURLSessionManager () @property (readwrite, nonatomic, strong) NSURLSessionConfiguration *sessionConfiguration; @property (readwrite, nonatomic, strong) NSOperationQueue *operationQueue; @property (readwrite, nonatomic, strong) NSURLSession *session; @property (readwrite, nonatomic, strong) NSMutableDictionary *mutableTaskDelegatesKeyedByTaskIdentifier; @property (readonly, nonatomic, copy) NSString *taskDescriptionForSessionTasks; @property (readwrite, nonatomic, strong) NSLock *lock; @property (readwrite, nonatomic, copy) AFURLSessionDidBecomeInvalidBlock sessionDidBecomeInvalid; @property (readwrite, nonatomic, copy) AFURLSessionDidReceiveAuthenticationChallengeBlock sessionDidReceiveAuthenticationChallenge; @property (readwrite, nonatomic, copy) AFURLSessionDidFinishEventsForBackgroundURLSessionBlock didFinishEventsForBackgroundURLSession; @property (readwrite, nonatomic, copy) AFURLSessionTaskWillPerformHTTPRedirectionBlock taskWillPerformHTTPRedirection; @property (readwrite, nonatomic, copy) AFURLSessionTaskDidReceiveAuthenticationChallengeBlock taskDidReceiveAuthenticationChallenge; @property (readwrite, nonatomic, copy) AFURLSessionTaskNeedNewBodyStreamBlock taskNeedNewBodyStream; @property (readwrite, nonatomic, copy) AFURLSessionTaskDidSendBodyDataBlock taskDidSendBodyData; @property (readwrite, nonatomic, copy) AFURLSessionTaskDidCompleteBlock taskDidComplete; @property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidReceiveResponseBlock dataTaskDidReceiveResponse; @property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidBecomeDownloadTaskBlock dataTaskDidBecomeDownloadTask; @property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidReceiveDataBlock dataTaskDidReceiveData; @property (readwrite, nonatomic, copy) AFURLSessionDataTaskWillCacheResponseBlock dataTaskWillCacheResponse; @property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidFinishDownloadingBlock downloadTaskDidFinishDownloading; @property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidWriteDataBlock downloadTaskDidWriteData; @property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidResumeBlock downloadTaskDidResume; @end @implementation AFURLSessionManager - (instancetype)init { return [self initWithSessionConfiguration:nil]; } - (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration { self = [super init]; if (!self) { return nil; } if (!configuration) { configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; } self.sessionConfiguration = configuration; self.operationQueue = [[NSOperationQueue alloc] init]; self.operationQueue.maxConcurrentOperationCount = 1; self.session = [NSURLSession sessionWithConfiguration:self.sessionConfiguration delegate:self delegateQueue:self.operationQueue]; self.responseSerializer = [AFJSONResponseSerializer serializer]; self.securityPolicy = [AFSecurityPolicy defaultPolicy]; #if !TARGET_OS_WATCH self.reachabilityManager = [AFNetworkReachabilityManager sharedManager]; #endif self.mutableTaskDelegatesKeyedByTaskIdentifier = [[NSMutableDictionary alloc] init]; self.lock = [[NSLock alloc] init]; self.lock.name = AFURLSessionManagerLockName; [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) { for (NSURLSessionDataTask *task in dataTasks) { [self addDelegateForDataTask:task completionHandler:nil]; } for (NSURLSessionUploadTask *uploadTask in uploadTasks) { [self addDelegateForUploadTask:uploadTask progress:nil completionHandler:nil]; } for (NSURLSessionDownloadTask *downloadTask in downloadTasks) { [self addDelegateForDownloadTask:downloadTask progress:nil destination:nil completionHandler:nil]; } }]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidResume:) name:AFNSURLSessionTaskDidResumeNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidSuspend:) name:AFNSURLSessionTaskDidSuspendNotification object:nil]; return self; } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; } #pragma mark - - (NSString *)taskDescriptionForSessionTasks { return [NSString stringWithFormat:@"%p", self]; } - (void)taskDidResume:(NSNotification *)notification { NSURLSessionTask *task = notification.object; if ([task respondsToSelector:@selector(taskDescription)]) { if ([task.taskDescription isEqualToString:self.taskDescriptionForSessionTasks]) { dispatch_async(dispatch_get_main_queue(), ^{ [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidResumeNotification object:task]; }); } } } - (void)taskDidSuspend:(NSNotification *)notification { NSURLSessionTask *task = notification.object; if ([task respondsToSelector:@selector(taskDescription)]) { if ([task.taskDescription isEqualToString:self.taskDescriptionForSessionTasks]) { dispatch_async(dispatch_get_main_queue(), ^{ [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidSuspendNotification object:task]; }); } } } #pragma mark - - (AFURLSessionManagerTaskDelegate *)delegateForTask:(NSURLSessionTask *)task { NSParameterAssert(task); AFURLSessionManagerTaskDelegate *delegate = nil; [self.lock lock]; delegate = self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)]; [self.lock unlock]; return delegate; } - (void)setDelegate:(AFURLSessionManagerTaskDelegate *)delegate forTask:(NSURLSessionTask *)task { NSParameterAssert(task); NSParameterAssert(delegate); [self.lock lock]; self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)] = delegate; [self.lock unlock]; } - (void)addDelegateForDataTask:(NSURLSessionDataTask *)dataTask completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler { AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] init]; delegate.manager = self; delegate.completionHandler = completionHandler; dataTask.taskDescription = self.taskDescriptionForSessionTasks; [self setDelegate:delegate forTask:dataTask]; } - (void)addDelegateForUploadTask:(NSURLSessionUploadTask *)uploadTask progress:(NSProgress * __autoreleasing *)progress completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler { AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] init]; delegate.manager = self; delegate.completionHandler = completionHandler; int64_t totalUnitCount = uploadTask.countOfBytesExpectedToSend; if(totalUnitCount == NSURLSessionTransferSizeUnknown) { NSString *contentLength = [uploadTask.originalRequest valueForHTTPHeaderField:@"Content-Length"]; if(contentLength) { totalUnitCount = (int64_t)[contentLength longLongValue]; } } if (delegate.progress) { delegate.progress.totalUnitCount = totalUnitCount; } else { delegate.progress = [NSProgress progressWithTotalUnitCount:totalUnitCount]; } delegate.progress.pausingHandler = ^{ [uploadTask suspend]; }; delegate.progress.cancellationHandler = ^{ [uploadTask cancel]; }; if (progress) { *progress = delegate.progress; } uploadTask.taskDescription = self.taskDescriptionForSessionTasks; [self setDelegate:delegate forTask:uploadTask]; } - (void)addDelegateForDownloadTask:(NSURLSessionDownloadTask *)downloadTask progress:(NSProgress * __autoreleasing *)progress destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler { AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] init]; delegate.manager = self; delegate.completionHandler = completionHandler; if (destination) { delegate.downloadTaskDidFinishDownloading = ^NSURL * (NSURLSession * __unused session, NSURLSessionDownloadTask *task, NSURL *location) { return destination(location, task.response); }; } if (progress) { *progress = delegate.progress; } downloadTask.taskDescription = self.taskDescriptionForSessionTasks; [self setDelegate:delegate forTask:downloadTask]; } - (void)removeDelegateForTask:(NSURLSessionTask *)task { NSParameterAssert(task); [self.lock lock]; [self.mutableTaskDelegatesKeyedByTaskIdentifier removeObjectForKey:@(task.taskIdentifier)]; [self.lock unlock]; } - (void)removeAllDelegates { [self.lock lock]; [self.mutableTaskDelegatesKeyedByTaskIdentifier removeAllObjects]; [self.lock unlock]; } #pragma mark - - (NSArray *)tasksForKeyPath:(NSString *)keyPath { __block NSArray *tasks = nil; dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) { if ([keyPath isEqualToString:NSStringFromSelector(@selector(dataTasks))]) { tasks = dataTasks; } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(uploadTasks))]) { tasks = uploadTasks; } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(downloadTasks))]) { tasks = downloadTasks; } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(tasks))]) { tasks = [@[dataTasks, uploadTasks, downloadTasks] valueForKeyPath:@"@unionOfArrays.self"]; } dispatch_semaphore_signal(semaphore); }]; dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); return tasks; } - (NSArray *)tasks { return [self tasksForKeyPath:NSStringFromSelector(_cmd)]; } - (NSArray *)dataTasks { return [self tasksForKeyPath:NSStringFromSelector(_cmd)]; } - (NSArray *)uploadTasks { return [self tasksForKeyPath:NSStringFromSelector(_cmd)]; } - (NSArray *)downloadTasks { return [self tasksForKeyPath:NSStringFromSelector(_cmd)]; } #pragma mark - - (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks { dispatch_async(dispatch_get_main_queue(), ^{ if (cancelPendingTasks) { [self.session invalidateAndCancel]; } else { [self.session finishTasksAndInvalidate]; } }); } #pragma mark - - (void)setResponseSerializer:(id <AFURLResponseSerialization>)responseSerializer { NSParameterAssert(responseSerializer); _responseSerializer = responseSerializer; } #pragma mark - - (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler { __block NSURLSessionDataTask *dataTask = nil; dispatch_sync(url_session_manager_creation_queue(), ^{ dataTask = [self.session dataTaskWithRequest:request]; }); [self addDelegateForDataTask:dataTask completionHandler:completionHandler]; return dataTask; } #pragma mark - - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURL progress:(NSProgress * __autoreleasing *)progress completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler { __block NSURLSessionUploadTask *uploadTask = nil; dispatch_sync(url_session_manager_creation_queue(), ^{ uploadTask = [self.session uploadTaskWithRequest:request fromFile:fileURL]; }); if (!uploadTask && self.attemptsToRecreateUploadTasksForBackgroundSessions && self.session.configuration.identifier) { for (NSUInteger attempts = 0; !uploadTask && attempts < AFMaximumNumberOfAttemptsToRecreateBackgroundSessionUploadTask; attempts++) { uploadTask = [self.session uploadTaskWithRequest:request fromFile:fileURL]; } } [self addDelegateForUploadTask:uploadTask progress:progress completionHandler:completionHandler]; return uploadTask; } - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromData:(NSData *)bodyData progress:(NSProgress * __autoreleasing *)progress completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler { __block NSURLSessionUploadTask *uploadTask = nil; dispatch_sync(url_session_manager_creation_queue(), ^{ uploadTask = [self.session uploadTaskWithRequest:request fromData:bodyData]; }); [self addDelegateForUploadTask:uploadTask progress:progress completionHandler:completionHandler]; return uploadTask; } - (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request progress:(NSProgress * __autoreleasing *)progress completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler { __block NSURLSessionUploadTask *uploadTask = nil; dispatch_sync(url_session_manager_creation_queue(), ^{ uploadTask = [self.session uploadTaskWithStreamedRequest:request]; }); [self addDelegateForUploadTask:uploadTask progress:progress completionHandler:completionHandler]; return uploadTask; } #pragma mark - - (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request progress:(NSProgress * __autoreleasing *)progress destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler { __block NSURLSessionDownloadTask *downloadTask = nil; dispatch_sync(url_session_manager_creation_queue(), ^{ downloadTask = [self.session downloadTaskWithRequest:request]; }); [self addDelegateForDownloadTask:downloadTask progress:progress destination:destination completionHandler:completionHandler]; return downloadTask; } - (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData progress:(NSProgress * __autoreleasing *)progress destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler { __block NSURLSessionDownloadTask *downloadTask = nil; dispatch_sync(url_session_manager_creation_queue(), ^{ downloadTask = [self.session downloadTaskWithResumeData:resumeData]; }); [self addDelegateForDownloadTask:downloadTask progress:progress destination:destination completionHandler:completionHandler]; return downloadTask; } #pragma mark - - (NSProgress *)uploadProgressForTask:(NSURLSessionUploadTask *)uploadTask { return [[self delegateForTask:uploadTask] progress]; } - (NSProgress *)downloadProgressForTask:(NSURLSessionDownloadTask *)downloadTask { return [[self delegateForTask:downloadTask] progress]; } #pragma mark - - (void)setSessionDidBecomeInvalidBlock:(void (^)(NSURLSession *session, NSError *error))block { self.sessionDidBecomeInvalid = block; } - (void)setSessionDidReceiveAuthenticationChallengeBlock:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential))block { self.sessionDidReceiveAuthenticationChallenge = block; } - (void)setDidFinishEventsForBackgroundURLSessionBlock:(void (^)(NSURLSession *session))block { self.didFinishEventsForBackgroundURLSession = block; } #pragma mark - - (void)setTaskNeedNewBodyStreamBlock:(NSInputStream * (^)(NSURLSession *session, NSURLSessionTask *task))block { self.taskNeedNewBodyStream = block; } - (void)setTaskWillPerformHTTPRedirectionBlock:(NSURLRequest * (^)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request))block { self.taskWillPerformHTTPRedirection = block; } - (void)setTaskDidReceiveAuthenticationChallengeBlock:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential))block { self.taskDidReceiveAuthenticationChallenge = block; } - (void)setTaskDidSendBodyDataBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))block { self.taskDidSendBodyData = block; } - (void)setTaskDidCompleteBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, NSError *error))block { self.taskDidComplete = block; } #pragma mark - - (void)setDataTaskDidReceiveResponseBlock:(NSURLSessionResponseDisposition (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response))block { self.dataTaskDidReceiveResponse = block; } - (void)setDataTaskDidBecomeDownloadTaskBlock:(void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask))block { self.dataTaskDidBecomeDownloadTask = block; } - (void)setDataTaskDidReceiveDataBlock:(void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data))block { self.dataTaskDidReceiveData = block; } - (void)setDataTaskWillCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse))block { self.dataTaskWillCacheResponse = block; } #pragma mark - - (void)setDownloadTaskDidFinishDownloadingBlock:(NSURL * (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block { self.downloadTaskDidFinishDownloading = block; } - (void)setDownloadTaskDidWriteDataBlock:(void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite))block { self.downloadTaskDidWriteData = block; } - (void)setDownloadTaskDidResumeBlock:(void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes))block { self.downloadTaskDidResume = block; } #pragma mark - NSObject - (NSString *)description { return [NSString stringWithFormat:@"<%@: %p, session: %@, operationQueue: %@>", NSStringFromClass([self class]), self, self.session, self.operationQueue]; } - (BOOL)respondsToSelector:(SEL)selector { if (selector == @selector(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:)) { return self.taskWillPerformHTTPRedirection != nil; } else if (selector == @selector(URLSession:dataTask:didReceiveResponse:completionHandler:)) { return self.dataTaskDidReceiveResponse != nil; } else if (selector == @selector(URLSession:dataTask:willCacheResponse:completionHandler:)) { return self.dataTaskWillCacheResponse != nil; } else if (selector == @selector(URLSessionDidFinishEventsForBackgroundURLSession:)) { return self.didFinishEventsForBackgroundURLSession != nil; } return [[self class] instancesRespondToSelector:selector]; } #pragma mark - NSURLSessionDelegate - (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)error { if (self.sessionDidBecomeInvalid) { self.sessionDidBecomeInvalid(session, error); } [self removeAllDelegates]; [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDidInvalidateNotification object:session]; } - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler { NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling; __block NSURLCredential *credential = nil; if (self.sessionDidReceiveAuthenticationChallenge) { disposition = self.sessionDidReceiveAuthenticationChallenge(session, challenge, &credential); } else { if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) { credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; if (credential) { disposition = NSURLSessionAuthChallengeUseCredential; } else { disposition = NSURLSessionAuthChallengePerformDefaultHandling; } } else { disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge; } } else { disposition = NSURLSessionAuthChallengePerformDefaultHandling; } } if (completionHandler) { completionHandler(disposition, credential); } } #pragma mark - NSURLSessionTaskDelegate - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest *))completionHandler { NSURLRequest *redirectRequest = request; if (self.taskWillPerformHTTPRedirection) { redirectRequest = self.taskWillPerformHTTPRedirection(session, task, response, request); } if (completionHandler) { completionHandler(redirectRequest); } } - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler { NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling; __block NSURLCredential *credential = nil; if (self.taskDidReceiveAuthenticationChallenge) { disposition = self.taskDidReceiveAuthenticationChallenge(session, task, challenge, &credential); } else { if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) { disposition = NSURLSessionAuthChallengeUseCredential; credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; } else { disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge; } } else { disposition = NSURLSessionAuthChallengePerformDefaultHandling; } } if (completionHandler) { completionHandler(disposition, credential); } } - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task needNewBodyStream:(void (^)(NSInputStream *bodyStream))completionHandler { NSInputStream *inputStream = nil; if (self.taskNeedNewBodyStream) { inputStream = self.taskNeedNewBodyStream(session, task); } else if (task.originalRequest.HTTPBodyStream && [task.originalRequest.HTTPBodyStream conformsToProtocol:@protocol(NSCopying)]) { inputStream = [task.originalRequest.HTTPBodyStream copy]; } if (completionHandler) { completionHandler(inputStream); } } - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend { int64_t totalUnitCount = totalBytesExpectedToSend; if(totalUnitCount == NSURLSessionTransferSizeUnknown) { NSString *contentLength = [task.originalRequest valueForHTTPHeaderField:@"Content-Length"]; if(contentLength) { totalUnitCount = (int64_t) [contentLength longLongValue]; } } AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task]; [delegate URLSession:session task:task didSendBodyData:bytesSent totalBytesSent:totalBytesSent totalBytesExpectedToSend:totalUnitCount]; if (self.taskDidSendBodyData) { self.taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalUnitCount); } } - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task]; // delegate may be nil when completing a task in the background if (delegate) { [delegate URLSession:session task:task didCompleteWithError:error]; [self removeDelegateForTask:task]; } if (self.taskDidComplete) { self.taskDidComplete(session, task, error); } } #pragma mark - NSURLSessionDataDelegate - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler { NSURLSessionResponseDisposition disposition = NSURLSessionResponseAllow; if (self.dataTaskDidReceiveResponse) { disposition = self.dataTaskDidReceiveResponse(session, dataTask, response); } if (completionHandler) { completionHandler(disposition); } } - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask { AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:dataTask]; if (delegate) { [self removeDelegateForTask:dataTask]; [self setDelegate:delegate forTask:downloadTask]; } if (self.dataTaskDidBecomeDownloadTask) { self.dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask); } } - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:dataTask]; [delegate URLSession:session dataTask:dataTask didReceiveData:data]; if (self.dataTaskDidReceiveData) { self.dataTaskDidReceiveData(session, dataTask, data); } } - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask willCacheResponse:(NSCachedURLResponse *)proposedResponse completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler { NSCachedURLResponse *cachedResponse = proposedResponse; if (self.dataTaskWillCacheResponse) { cachedResponse = self.dataTaskWillCacheResponse(session, dataTask, proposedResponse); } if (completionHandler) { completionHandler(cachedResponse); } } - (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session { if (self.didFinishEventsForBackgroundURLSession) { dispatch_async(dispatch_get_main_queue(), ^{ self.didFinishEventsForBackgroundURLSession(session); }); } } #pragma mark - NSURLSessionDownloadDelegate - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location { AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask]; if (self.downloadTaskDidFinishDownloading) { NSURL *fileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location); if (fileURL) { delegate.downloadFileURL = fileURL; NSError *error = nil; [[NSFileManager defaultManager] moveItemAtURL:location toURL:fileURL error:&error]; if (error) { [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:error.userInfo]; } return; } } if (delegate) { [delegate URLSession:session downloadTask:downloadTask didFinishDownloadingToURL:location]; } } - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite { AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask]; [delegate URLSession:session downloadTask:downloadTask didWriteData:bytesWritten totalBytesWritten:totalBytesWritten totalBytesExpectedToWrite:totalBytesExpectedToWrite]; if (self.downloadTaskDidWriteData) { self.downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite); } } - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes { AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask]; [delegate URLSession:session downloadTask:downloadTask didResumeAtOffset:fileOffset expectedTotalBytes:expectedTotalBytes]; if (self.downloadTaskDidResume) { self.downloadTaskDidResume(session, downloadTask, fileOffset, expectedTotalBytes); } } #pragma mark - NSSecureCoding + (BOOL)supportsSecureCoding { return YES; } - (id)initWithCoder:(NSCoder *)decoder { NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"]; self = [self initWithSessionConfiguration:configuration]; if (!self) { return nil; } return self; } - (void)encodeWithCoder:(NSCoder *)coder { [coder encodeObject:self.session.configuration forKey:@"sessionConfiguration"]; } #pragma mark - NSCopying - (id)copyWithZone:(NSZone *)zone { return [[[self class] allocWithZone:zone] initWithSessionConfiguration:self.session.configuration]; } @end #endif
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h
C/C++ Header
// AFNetworkActivityIndicatorManager.h // Copyright (c) 2011–2015 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 <Availability.h> #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #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 network request operation 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 is currently displayed in the status bar. */ @property (readonly, nonatomic, assign) BOOL isNetworkActivityIndicatorVisible; /** 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; @end NS_ASSUME_NONNULL_END #endif
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m
Objective-C
// AFNetworkActivityIndicatorManager.m // Copyright (c) 2011–2015 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 defined(__IPHONE_OS_VERSION_MAX_ALLOWED) #import "AFHTTPRequestOperation.h" #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000 #import "AFURLSessionManager.h" #endif static NSTimeInterval const kAFNetworkActivityIndicatorInvisibilityDelay = 0.17; static NSURLRequest * AFNetworkRequestFromNotification(NSNotification *notification) { if ([[notification object] isKindOfClass:[AFURLConnectionOperation class]]) { return [(AFURLConnectionOperation *)[notification object] request]; } #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000 if ([[notification object] respondsToSelector:@selector(originalRequest)]) { return [(NSURLSessionTask *)[notification object] originalRequest]; } #endif return nil; } @interface AFNetworkActivityIndicatorManager () @property (readwrite, nonatomic, assign) NSInteger activityCount; @property (readwrite, nonatomic, strong) NSTimer *activityIndicatorVisibilityTimer; @property (readonly, nonatomic, getter = isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible; - (void)updateNetworkActivityIndicatorVisibility; - (void)updateNetworkActivityIndicatorVisibilityDelayed; @end @implementation AFNetworkActivityIndicatorManager @dynamic networkActivityIndicatorVisible; + (instancetype)sharedManager { static AFNetworkActivityIndicatorManager *_sharedManager = nil; static dispatch_once_t oncePredicate; dispatch_once(&oncePredicate, ^{ _sharedManager = [[self alloc] init]; }); return _sharedManager; } + (NSSet *)keyPathsForValuesAffectingIsNetworkActivityIndicatorVisible { return [NSSet setWithObject:@"activityCount"]; } - (id)init { self = [super init]; if (!self) { return nil; } [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidStart:) name:AFNetworkingOperationDidStartNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingOperationDidFinishNotification object:nil]; #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000 [[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]; #endif return self; } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; [_activityIndicatorVisibilityTimer invalidate]; } - (void)updateNetworkActivityIndicatorVisibilityDelayed { if (self.enabled) { // Delay hiding of activity indicator for a short interval, to avoid flickering if (![self isNetworkActivityIndicatorVisible]) { [self.activityIndicatorVisibilityTimer invalidate]; self.activityIndicatorVisibilityTimer = [NSTimer timerWithTimeInterval:kAFNetworkActivityIndicatorInvisibilityDelay target:self selector:@selector(updateNetworkActivityIndicatorVisibility) userInfo:nil repeats:NO]; [[NSRunLoop mainRunLoop] addTimer:self.activityIndicatorVisibilityTimer forMode:NSRunLoopCommonModes]; } else { [self performSelectorOnMainThread:@selector(updateNetworkActivityIndicatorVisibility) withObject:nil waitUntilDone:NO modes:@[NSRunLoopCommonModes]]; } } } - (BOOL)isNetworkActivityIndicatorVisible { return self.activityCount > 0; } - (void)updateNetworkActivityIndicatorVisibility { [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:[self isNetworkActivityIndicatorVisible]]; } - (void)setActivityCount:(NSInteger)activityCount { @synchronized(self) { _activityCount = activityCount; } dispatch_async(dispatch_get_main_queue(), ^{ [self updateNetworkActivityIndicatorVisibilityDelayed]; }); } - (void)incrementActivityCount { [self willChangeValueForKey:@"activityCount"]; @synchronized(self) { _activityCount++; } [self didChangeValueForKey:@"activityCount"]; dispatch_async(dispatch_get_main_queue(), ^{ [self updateNetworkActivityIndicatorVisibilityDelayed]; }); } - (void)decrementActivityCount { [self willChangeValueForKey:@"activityCount"]; @synchronized(self) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wgnu" _activityCount = MAX(_activityCount - 1, 0); #pragma clang diagnostic pop } [self didChangeValueForKey:@"activityCount"]; dispatch_async(dispatch_get_main_queue(), ^{ [self updateNetworkActivityIndicatorVisibilityDelayed]; }); } - (void)networkRequestDidStart:(NSNotification *)notification { if ([AFNetworkRequestFromNotification(notification) URL]) { [self incrementActivityCount]; } } - (void)networkRequestDidFinish:(NSNotification *)notification { if ([AFNetworkRequestFromNotification(notification) URL]) { [self decrementActivityCount]; } } @end #endif
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h
C/C++ Header
// UIActivityIndicatorView+AFNetworking.h // Copyright (c) 2011–2015 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 <Availability.h> #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #import <UIKit/UIKit.h> @class AFURLConnectionOperation; /** 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 request operation or 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. */ #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 - (void)setAnimatingWithStateOfTask:(nullable NSURLSessionTask *)task; #endif ///--------------------------------------- /// @name Animating for Request Operations ///--------------------------------------- /** Binds the animating state to the execution state of the specified operation. @param operation The operation. If `nil`, automatic updating from any previously specified operation will be disabled. */ - (void)setAnimatingWithStateOfOperation:(nullable AFURLConnectionOperation *)operation; @end #endif
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m
Objective-C
// UIActivityIndicatorView+AFNetworking.m // Copyright (c) 2011–2015 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 defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #import "AFHTTPRequestOperation.h" #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 #import "AFURLSessionManager.h" #endif @interface AFActivityIndicatorViewNotificationObserver : NSObject @property (readonly, nonatomic, weak) UIActivityIndicatorView *activityIndicatorView; - (instancetype)initWithActivityIndicatorView:(UIActivityIndicatorView *)activityIndicatorView; #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 - (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task; #endif - (void)setAnimatingWithStateOfOperation:(AFURLConnectionOperation *)operation; @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; } #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 - (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task { [[self af_notificationObserver] setAnimatingWithStateOfTask:task]; } #endif - (void)setAnimatingWithStateOfOperation:(AFURLConnectionOperation *)operation { [[self af_notificationObserver] setAnimatingWithStateOfOperation:operation]; } @end @implementation AFActivityIndicatorViewNotificationObserver - (instancetype)initWithActivityIndicatorView:(UIActivityIndicatorView *)activityIndicatorView { self = [super init]; if (self) { _activityIndicatorView = activityIndicatorView; } return self; } #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 - (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) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wreceiver-is-weak" #pragma clang diagnostic ignored "-Warc-repeated-use-of-weak" if (task.state == NSURLSessionTaskStateRunning) { [self.activityIndicatorView startAnimating]; } else { [self.activityIndicatorView stopAnimating]; } #pragma clang diagnostic pop [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]; } } } #endif #pragma mark - - (void)setAnimatingWithStateOfOperation:(AFURLConnectionOperation *)operation { NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; [notificationCenter removeObserver:self name:AFNetworkingOperationDidStartNotification object:nil]; [notificationCenter removeObserver:self name:AFNetworkingOperationDidFinishNotification object:nil]; if (operation) { if (![operation isFinished]) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wreceiver-is-weak" #pragma clang diagnostic ignored "-Warc-repeated-use-of-weak" if ([operation isExecuting]) { [self.activityIndicatorView startAnimating]; } else { [self.activityIndicatorView stopAnimating]; } #pragma clang diagnostic pop [notificationCenter addObserver:self selector:@selector(af_startAnimating) name:AFNetworkingOperationDidStartNotification object:operation]; [notificationCenter addObserver:self selector:@selector(af_stopAnimating) name:AFNetworkingOperationDidFinishNotification object:operation]; } } } #pragma mark - - (void)af_startAnimating { dispatch_async(dispatch_get_main_queue(), ^{ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wreceiver-is-weak" [self.activityIndicatorView startAnimating]; #pragma clang diagnostic pop }); } - (void)af_stopAnimating { dispatch_async(dispatch_get_main_queue(), ^{ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wreceiver-is-weak" [self.activityIndicatorView stopAnimating]; #pragma clang diagnostic pop }); } #pragma mark - - (void)dealloc { NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; #endif [notificationCenter removeObserver:self name:AFNetworkingOperationDidStartNotification object:nil]; [notificationCenter removeObserver:self name:AFNetworkingOperationDidFinishNotification object:nil]; } @end #endif
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/AFNetworking/UIKit+AFNetworking/UIAlertView+AFNetworking.h
C/C++ Header
// UIAlertView+AFNetworking.h // Copyright (c) 2011–2015 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 <Availability.h> #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @class AFURLConnectionOperation; /** This category adds methods to the UIKit framework's `UIAlertView` class. The methods in this category provide support for automatically showing an alert if a session task or request operation finishes with an error. Alert title and message are filled from the corresponding `localizedDescription` & `localizedRecoverySuggestion` or `localizedFailureReason` of the error. */ @interface UIAlertView (AFNetworking) ///------------------------------------- /// @name Showing Alert for Session Task ///------------------------------------- /** Shows an alert view with the error of the specified session task, if any. @param task The session task. @param delegate The alert view delegate. */ #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 + (void)showAlertViewForTaskWithErrorOnCompletion:(NSURLSessionTask *)task delegate:(nullable id)delegate NS_EXTENSION_UNAVAILABLE_IOS("Not available in app extensions."); #endif /** Shows an alert view with the error of the specified session task, if any, with a custom cancel button title and other button titles. @param task The session task. @param delegate The alert view delegate. @param cancelButtonTitle The title of the cancel button or nil if there is no cancel button. Using this argument is equivalent to setting the cancel button index to the value returned by invoking addButtonWithTitle: specifying this title. @param otherButtonTitles The title of another button. Using this argument is equivalent to invoking addButtonWithTitle: with this title to add more buttons. Too many buttons can cause the alert view to scroll. For guidelines on the best ways to use an alert in an app, see "Temporary Views". Titles of additional buttons to add to the receiver, terminated with `nil`. */ #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 + (void)showAlertViewForTaskWithErrorOnCompletion:(NSURLSessionTask *)task delegate:(nullable id)delegate cancelButtonTitle:(nullable NSString *)cancelButtonTitle otherButtonTitles:(nullable NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION NS_EXTENSION_UNAVAILABLE_IOS("Not available in app extensions."); #endif ///------------------------------------------ /// @name Showing Alert for Request Operation ///------------------------------------------ /** Shows an alert view with the error of the specified request operation, if any. @param operation The request operation. @param delegate The alert view delegate. */ + (void)showAlertViewForRequestOperationWithErrorOnCompletion:(AFURLConnectionOperation *)operation delegate:(nullable id)delegate NS_EXTENSION_UNAVAILABLE_IOS("Not available in app extensions."); /** Shows an alert view with the error of the specified request operation, if any, with a custom cancel button title and other button titles. @param operation The request operation. @param delegate The alert view delegate. @param cancelButtonTitle The title of the cancel button or nil if there is no cancel button. Using this argument is equivalent to setting the cancel button index to the value returned by invoking addButtonWithTitle: specifying this title. @param otherButtonTitles The title of another button. Using this argument is equivalent to invoking addButtonWithTitle: with this title to add more buttons. Too many buttons can cause the alert view to scroll. For guidelines on the best ways to use an alert in an app, see "Temporary Views". Titles of additional buttons to add to the receiver, terminated with `nil`. */ + (void)showAlertViewForRequestOperationWithErrorOnCompletion:(AFURLConnectionOperation *)operation delegate:(nullable id)delegate cancelButtonTitle:(nullable NSString *)cancelButtonTitle otherButtonTitles:(nullable NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION NS_EXTENSION_UNAVAILABLE_IOS("Not available in app extensions."); @end NS_ASSUME_NONNULL_END #endif
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/AFNetworking/UIKit+AFNetworking/UIAlertView+AFNetworking.m
Objective-C
// UIAlertView+AFNetworking.m // Copyright (c) 2011–2015 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 "UIAlertView+AFNetworking.h" #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #import "AFURLConnectionOperation.h" #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 #import "AFURLSessionManager.h" #endif static void AFGetAlertViewTitleAndMessageFromError(NSError *error, NSString * __autoreleasing *title, NSString * __autoreleasing *message) { if (error.localizedDescription && (error.localizedRecoverySuggestion || error.localizedFailureReason)) { *title = error.localizedDescription; if (error.localizedRecoverySuggestion) { *message = error.localizedRecoverySuggestion; } else { *message = error.localizedFailureReason; } } else if (error.localizedDescription) { *title = NSLocalizedStringFromTable(@"Error", @"AFNetworking", @"Fallback Error Description"); *message = error.localizedDescription; } else { *title = NSLocalizedStringFromTable(@"Error", @"AFNetworking", @"Fallback Error Description"); *message = [NSString stringWithFormat:NSLocalizedStringFromTable(@"%@ Error: %ld", @"AFNetworking", @"Fallback Error Failure Reason Format"), error.domain, (long)error.code]; } } @implementation UIAlertView (AFNetworking) #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 + (void)showAlertViewForTaskWithErrorOnCompletion:(NSURLSessionTask *)task delegate:(id)delegate { [self showAlertViewForTaskWithErrorOnCompletion:task delegate:delegate cancelButtonTitle:NSLocalizedStringFromTable(@"Dismiss", @"AFNetworking", @"UIAlertView Cancel Button Title") otherButtonTitles:nil, nil]; } + (void)showAlertViewForTaskWithErrorOnCompletion:(NSURLSessionTask *)task delegate:(id)delegate cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION { NSMutableArray *mutableOtherTitles = [NSMutableArray array]; va_list otherButtonTitleList; va_start(otherButtonTitleList, otherButtonTitles); { for (NSString *otherButtonTitle = otherButtonTitles; otherButtonTitle != nil; otherButtonTitle = va_arg(otherButtonTitleList, NSString *)) { [mutableOtherTitles addObject:otherButtonTitle]; } } va_end(otherButtonTitleList); __block __weak id<NSObject> observer = [[NSNotificationCenter defaultCenter] addObserverForName:AFNetworkingTaskDidCompleteNotification object:task queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *notification) { NSError *error = notification.userInfo[AFNetworkingTaskDidCompleteErrorKey]; if (error) { NSString *title, *message; AFGetAlertViewTitleAndMessageFromError(error, &title, &message); UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:nil delegate:delegate cancelButtonTitle:cancelButtonTitle otherButtonTitles:nil, nil]; for (NSString *otherButtonTitle in mutableOtherTitles) { [alertView addButtonWithTitle:otherButtonTitle]; } [alertView setTitle:title]; [alertView setMessage:message]; [alertView show]; } [[NSNotificationCenter defaultCenter] removeObserver:observer]; }]; } #endif #pragma mark - + (void)showAlertViewForRequestOperationWithErrorOnCompletion:(AFURLConnectionOperation *)operation delegate:(id)delegate { [self showAlertViewForRequestOperationWithErrorOnCompletion:operation delegate:delegate cancelButtonTitle:NSLocalizedStringFromTable(@"Dismiss", @"AFNetworking", @"UIAlertView Cancel Button Title") otherButtonTitles:nil, nil]; } + (void)showAlertViewForRequestOperationWithErrorOnCompletion:(AFURLConnectionOperation *)operation delegate:(id)delegate cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION { NSMutableArray *mutableOtherTitles = [NSMutableArray array]; va_list otherButtonTitleList; va_start(otherButtonTitleList, otherButtonTitles); { for (NSString *otherButtonTitle = otherButtonTitles; otherButtonTitle != nil; otherButtonTitle = va_arg(otherButtonTitleList, NSString *)) { [mutableOtherTitles addObject:otherButtonTitle]; } } va_end(otherButtonTitleList); __block __weak id<NSObject> observer = [[NSNotificationCenter defaultCenter] addObserverForName:AFNetworkingOperationDidFinishNotification object:operation queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *notification) { if (notification.object && [notification.object isKindOfClass:[AFURLConnectionOperation class]]) { NSError *error = [(AFURLConnectionOperation *)notification.object error]; if (error) { NSString *title, *message; AFGetAlertViewTitleAndMessageFromError(error, &title, &message); UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:nil delegate:delegate cancelButtonTitle:cancelButtonTitle otherButtonTitles:nil, nil]; for (NSString *otherButtonTitle in mutableOtherTitles) { [alertView addButtonWithTitle:otherButtonTitle]; } [alertView setTitle:title]; [alertView setMessage:message]; [alertView show]; } } [[NSNotificationCenter defaultCenter] removeObserver:observer]; }]; } @end #endif
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h
C/C++ Header
// UIButton+AFNetworking.h // Copyright (c) 2011–2015 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 <Availability.h> #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @protocol AFURLResponseSerialization, AFImageCache; /** 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 Image Cache ///---------------------------- /** The image cache used to improve image loading performance on scroll views. By default, `UIButton` will use the `sharedImageCache` of `UIImageView`. */ + (id <AFImageCache>)sharedImageCache; /** Set the cache used for image loading. @param imageCache The image cache. */ + (void)setSharedImageCache:(id <AFImageCache>)imageCache; ///------------------------------------ /// @name Accessing Response Serializer ///------------------------------------ /** The response serializer used to create an image representation from the server response and response data. By default, this is an instance of `AFImageResponseSerializer`. @discussion Subclasses of `AFImageResponseSerializer` could be used to perform post-processing, such as color correction, face detection, or other effects. See https://github.com/AFNetworking/AFCoreImageSerializer */ @property (nonatomic, strong) id <AFURLResponseSerialization> imageResponseSerializer; ///-------------------- /// @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 request operation finishes successfully. This block has no return value and takes two arguments: the server response and the image. If the image was returned from cache, the request and response parameters will be `nil`. @param failure A block object to be executed when the image request operation finishes unsuccessfully, or that finishes successfully. This block has no return value and takes a single argument: the error that occurred. */ - (void)setImageForState:(UIControlState)state withURLRequest:(NSURLRequest *)urlRequest placeholderImage:(nullable UIImage *)placeholderImage success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success failure:(nullable void (^)(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. */ - (void)setBackgroundImageForState:(UIControlState)state withURLRequest:(NSURLRequest *)urlRequest placeholderImage:(nullable UIImage *)placeholderImage success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success failure:(nullable void (^)(NSError *error))failure; ///------------------------------ /// @name Canceling Image Loading ///------------------------------ /** Cancels any executing image operation for the specified control state of the receiver, if one exists. @param state The control state. */ - (void)cancelImageRequestOperationForState:(UIControlState)state; /** Cancels any executing background image operation for the specified control state of the receiver, if one exists. @param state The control state. */ - (void)cancelBackgroundImageRequestOperationForState:(UIControlState)state; @end NS_ASSUME_NONNULL_END #endif
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.m
Objective-C
// UIButton+AFNetworking.m // Copyright (c) 2011–2015 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 defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #import "AFURLResponseSerialization.h" #import "AFHTTPRequestOperation.h" #import "UIImageView+AFNetworking.h" @interface UIButton (_AFNetworking) @end @implementation UIButton (_AFNetworking) + (NSOperationQueue *)af_sharedImageRequestOperationQueue { static NSOperationQueue *_af_sharedImageRequestOperationQueue = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _af_sharedImageRequestOperationQueue = [[NSOperationQueue alloc] init]; _af_sharedImageRequestOperationQueue.maxConcurrentOperationCount = NSOperationQueueDefaultMaxConcurrentOperationCount; }); return _af_sharedImageRequestOperationQueue; } #pragma mark - static char AFImageRequestOperationNormal; static char AFImageRequestOperationHighlighted; static char AFImageRequestOperationSelected; static char AFImageRequestOperationDisabled; static const char * af_imageRequestOperationKeyForState(UIControlState state) { switch (state) { case UIControlStateHighlighted: return &AFImageRequestOperationHighlighted; case UIControlStateSelected: return &AFImageRequestOperationSelected; case UIControlStateDisabled: return &AFImageRequestOperationDisabled; case UIControlStateNormal: default: return &AFImageRequestOperationNormal; } } - (AFHTTPRequestOperation *)af_imageRequestOperationForState:(UIControlState)state { return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, af_imageRequestOperationKeyForState(state)); } - (void)af_setImageRequestOperation:(AFHTTPRequestOperation *)imageRequestOperation forState:(UIControlState)state { objc_setAssociatedObject(self, af_imageRequestOperationKeyForState(state), imageRequestOperation, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } #pragma mark - static char AFBackgroundImageRequestOperationNormal; static char AFBackgroundImageRequestOperationHighlighted; static char AFBackgroundImageRequestOperationSelected; static char AFBackgroundImageRequestOperationDisabled; static const char * af_backgroundImageRequestOperationKeyForState(UIControlState state) { switch (state) { case UIControlStateHighlighted: return &AFBackgroundImageRequestOperationHighlighted; case UIControlStateSelected: return &AFBackgroundImageRequestOperationSelected; case UIControlStateDisabled: return &AFBackgroundImageRequestOperationDisabled; case UIControlStateNormal: default: return &AFBackgroundImageRequestOperationNormal; } } - (AFHTTPRequestOperation *)af_backgroundImageRequestOperationForState:(UIControlState)state { return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, af_backgroundImageRequestOperationKeyForState(state)); } - (void)af_setBackgroundImageRequestOperation:(AFHTTPRequestOperation *)imageRequestOperation forState:(UIControlState)state { objc_setAssociatedObject(self, af_backgroundImageRequestOperationKeyForState(state), imageRequestOperation, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } @end #pragma mark - @implementation UIButton (AFNetworking) + (id <AFImageCache>)sharedImageCache { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wgnu" return objc_getAssociatedObject(self, @selector(sharedImageCache)) ?: [UIImageView sharedImageCache]; #pragma clang diagnostic pop } + (void)setSharedImageCache:(id <AFImageCache>)imageCache { objc_setAssociatedObject(self, @selector(sharedImageCache), imageCache, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } #pragma mark - - (id <AFURLResponseSerialization>)imageResponseSerializer { static id <AFURLResponseSerialization> _af_defaultImageResponseSerializer = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _af_defaultImageResponseSerializer = [AFImageResponseSerializer serializer]; }); #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wgnu" return objc_getAssociatedObject(self, @selector(imageResponseSerializer)) ?: _af_defaultImageResponseSerializer; #pragma clang diagnostic pop } - (void)setImageResponseSerializer:(id <AFURLResponseSerialization>)serializer { objc_setAssociatedObject(self, @selector(imageResponseSerializer), serializer, 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:(UIImage *)placeholderImage success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success failure:(void (^)(NSError *error))failure { [self cancelImageRequestOperationForState:state]; UIImage *cachedImage = [[[self class] sharedImageCache] cachedImageForRequest:urlRequest]; if (cachedImage) { if (success) { success(nil, nil, cachedImage); } else { [self setImage:cachedImage forState:state]; } [self af_setImageRequestOperation:nil forState:state]; } else { if (placeholderImage) { [self setImage:placeholderImage forState:state]; } __weak __typeof(self)weakSelf = self; AFHTTPRequestOperation *imageRequestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest]; imageRequestOperation.responseSerializer = self.imageResponseSerializer; [imageRequestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { __strong __typeof(weakSelf)strongSelf = weakSelf; if ([[urlRequest URL] isEqual:[operation.request URL]]) { if (success) { success(operation.request, operation.response, responseObject); } else if (responseObject) { [strongSelf setImage:responseObject forState:state]; } } [[[strongSelf class] sharedImageCache] cacheImage:responseObject forRequest:urlRequest]; } failure:^(AFHTTPRequestOperation *operation, NSError *error) { if ([[urlRequest URL] isEqual:[operation.request URL]]) { if (failure) { failure(error); } } }]; [self af_setImageRequestOperation:imageRequestOperation forState:state]; [[[self class] af_sharedImageRequestOperationQueue] addOperation:imageRequestOperation]; } } #pragma mark - - (void)setBackgroundImageForState:(UIControlState)state withURL:(NSURL *)url { [self setBackgroundImageForState:state withURL:url placeholderImage:nil]; } - (void)setBackgroundImageForState:(UIControlState)state withURL:(NSURL *)url placeholderImage:(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:(UIImage *)placeholderImage success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success failure:(void (^)(NSError *error))failure { [self cancelBackgroundImageRequestOperationForState:state]; UIImage *cachedImage = [[[self class] sharedImageCache] cachedImageForRequest:urlRequest]; if (cachedImage) { if (success) { success(nil, nil, cachedImage); } else { [self setBackgroundImage:cachedImage forState:state]; } [self af_setBackgroundImageRequestOperation:nil forState:state]; } else { if (placeholderImage) { [self setBackgroundImage:placeholderImage forState:state]; } __weak __typeof(self)weakSelf = self; AFHTTPRequestOperation *backgroundImageRequestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest]; backgroundImageRequestOperation.responseSerializer = self.imageResponseSerializer; [backgroundImageRequestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { __strong __typeof(weakSelf)strongSelf = weakSelf; if ([[urlRequest URL] isEqual:[operation.request URL]]) { if (success) { success(operation.request, operation.response, responseObject); } else if (responseObject) { [strongSelf setBackgroundImage:responseObject forState:state]; } } [[[strongSelf class] sharedImageCache] cacheImage:responseObject forRequest:urlRequest]; } failure:^(AFHTTPRequestOperation *operation, NSError *error) { if ([[urlRequest URL] isEqual:[operation.request URL]]) { if (failure) { failure(error); } } }]; [self af_setBackgroundImageRequestOperation:backgroundImageRequestOperation forState:state]; [[[self class] af_sharedImageRequestOperationQueue] addOperation:backgroundImageRequestOperation]; } } #pragma mark - - (void)cancelImageRequestOperationForState:(UIControlState)state { [[self af_imageRequestOperationForState:state] cancel]; [self af_setImageRequestOperation:nil forState:state]; } - (void)cancelBackgroundImageRequestOperationForState:(UIControlState)state { [[self af_backgroundImageRequestOperationForState:state] cancel]; [self af_setBackgroundImageRequestOperation:nil forState:state]; } @end #endif
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/AFNetworking/UIKit+AFNetworking/UIImage+AFNetworking.h
C/C++ Header
// // UIImage+AFNetworking.h // // // Created by Paulo Ferreira on 08/07/15. // // 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. #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #import <UIKit/UIKit.h> @interface UIImage (AFNetworking) + (UIImage*) safeImageWithData:(NSData*)data; @end #endif
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h
C/C++ Header
// UIImageView+AFNetworking.h // Copyright (c) 2011–2015 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 <Availability.h> #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @protocol AFURLResponseSerialization, AFImageCache; /** 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 Image Cache ///---------------------------- /** The image cache used to improve image loading performance on scroll views. By default, this is an `NSCache` subclass conforming to the `AFImageCache` protocol, which listens for notification warnings and evicts objects accordingly. */ + (id <AFImageCache>)sharedImageCache; /** Set the cache used for image loading. @param imageCache The image cache. */ + (void)setSharedImageCache:(id <AFImageCache>)imageCache; ///------------------------------------ /// @name Accessing Response Serializer ///------------------------------------ /** The response serializer used to create an image representation from the server response and response data. By default, this is an instance of `AFImageResponseSerializer`. @discussion Subclasses of `AFImageResponseSerializer` could be used to perform post-processing, such as color correction, face detection, or other effects. See https://github.com/AFNetworking/AFCoreImageSerializer */ @property (nonatomic, strong) id <AFURLResponseSerialization> imageResponseSerializer; ///-------------------- /// @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 request operation 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 request operation 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 *response, UIImage *image))success failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; /** Cancels any executing image operation for the receiver, if one exists. */ - (void)cancelImageRequestOperation; @end #pragma mark - /** The `AFImageCache` protocol is adopted by an object used to cache images loaded by the AFNetworking category on `UIImageView`. */ @protocol AFImageCache <NSObject> /** Returns a cached image for the specified request, if available. @param request The image request. @return The cached image. */ - (nullable UIImage *)cachedImageForRequest:(NSURLRequest *)request; /** Caches a particular image for the specified request. @param image The image to cache. @param request The request to be used as a cache key. */ - (void)cacheImage:(UIImage *)image forRequest:(NSURLRequest *)request; @end NS_ASSUME_NONNULL_END #endif
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.m
Objective-C
// UIImageView+AFNetworking.m // Copyright (c) 2011–2015 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 defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #import "AFHTTPRequestOperation.h" @interface AFImageCache : NSCache <AFImageCache> @end #pragma mark - @interface UIImageView (_AFNetworking) @property (readwrite, nonatomic, strong, setter = af_setImageRequestOperation:) AFHTTPRequestOperation *af_imageRequestOperation; @end @implementation UIImageView (_AFNetworking) + (NSOperationQueue *)af_sharedImageRequestOperationQueue { static NSOperationQueue *_af_sharedImageRequestOperationQueue = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _af_sharedImageRequestOperationQueue = [[NSOperationQueue alloc] init]; _af_sharedImageRequestOperationQueue.maxConcurrentOperationCount = NSOperationQueueDefaultMaxConcurrentOperationCount; }); return _af_sharedImageRequestOperationQueue; } - (AFHTTPRequestOperation *)af_imageRequestOperation { return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, @selector(af_imageRequestOperation)); } - (void)af_setImageRequestOperation:(AFHTTPRequestOperation *)imageRequestOperation { objc_setAssociatedObject(self, @selector(af_imageRequestOperation), imageRequestOperation, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } @end #pragma mark - @implementation UIImageView (AFNetworking) @dynamic imageResponseSerializer; + (id <AFImageCache>)sharedImageCache { static AFImageCache *_af_defaultImageCache = nil; static dispatch_once_t oncePredicate; dispatch_once(&oncePredicate, ^{ _af_defaultImageCache = [[AFImageCache alloc] init]; [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidReceiveMemoryWarningNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * __unused notification) { [_af_defaultImageCache removeAllObjects]; }]; }); #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wgnu" return objc_getAssociatedObject(self, @selector(sharedImageCache)) ?: _af_defaultImageCache; #pragma clang diagnostic pop } + (void)setSharedImageCache:(id <AFImageCache>)imageCache { objc_setAssociatedObject(self, @selector(sharedImageCache), imageCache, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } #pragma mark - - (id <AFURLResponseSerialization>)imageResponseSerializer { static id <AFURLResponseSerialization> _af_defaultImageResponseSerializer = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _af_defaultImageResponseSerializer = [AFImageResponseSerializer serializer]; }); #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wgnu" return objc_getAssociatedObject(self, @selector(imageResponseSerializer)) ?: _af_defaultImageResponseSerializer; #pragma clang diagnostic pop } - (void)setImageResponseSerializer:(id <AFURLResponseSerialization>)serializer { objc_setAssociatedObject(self, @selector(imageResponseSerializer), serializer, 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 *response, UIImage *image))success failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure { [self cancelImageRequestOperation]; UIImage *cachedImage = [[[self class] sharedImageCache] cachedImageForRequest:urlRequest]; if (cachedImage) { if (success) { success(urlRequest, nil, cachedImage); } else { self.image = cachedImage; } self.af_imageRequestOperation = nil; } else { if (placeholderImage) { self.image = placeholderImage; } __weak __typeof(self)weakSelf = self; self.af_imageRequestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest]; self.af_imageRequestOperation.responseSerializer = self.imageResponseSerializer; [self.af_imageRequestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { __strong __typeof(weakSelf)strongSelf = weakSelf; if ([[urlRequest URL] isEqual:[strongSelf.af_imageRequestOperation.request URL]]) { if (success) { success(urlRequest, operation.response, responseObject); } else if (responseObject) { strongSelf.image = responseObject; } if (operation == strongSelf.af_imageRequestOperation){ strongSelf.af_imageRequestOperation = nil; } } [[[strongSelf class] sharedImageCache] cacheImage:responseObject forRequest:urlRequest]; } failure:^(AFHTTPRequestOperation *operation, NSError *error) { __strong __typeof(weakSelf)strongSelf = weakSelf; if ([[urlRequest URL] isEqual:[strongSelf.af_imageRequestOperation.request URL]]) { if (failure) { failure(urlRequest, operation.response, error); } if (operation == strongSelf.af_imageRequestOperation){ strongSelf.af_imageRequestOperation = nil; } } }]; [[[self class] af_sharedImageRequestOperationQueue] addOperation:self.af_imageRequestOperation]; } } - (void)cancelImageRequestOperation { [self.af_imageRequestOperation cancel]; self.af_imageRequestOperation = nil; } @end #pragma mark - static inline NSString * AFImageCacheKeyFromURLRequest(NSURLRequest *request) { return [[request URL] absoluteString]; } @implementation AFImageCache - (UIImage *)cachedImageForRequest:(NSURLRequest *)request { switch ([request cachePolicy]) { case NSURLRequestReloadIgnoringCacheData: case NSURLRequestReloadIgnoringLocalAndRemoteCacheData: return nil; default: break; } return [self objectForKey:AFImageCacheKeyFromURLRequest(request)]; } - (void)cacheImage:(UIImage *)image forRequest:(NSURLRequest *)request { if (image && request) { [self setObject:image forKey:AFImageCacheKeyFromURLRequest(request)]; } } @end #endif
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h
C/C++ Header
// UIKit+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. #if TARGET_OS_IOS #import <UIKit/UIKit.h> #ifndef _UIKIT_AFNETWORKING_ #define _UIKIT_AFNETWORKING_ #import "AFNetworkActivityIndicatorManager.h" #import "UIActivityIndicatorView+AFNetworking.h" #import "UIAlertView+AFNetworking.h" #import "UIButton+AFNetworking.h" #import "UIImageView+AFNetworking.h" #import "UIProgressView+AFNetworking.h" #import "UIRefreshControl+AFNetworking.h" #import "UIWebView+AFNetworking.h" #endif /* _UIKIT_AFNETWORKING_ */ #endif
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h
C/C++ Header
// UIProgressView+AFNetworking.h // Copyright (c) 2011–2015 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 <Availability.h> #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @class AFURLConnectionOperation; /** 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 or request operation. */ @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. */ #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 - (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task animated:(BOOL)animated; #endif /** 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. */ #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 - (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task animated:(BOOL)animated; #endif ///------------------------------------ /// @name Setting Session Task Progress ///------------------------------------ /** Binds the progress to the upload progress of the specified request operation. @param operation The request operation. @param animated `YES` if the change should be animated, `NO` if the change should happen immediately. */ - (void)setProgressWithUploadProgressOfOperation:(AFURLConnectionOperation *)operation animated:(BOOL)animated; /** Binds the progress to the download progress of the specified request operation. @param operation The request operation. @param animated `YES` if the change should be animated, `NO` if the change should happen immediately. */ - (void)setProgressWithDownloadProgressOfOperation:(AFURLConnectionOperation *)operation animated:(BOOL)animated; @end NS_ASSUME_NONNULL_END #endif
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.m
Objective-C
// UIProgressView+AFNetworking.m // Copyright (c) 2011–2015 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 defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #import "AFURLConnectionOperation.h" #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 #import "AFURLSessionManager.h" #endif static void * AFTaskCountOfBytesSentContext = &AFTaskCountOfBytesSentContext; static void * AFTaskCountOfBytesReceivedContext = &AFTaskCountOfBytesReceivedContext; @interface AFURLConnectionOperation (_UIProgressView) @property (readwrite, nonatomic, copy) void (^uploadProgress)(NSUInteger bytes, long long totalBytes, long long totalBytesExpected); @property (readwrite, nonatomic, assign, setter = af_setUploadProgressAnimated:) BOOL af_uploadProgressAnimated; @property (readwrite, nonatomic, copy) void (^downloadProgress)(NSUInteger bytes, long long totalBytes, long long totalBytesExpected); @property (readwrite, nonatomic, assign, setter = af_setDownloadProgressAnimated:) BOOL af_downloadProgressAnimated; @end @implementation AFURLConnectionOperation (_UIProgressView) @dynamic uploadProgress; // Implemented in AFURLConnectionOperation @dynamic af_uploadProgressAnimated; @dynamic downloadProgress; // Implemented in AFURLConnectionOperation @dynamic af_downloadProgressAnimated; @end #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 - #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 - (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task animated:(BOOL)animated { [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 { [task addObserver:self forKeyPath:@"state" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext]; [task addObserver:self forKeyPath:@"countOfBytesReceived" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext]; [self af_setDownloadProgressAnimated:animated]; } #endif #pragma mark - - (void)setProgressWithUploadProgressOfOperation:(AFURLConnectionOperation *)operation animated:(BOOL)animated { __weak __typeof(self)weakSelf = self; void (^original)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) = [operation.uploadProgress copy]; [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) { if (original) { original(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite); } dispatch_async(dispatch_get_main_queue(), ^{ if (totalBytesExpectedToWrite > 0) { __strong __typeof(weakSelf)strongSelf = weakSelf; [strongSelf setProgress:(totalBytesWritten / (totalBytesExpectedToWrite * 1.0f)) animated:animated]; } }); }]; } - (void)setProgressWithDownloadProgressOfOperation:(AFURLConnectionOperation *)operation animated:(BOOL)animated { __weak __typeof(self)weakSelf = self; void (^original)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) = [operation.downloadProgress copy]; [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) { if (original) { original(bytesRead, totalBytesRead, totalBytesExpectedToRead); } dispatch_async(dispatch_get_main_queue(), ^{ if (totalBytesExpectedToRead > 0) { __strong __typeof(weakSelf)strongSelf = weakSelf; [strongSelf setProgress:(totalBytesRead / (totalBytesExpectedToRead * 1.0f)) animated:animated]; } }); }]; } #pragma mark - NSKeyValueObserving - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(__unused NSDictionary *)change context:(void *)context { #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 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) {} } } } #endif } @end #endif
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h
C/C++ Header
// UIRefreshControl+AFNetworking.m // // Copyright (c) 2014 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> #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @class AFURLConnectionOperation; /** 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 request operation or 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. */ #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 - (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task; #endif ///---------------------------------------- /// @name Refreshing for Request Operations ///---------------------------------------- /** Binds the refreshing state to the execution state of the specified operation. @param operation The operation. If `nil`, automatic updating from any previously specified operation will be disabled. */ - (void)setRefreshingWithStateOfOperation:(AFURLConnectionOperation *)operation; @end NS_ASSUME_NONNULL_END #endif
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.m
Objective-C
// UIRefreshControl+AFNetworking.m // // Copyright (c) 2014 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 "UIRefreshControl+AFNetworking.h" #import <objc/runtime.h> #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #import "AFHTTPRequestOperation.h" #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 #import "AFURLSessionManager.h" #endif @interface AFRefreshControlNotificationObserver : NSObject @property (readonly, nonatomic, weak) UIRefreshControl *refreshControl; - (instancetype)initWithActivityRefreshControl:(UIRefreshControl *)refreshControl; #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 - (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task; #endif - (void)setRefreshingWithStateOfOperation:(AFURLConnectionOperation *)operation; @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; } #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 - (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task { [[self af_notificationObserver] setRefreshingWithStateOfTask:task]; } #endif - (void)setRefreshingWithStateOfOperation:(AFURLConnectionOperation *)operation { [[self af_notificationObserver] setRefreshingWithStateOfOperation:operation]; } @end @implementation AFRefreshControlNotificationObserver - (instancetype)initWithActivityRefreshControl:(UIRefreshControl *)refreshControl { self = [super init]; if (self) { _refreshControl = refreshControl; } return self; } #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 - (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) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wreceiver-is-weak" #pragma clang diagnostic ignored "-Warc-repeated-use-of-weak" if (task.state == NSURLSessionTaskStateRunning) { [self.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 { [self.refreshControl endRefreshing]; } #pragma clang diagnostic pop } } #endif - (void)setRefreshingWithStateOfOperation:(AFURLConnectionOperation *)operation { NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; [notificationCenter removeObserver:self name:AFNetworkingOperationDidStartNotification object:nil]; [notificationCenter removeObserver:self name:AFNetworkingOperationDidFinishNotification object:nil]; if (operation) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wreceiver-is-weak" #pragma clang diagnostic ignored "-Warc-repeated-use-of-weak" if (![operation isFinished]) { if ([operation isExecuting]) { [self.refreshControl beginRefreshing]; } else { [self.refreshControl endRefreshing]; } [notificationCenter addObserver:self selector:@selector(af_beginRefreshing) name:AFNetworkingOperationDidStartNotification object:operation]; [notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingOperationDidFinishNotification object:operation]; } #pragma clang diagnostic pop } } #pragma mark - - (void)af_beginRefreshing { dispatch_async(dispatch_get_main_queue(), ^{ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wreceiver-is-weak" [self.refreshControl beginRefreshing]; #pragma clang diagnostic pop }); } - (void)af_endRefreshing { dispatch_async(dispatch_get_main_queue(), ^{ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wreceiver-is-weak" [self.refreshControl endRefreshing]; #pragma clang diagnostic pop }); } #pragma mark - - (void)dealloc { NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; #endif [notificationCenter removeObserver:self name:AFNetworkingOperationDidStartNotification object:nil]; [notificationCenter removeObserver:self name:AFNetworkingOperationDidFinishNotification object:nil]; } @end #endif
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.h
C/C++ Header
// UIWebView+AFNetworking.h // Copyright (c) 2011–2015 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 <Availability.h> #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @class AFHTTPRequestSerializer, AFHTTPResponseSerializer; @protocol AFURLRequestSerialization, AFURLResponseSerialization; /** This category adds methods to the UIKit framework's `UIWebView` class. The methods in this category provide increased control over the request cycle, including progress monitoring and success / failure handling. @discussion When using these category methods, make sure to assign `delegate` for the web view, which implements `–webView:shouldStartLoadWithRequest:navigationType:` appropriately. This allows for tapped links to be loaded through AFNetworking, and can ensure that `canGoBack` & `canGoForward` update their values correctly. */ @interface UIWebView (AFNetworking) /** The request serializer used to serialize requests made with the `-loadRequest:...` category methods. By default, this is an instance of `AFHTTPRequestSerializer`. */ @property (nonatomic, strong) AFHTTPRequestSerializer <AFURLRequestSerialization> * requestSerializer; /** The response serializer used to serialize responses made with the `-loadRequest:...` category methods. By default, this is an instance of `AFHTTPResponseSerializer`. */ @property (nonatomic, strong) AFHTTPResponseSerializer <AFURLResponseSerialization> * responseSerializer; /** Asynchronously loads the specified request. @param request A URL request identifying the location of the content to load. This must not be `nil`. @param progress 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 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 main thread. @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 request operation 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 progress:(nullable void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))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 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 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 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 main thread. @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 request operation 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 MIMEType:(nullable NSString *)MIMEType textEncodingName:(nullable NSString *)textEncodingName progress:(nullable void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))progress success:(nullable NSData * (^)(NSHTTPURLResponse *response, NSData *data))success failure:(nullable void (^)(NSError *error))failure; @end NS_ASSUME_NONNULL_END #endif
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.m
Objective-C
// UIWebView+AFNetworking.m // Copyright (c) 2011–2015 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 "UIWebView+AFNetworking.h" #import <objc/runtime.h> #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #import "AFHTTPRequestOperation.h" #import "AFURLResponseSerialization.h" #import "AFURLRequestSerialization.h" @interface UIWebView (_AFNetworking) @property (readwrite, nonatomic, strong, setter = af_setHTTPRequestOperation:) AFHTTPRequestOperation *af_HTTPRequestOperation; @end @implementation UIWebView (_AFNetworking) - (AFHTTPRequestOperation *)af_HTTPRequestOperation { return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, @selector(af_HTTPRequestOperation)); } - (void)af_setHTTPRequestOperation:(AFHTTPRequestOperation *)operation { objc_setAssociatedObject(self, @selector(af_HTTPRequestOperation), operation, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } @end #pragma mark - @implementation UIWebView (AFNetworking) - (AFHTTPRequestSerializer <AFURLRequestSerialization> *)requestSerializer { static AFHTTPRequestSerializer <AFURLRequestSerialization> *_af_defaultRequestSerializer = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _af_defaultRequestSerializer = [AFHTTPRequestSerializer serializer]; }); #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wgnu" return objc_getAssociatedObject(self, @selector(requestSerializer)) ?: _af_defaultRequestSerializer; #pragma clang diagnostic pop } - (void)setRequestSerializer:(AFHTTPRequestSerializer<AFURLRequestSerialization> *)requestSerializer { objc_setAssociatedObject(self, @selector(requestSerializer), requestSerializer, 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]; }); #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wgnu" return objc_getAssociatedObject(self, @selector(responseSerializer)) ?: _af_defaultResponseSerializer; #pragma clang diagnostic pop } - (void)setResponseSerializer:(AFHTTPResponseSerializer<AFURLResponseSerialization> *)responseSerializer { objc_setAssociatedObject(self, @selector(responseSerializer), responseSerializer, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } #pragma mark - - (void)loadRequest:(NSURLRequest *)request progress:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))progress success:(NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success failure:(void (^)(NSError *error))failure { [self loadRequest:request MIMEType:nil textEncodingName:nil progress:progress success:^NSData *(NSHTTPURLResponse *response, NSData *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 MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)textEncodingName progress:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))progress success:(NSData * (^)(NSHTTPURLResponse *response, NSData *data))success failure:(void (^)(NSError *error))failure { NSParameterAssert(request); if (self.af_HTTPRequestOperation) { [self.af_HTTPRequestOperation cancel]; } request = [self.requestSerializer requestBySerializingRequest:request withParameters:nil error:nil]; self.af_HTTPRequestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; self.af_HTTPRequestOperation.responseSerializer = self.responseSerializer; __weak __typeof(self)weakSelf = self; [self.af_HTTPRequestOperation setDownloadProgressBlock:progress]; [self.af_HTTPRequestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id __unused responseObject) { NSData *data = success ? success(operation.response, operation.responseData) : operation.responseData; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wgnu" __strong __typeof(weakSelf) strongSelf = weakSelf; [strongSelf loadData:data MIMEType:(MIMEType ?: [operation.response MIMEType]) textEncodingName:(textEncodingName ?: [operation.response textEncodingName]) baseURL:[operation.response URL]]; if ([strongSelf.delegate respondsToSelector:@selector(webViewDidFinishLoad:)]) { [strongSelf.delegate webViewDidFinishLoad:strongSelf]; } #pragma clang diagnostic pop } failure:^(AFHTTPRequestOperation * __unused operation, NSError *error) { if (failure) { failure(error); } }]; [self.af_HTTPRequestOperation start]; if ([self.delegate respondsToSelector:@selector(webViewDidStartLoad:)]) { [self.delegate webViewDidStartLoad:self]; } } @end #endif
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/DXRefresh/Pod/Classes/UIScrollView+DXRefresh.h
C/C++ Header
// // UIScrollView+DXRefresh.h // DXRefresh // // Created by xiekw on 10/11/14. // Copyright (c) 2014 xiekw. All rights reserved. // #import <UIKit/UIKit.h> @interface UIScrollView (DXRefresh) - (void)addHeaderWithTarget:(id)target action:(SEL)action withIndicatorColor:(UIColor *)color; - (void)addHeaderWithTarget:(id)target action:(SEL)action; - (void)addHeaderWithBlock:(dispatch_block_t)block withIndicatorColor:(UIColor *)color; - (void)addHeaderWithBlock:(dispatch_block_t)block; - (void)headerBeginRefreshing; - (void)headerEndRefreshing; - (BOOL)isHeaderRefreshing; /** * iOS 7 RefreshControl have some bugs, this is a solution for the situation when pull half of it, and then switch tabs or press iPhone home button and then back to screen You should use it in these two situation: 1. - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; [self.tableView relaxHeader]; } 2. - (void)viewDidLoad { ... // end of this [[NSNotificationCenter defaultCenter] addObserver:self.tableView selector:@selector(relaxHeader) name:UIApplicationDidBecomeActiveNotification object:nil]; } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self.tableView name:UIApplicationDidBecomeActiveNotification object:nil]; } You must imp these two methods */ - (void)relaxHeader; - (void)removeHeader; - (void)addFooterWithTarget:(id)target action:(SEL)action withIndicatorColor:(UIColor *)color; - (void)addFooterWithTarget:(id)target action:(SEL)action; - (void)addFooterWithBlock:(dispatch_block_t)block withIndicatorColor:(UIColor *)color; - (void)addFooterWithBlock:(dispatch_block_t)block; /** * Trigger footer target's action * * @param scroll If YES, then it will jump to the footer position of the scrollview */ - (void)footerBeginRefreshingScrollToFooter:(BOOL)scroll; /** * Same as footerBeginRefreshingScrollToFooter:NO */ - (void)footerBeginRefreshing; - (void)footerEndRefreshing; - (BOOL)isFooterRefreshing; - (void)removeFooter; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/DXRefresh/Pod/Classes/UIScrollView+DXRefresh.m
Objective-C
// // UIScrollView+DXRefresh.m // DXRefresh // // Created by xiekw on 10/11/14. // Copyright (c) 2014 xiekw. All rights reserved. // #import "UIScrollView+DXRefresh.h" #import <objc/runtime.h> @protocol DXRefreshView <NSObject> @required - (void)beginRefreshing; - (void)endRefreshing; - (BOOL)isRefreshing; @optional + (CGFloat)standHeight; + (CGFloat)standTriggerHeight; @end @interface DXRfreshFooter : UIControl<DXRefreshView> { CGFloat _cutBottomOffset; } @property (nonatomic, strong) UIActivityIndicatorView *acv; @property (nonatomic, assign) BOOL refreshing; @property (nonatomic, assign) BOOL observed; - (void)beginRefreshing; - (void)endRefreshing; - (BOOL)isRefreshing; + (CGFloat)standHeight; + (CGFloat)standTriggerHeight; @end @implementation DXRfreshFooter - (void)dealloc { if (self.observed) { [self.superview removeObserver:self forKeyPath:@"contentSize" context:nil]; [self.superview removeObserver:self forKeyPath:@"contentOffset" context:nil]; self.observed = NO; } } + (CGFloat)standHeight { return 44.0; } + (CGFloat)standTriggerHeight { return [self standHeight] + 20.0; } - (void)beginRefreshing { self.refreshing = YES; [self.acv startAnimating]; } - (BOOL)isRefreshing { return self.acv.isAnimating; } - (void)endRefreshing { //wierd handle way, otherwise it will flash the table view when reloaddata __weak typeof(self)wself = self; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ wself.refreshing = NO; [wself.acv stopAnimating]; [UIView animateWithDuration:0.1 delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{ if (wself.superview) { UIScrollView *scrollView = (UIScrollView *)wself.superview; NSLog(@"_cut bottom offset is %f", _cutBottomOffset); scrollView.contentInset = UIEdgeInsetsMake(scrollView.contentInset.top, 0.0f, MAX(0, scrollView.contentInset.bottom - _cutBottomOffset), 0.0f); _cutBottomOffset = 0.0; } } completion:^(BOOL finished) { }]; }); } - (id)initWithFrame:(CGRect)frame { if (self = [super initWithFrame:frame]) { self.autoresizingMask = UIViewAutoresizingFlexibleWidth; self.acv = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]; CGFloat height = CGRectGetHeight(frame) * 0.8; self.acv.frame = CGRectMake(0, 0, height, height); self.acv.center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds)); self.acv.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin; [self addSubview:self.acv]; } return self; } - (void)willMoveToSuperview:(UIView *)newSuperview { [super willMoveToSuperview:newSuperview]; if (self.observed) { [self.superview removeObserver:self forKeyPath:@"contentSize" context:nil]; [self.superview removeObserver:self forKeyPath:@"contentOffset" context:nil]; self.observed = NO; } if (newSuperview && [newSuperview isKindOfClass:[UIScrollView class]]) { [newSuperview addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil]; [newSuperview addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil]; self.observed = YES; [self adjustFrameWithContentSize]; } } - (void)adjustFrameWithContentSize { UIScrollView *scrollView = (UIScrollView *)self.superview; CGFloat contentHeight = scrollView.contentSize.height; CGFloat scrollHeight = scrollView.frame.size.height - scrollView.contentInset.top - scrollView.contentInset.bottom; CGRect selfFrame = self.frame; selfFrame.origin.y = MAX(contentHeight, scrollHeight); self.frame = selfFrame; } - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if (!self.userInteractionEnabled || self.alpha <= 0.01 || self.hidden) return; if ([@"contentSize" isEqualToString:keyPath]) { [self adjustFrameWithContentSize]; } else if ([@"contentOffset" isEqualToString:keyPath]) { UIScrollView *scrollView = (UIScrollView *)self.superview; if (scrollView.contentOffset.y <= 0) { return; } if (scrollView.contentOffset.y+(scrollView.frame.size.height) > scrollView.contentSize.height+[DXRfreshFooter standTriggerHeight] + scrollView.contentInset.bottom && !self.refreshing) { [self beginRefreshing]; [UIView animateWithDuration:0.2 delay:0.01 options:UIViewAnimationOptionCurveEaseIn animations:^{ _cutBottomOffset = [DXRfreshFooter standHeight]; scrollView.contentInset = UIEdgeInsetsMake(scrollView.contentInset.top, 0.0f, scrollView.contentInset.bottom + _cutBottomOffset, 0.0f); } completion:^(BOOL finished) { }]; [self sendActionsForControlEvents:UIControlEventValueChanged]; } } } @end @interface UIScrollView () @property (nonatomic, strong) UIControl<DXRefreshView> *header; @property (nonatomic, strong) DXRfreshFooter *footer; @end @implementation UIScrollView (DXRefresh) static char DXRefreshHeaderViewKey; static char DXRefreshFooterViewKey; static char DXHeaderBlockKey; static char DXFooterBlockKey; - (void)setHeader:(UIView *)header { objc_setAssociatedObject(self, &DXRefreshHeaderViewKey, header, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - (UIView *)header { return objc_getAssociatedObject(self, &DXRefreshHeaderViewKey); } - (void)setFooter:(UIView *)footer { objc_setAssociatedObject(self, &DXRefreshFooterViewKey, footer, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - (UIView *)footer { return objc_getAssociatedObject(self, &DXRefreshFooterViewKey); } - (void)setHeaderBlock:(dispatch_block_t)block { objc_setAssociatedObject(self, &DXHeaderBlockKey, block, OBJC_ASSOCIATION_COPY_NONATOMIC); } - (dispatch_block_t)headerBlock { return objc_getAssociatedObject(self, &DXHeaderBlockKey); } - (void)setFooterBlock:(dispatch_block_t)block { objc_setAssociatedObject(self, &DXFooterBlockKey, block, OBJC_ASSOCIATION_COPY_NONATOMIC); } - (dispatch_block_t)footerBlock { return objc_getAssociatedObject(self, &DXFooterBlockKey); } - (void)addHeaderWithTarget:(id)target action:(SEL)action withIndicatorColor:(UIColor *)color { if (self.header) { return; } UIRefreshControl *refresh = [[UIRefreshControl alloc] init]; if (color) { refresh.tintColor = color; } self.alwaysBounceVertical = YES; self.header = (UIControl<DXRefreshView> *)refresh; [self addSubview:self.header]; [self.header addTarget:target action:action forControlEvents:UIControlEventValueChanged]; } - (void)addHeaderWithTarget:(id)target action:(SEL)action { [self addHeaderWithTarget:target action:action withIndicatorColor:nil]; } - (void)relaxHeader { if ([self.header isKindOfClass:[UIRefreshControl class]]) { UIRefreshControl *refresh = (UIRefreshControl *)self.header; if (refresh.isRefreshing) { }else { [refresh endRefreshing]; } } } - (void)removeHeader { [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil]; [self.header removeFromSuperview]; self.header = nil; } static CGFloat const _kRefreshControlHeight = -64.0; - (void)headerBeginRefreshing { if ([self.header isKindOfClass:[UIRefreshControl class]]) { UIRefreshControl *refresh = (UIRefreshControl *)self.header; CGFloat contentOffsetY = _kRefreshControlHeight - self.contentInset.top; [self setContentOffset:CGPointMake(0, contentOffsetY) animated:YES]; [refresh beginRefreshing]; } } - (void)headerEndRefreshing { if ([self.header isKindOfClass:[UIRefreshControl class]]) { UIRefreshControl *refresh = (UIRefreshControl *)self.header; [refresh endRefreshing]; } } - (BOOL)isHeaderRefreshing { if ([self.header isKindOfClass:[UIRefreshControl class]]) { UIRefreshControl *refresh = (UIRefreshControl *)self.header; return refresh.isRefreshing; } return NO; } - (void)addFooterWithTarget:(id)target action:(SEL)action withIndicatorColor:(UIColor *)color { if (self.footer) { return; } self.footer = [[DXRfreshFooter alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.bounds), [DXRfreshFooter standHeight])]; if (color) { self.footer.acv.color = color; } [self.footer addTarget:target action:action forControlEvents:UIControlEventValueChanged]; [self addSubview:self.footer]; } - (void)addFooterWithTarget:(id)target action:(SEL)action { [self addFooterWithTarget:target action:action withIndicatorColor:nil]; } - (void)footerBeginRefreshing { [self footerBeginRefreshingScrollToFooter:NO]; } - (void)footerBeginRefreshingScrollToFooter:(BOOL)scroll { if (!self.footer) { return; } if (scroll) { CGFloat upOffset = self.contentSize.height - CGRectGetHeight(self.bounds); upOffset = MAX(0, upOffset); [self setContentOffset:CGPointMake(0, upOffset + [DXRfreshFooter standTriggerHeight]) animated:YES]; } [self.footer beginRefreshing]; } - (void)footerEndRefreshing { [self.footer endRefreshing]; } - (BOOL)isFooterRefreshing { return self.footer.isRefreshing; } - (void)removeFooter { [self.footer removeFromSuperview]; self.footer = nil; } - (void)addHeaderWithBlock:(dispatch_block_t)block withIndicatorColor:(UIColor *)color { if (block) { self.headerBlock = block; } if (self.header) { return; } UIRefreshControl *refresh = [[UIRefreshControl alloc] init]; if (color) { refresh.tintColor = color; } self.alwaysBounceVertical = YES; self.header = (UIControl<DXRefreshView> *)refresh; [self addSubview:self.header]; [self.header addTarget:self action:@selector(_headerAction) forControlEvents:UIControlEventValueChanged]; } - (void)addHeaderWithBlock:(dispatch_block_t)block { [self addHeaderWithBlock:block withIndicatorColor:nil]; } - (void)_headerAction { if (self.headerBlock) { self.headerBlock(); } } - (void)addFooterWithBlock:(dispatch_block_t)block withIndicatorColor:(UIColor *)color { if (block) { self.footerBlock = block; } if (self.footer) { return; } self.footer = [[DXRfreshFooter alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.bounds), [DXRfreshFooter standHeight])]; if (color) { self.footer.acv.color = color; } [self.footer addTarget:self action:@selector(_footerAction) forControlEvents:UIControlEventValueChanged]; [self addSubview:self.footer]; } - (void)addFooterWithBlock:(dispatch_block_t)block { [self addFooterWithBlock:block withIndicatorColor:nil]; } - (void)_footerAction { if (self.footerBlock) { self.footerBlock(); } } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/attributedlabel/src/NIAttributedLabel.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // Originally created by Roger Chapman // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <UIKit/UIKit.h> #import <CoreText/CoreText.h> #import "NimbusCore.h" // For __NI_DEPRECATED_METHOD #if defined __cplusplus extern "C" { #endif /** * Calculates the ideal dimensions of an attributed string fitting a given size. * * This calculation is performed off the raw attributed string so this calculation may differ * slightly from NIAttributedLabel's use of it due to lack of link and image attributes. * * This method is used in NIAttributedLabel to calculate its size after all additional * styling attributes have been set. */ CGSize NISizeOfAttributedStringConstrainedToSize(NSAttributedString* attributedString, CGSize size, NSInteger numberOfLines); #if defined __cplusplus }; #endif // Vertical alignments for NIAttributedLabel. typedef enum { NIVerticalTextAlignmentTop = 0, NIVerticalTextAlignmentMiddle, NIVerticalTextAlignmentBottom, } NIVerticalTextAlignment; extern NSString* const NIAttributedLabelLinkAttributeName; // Value is an NSTextCheckingResult. @protocol NIAttributedLabelDelegate; /** * The NIAttributedLabel class provides support for displaying rich text with selectable links and * embedded images. * * Differences between UILabel and NIAttributedLabel: * * - @c NSLineBreakByTruncatingHead and @c NSLineBreakByTruncatingMiddle only apply to single * lines and will not wrap the label regardless of the @c numberOfLines property. To wrap lines * with any of these line break modes you must explicitly add newline characters to the string. * - When you assign an NSString to the text property the attributed label will create an * attributed string that inherits all of the label's current styles. * - Text is aligned vertically to the top of the bounds by default rather than centered. You can * change this behavior using @link NIAttributedLabel::verticalTextAlignment verticalTextAlignment@endlink. * - CoreText fills the frame with glyphs until they no longer fit. This is an important difference * from UILabel because it means that CoreText will not add any glyphs that won't fit in the * frame, while UILabel does. This can result in empty NIAttributedLabels if your frame is too * small where UILabel would draw clipped text. It is recommended that you use sizeToFit to get * the correct dimensions of the attributed label before setting the frame. * * NIAttributedLabel implements the UIAccessibilityContainer methods to expose each link as an * accessibility item. * * @ingroup NimbusAttributedLabel */ @interface NIAttributedLabel : UILabel // Please use attributedText instead. MAINTENANCE: Remove by Feb 28, 2014. @property (nonatomic, copy) NSAttributedString* attributedString __NI_DEPRECATED_METHOD; @property (nonatomic) BOOL autoDetectLinks; // Default: NO @property (nonatomic) NSTextCheckingType dataDetectorTypes; // Default: NSTextCheckingTypeLink @property (nonatomic) BOOL deferLinkDetection; // Default: NO - (void)addLink:(NSURL *)urlLink range:(NSRange)range; - (void)removeAllExplicitLinks; // Removes all links that were added by addLink:range:. Does not remove autodetected links. @property (nonatomic, strong) UIColor* linkColor; // Default: self.tintColor (iOS 7) or [UIColor blueColor] (iOS 6) @property (nonatomic, strong) UIColor* highlightedLinkBackgroundColor; // Default: [UIColor colorWithWhite:0.5 alpha:0.5 @property (nonatomic) BOOL linksHaveUnderlines; // Default: NO @property (nonatomic, copy) NSDictionary* attributesForLinks; // Default: nil @property (nonatomic, copy) NSDictionary* attributesForHighlightedLink; // Default: nil @property (nonatomic) CGFloat lineHeight; @property (nonatomic) NIVerticalTextAlignment verticalTextAlignment; // Default: NIVerticalTextAlignmentTop @property (nonatomic) CTUnderlineStyle underlineStyle; @property (nonatomic) CTUnderlineStyleModifiers underlineStyleModifier; @property (nonatomic) CGFloat shadowBlur; // Default: 0 @property (nonatomic) CGFloat strokeWidth; @property (nonatomic, strong) UIColor* strokeColor; @property (nonatomic) CGFloat textKern; @property (nonatomic, copy) NSString* tailTruncationString; - (void)setFont:(UIFont *)font range:(NSRange)range; - (void)setStrokeColor:(UIColor *)color range:(NSRange)range; - (void)setStrokeWidth:(CGFloat)width range:(NSRange)range; - (void)setTextColor:(UIColor *)textColor range:(NSRange)range; - (void)setTextKern:(CGFloat)kern range:(NSRange)range; - (void)setUnderlineStyle:(CTUnderlineStyle)style modifier:(CTUnderlineStyleModifiers)modifier range:(NSRange)range; - (void)insertImage:(UIImage *)image atIndex:(NSInteger)index; - (void)insertImage:(UIImage *)image atIndex:(NSInteger)index margins:(UIEdgeInsets)margins; - (void)insertImage:(UIImage *)image atIndex:(NSInteger)index margins:(UIEdgeInsets)margins verticalTextAlignment:(NIVerticalTextAlignment)verticalTextAlignment; - (void)invalidateAccessibleElements; @property (nonatomic, weak) IBOutlet id<NIAttributedLabelDelegate> delegate; @end /** * The methods declared by the NIAttributedLabelDelegate protocol allow the adopting delegate to * respond to messages from the NIAttributedLabel class and thus respond to selections. * * @ingroup NimbusAttributedLabel */ @protocol NIAttributedLabelDelegate <NSObject> @optional /** @name Managing Selections */ /** * Informs the receiver that a data detector result has been selected. * * @param attributedLabel An attributed label informing the receiver of the selection. * @param result The data detector result that was selected. * @param point The point within @c attributedLabel where the result was tapped. */ - (void)attributedLabel:(NIAttributedLabel *)attributedLabel didSelectTextCheckingResult:(NSTextCheckingResult *)result atPoint:(CGPoint)point; /** * Asks the receiver whether an action sheet should be displayed at the given point. * * If this method is not implemented by the receiver then @c actionSheet will always be displayed. * * @c actionSheet will be populated with actions that match the data type that was selected. For * example, a link will have the actions "Open in Safari" and "Copy URL". A phone number will have * @"Call" and "Copy Phone Number". * * @param attributedLabel An attributed label asking the delegate whether to display the action * sheet. * @param actionSheet The action sheet that will be displayed if YES is returned. * @param result The data detector result that was selected. * @param point The point within @c attributedLabel where the result was tapped. * @returns YES if @c actionSheet should be displayed. NO if @c actionSheet should not be * displayed. */ - (BOOL)attributedLabel:(NIAttributedLabel *)attributedLabel shouldPresentActionSheet:(UIActionSheet *)actionSheet withTextCheckingResult:(NSTextCheckingResult *)result atPoint:(CGPoint)point; @end /** @name Accessing the Text Attributes */ /** * This method is now deprecated and will eventually be removed, please use attributedText instead. * * @fn NIAttributedLabel::attributedString */ /** @name Accessing and Detecting Links */ /** * A Booelan value indicating whether to automatically detect links in the string. * * By default this is disabled. * * Link detection is deferred until the label is displayed for the first time. If the text changes * then all of the links will be cleared and re-detected when the label displays again. * * Note that link detection is an expensive operation. If you are planning to use attributed labels * in table views or similar high-performance situations then you should consider enabling defered * link detection by setting @link NIAttributedLabel::deferLinkDetection deferLinkDetection@endlink * to YES. * * @sa NIAttributedLabel::dataDetectorTypes * @sa NIAttributedLabel::deferLinkDetection * @fn NIAttributedLabel::autoDetectLinks */ /** * A Boolean value indicating whether to defer link detection to a separate thread. * * By default this is disabled. * * When defering is enabled, link detection will be performed on a separate thread. This will cause * your label to appear without any links briefly before being redrawn with the detected links. * This offloads the data detection to a separate thread so that your labels can be displayed * faster. * * @fn NIAttributedLabel::deferLinkDetection */ /** * The types of data that will be detected when * @link NIAttributedLabel::autoDetectLinks autoDetectLinks@endlink is enabled. * * By default this is NSTextCheckingTypeLink. <a href="https://developer.apple.com/library/mac/#documentation/AppKit/Reference/NSTextCheckingResult_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40008798-CH1-DontLinkElementID_50">All available data detector types</a>. * * @fn NIAttributedLabel::dataDetectorTypes */ /** * Adds a link to a URL at a given range. * * Adding any links will immediately enable user interaction on this label. Explicitly added * links are removed whenever the text changes. * * @fn NIAttributedLabel::addLink:range: */ /** * Removes all explicit links from the label. * * If you wish to remove automatically-detected links, set autoDetectLinks to NO. * * @fn NIAttributedLabel::removeAllExplicitLinks */ /** @name Accessing Link Display Styles */ /** * The text color of detected links. * * The default color is [UIColor blueColor] on pre-iOS 7 devices or self.tintColor on iOS 7 devices. * If linkColor is assigned nil then links will not be given any special color. Use * attributesForLinks to specify alternative styling. * * @image html NIAttributedLabelLinkAttributes.png "Link attributes" * * @fn NIAttributedLabel::linkColor */ /** * The background color of the link's selection frame when the user is touching the link. * * The default is [UIColor colorWithWhite:0.5 alpha:0.5]. * * If you do not want links to be highlighted when touched, set this to nil. * * @image html NIAttributedLabelLinkAttributes.png "Link attributes" * * @fn NIAttributedLabel::highlightedLinkBackgroundColor */ /** * A Boolean value indicating whether links should have underlines. * * By default this is disabled. * * This affects all links in the label. * * @fn NIAttributedLabel::linksHaveUnderlines */ /** * A dictionary of CoreText attributes to apply to links. * * This dictionary must contain CoreText attributes. These attributes are applied after the color * and underline styles have been applied to the link. * * @fn NIAttributedLabel::attributesForLinks */ /** * A dictionary of CoreText attributes to apply to the highlighted link. * * This dictionary must contain CoreText attributes. These attributes are applied after * attributesForLinks have been applied to the highlighted link. * * @fn NIAttributedLabel::attributesForHighlightedLink */ /** @name Modifying Rich Text Styles for All Text */ /** * The vertical alignment of the text within the label's bounds. * * The default is @c NIVerticalTextAlignmentTop. This is for performance reasons because the other * modes require more computation. Aligning to the top is generally what you want anyway. * * @c NIVerticalTextAlignmentBottom will align the text to the bottom of the bounds, while * @c NIVerticalTextAlignmentMiddle will center the text vertically. * * @fn NIAttributedLabel::verticalTextAlignment */ /** * The underline style for the entire label. * * By default this is @c kCTUnderlineStyleNone. * * <a href="https://developer.apple.com/library/mac/#documentation/Carbon/Reference/CoreText_StringAttributes_Ref/Reference/reference.html#//apple_ref/c/tdef/CTUnderlineStyle">View all available styles</a>. * * @fn NIAttributedLabel::underlineStyle */ /** * The underline style modifier for the entire label. * * By default this is @c kCTUnderlinePatternSolid. * * <a href="https://developer.apple.com/library/mac/#documentation/Carbon/Reference/CoreText_StringAttributes_Ref/Reference/reference.html#//apple_ref/c/tdef/CTUnderlineStyleModifiers">View all available style * modifiers</a>. * * @fn NIAttributedLabel::underlineStyleModifier */ /** * A non-negative number specifying the amount of blur to apply to the label's text shadow. * * By default this is zero. * * @fn NIAttributedLabel::shadowBlur */ /** * Sets the stroke width for the text. * * By default this is zero. * * Positive numbers will draw the stroke. Negative numbers will draw the stroke and fill. * * @fn NIAttributedLabel::strokeWidth */ /** * Sets the stroke color for the text. * * By default this is nil. * * @fn NIAttributedLabel::strokeColor */ /** * Sets the line height for the text. * * By default this is zero. * * Setting this value to zero will make the label use the default line height for the text's font. * * @fn NIAttributedLabel::lineHeight */ /** * Sets the kern for the text. * * By default this is zero. * * The text kern indicates how many points each character should be shifted from its default offset. * A positive kern indicates a shift farther away. A negative kern indicates a shift closer. * * @fn NIAttributedLabel::textKern */ /** @name Modifying Tail Truncation Properties */ /** * The string to display for tail truncation. * * By default this is nil and the default ellipses character, \u2026, is used. * * @fn NIAttributedLabel::tailTruncationString */ /** @name Modifying Rich Text Styles in Ranges */ /** * Sets the text color for text in a given range. * * @fn NIAttributedLabel::setTextColor:range: */ /** * Sets the font for text in a given range. * * @fn NIAttributedLabel::setFont:range: */ /** * Sets the underline style and modifier for text in a given range. * * <a href="https://developer.apple.com/library/mac/#documentation/Carbon/Reference/CoreText_StringAttributes_Ref/Reference/reference.html#//apple_ref/c/tdef/CTUnderlineStyle">View all available styles</a>. * * <a href="https://developer.apple.com/library/mac/#documentation/Carbon/Reference/CoreText_StringAttributes_Ref/Reference/reference.html#//apple_ref/c/tdef/CTUnderlineStyleModifiers">View all available style * modifiers</a>. * * @fn NIAttributedLabel::setUnderlineStyle:modifier:range: */ /** * Sets the stroke width for text in a given range. * * Positive numbers will draw the stroke. Negative numbers will draw the stroke and fill. * * @fn NIAttributedLabel::setStrokeWidth:range: */ /** * Sets the stroke color for text in a given range. * * @fn NIAttributedLabel::setStrokeColor:range: */ /** * Sets the kern for text in a given range. * * The text kern indicates how many points each character should be shifted from its default offset. * A positive kern indicates a shift farther away. A negative kern indicates a shift closer. * * @fn NIAttributedLabel::setTextKern:range: */ /** @name Adding Inline Images */ /** * Inserts the given image inline at the given index in the receiver's text. * * The image will have no margins. * The image's vertical text alignment will be NIVerticalTextAlignmentBottom. * * @param image The image to add to the receiver. * @param index The index into the receiver's text at which to insert the image. * @fn NIAttributedLabel::insertImage:atIndex: */ /** * Inserts the given image inline at the given index in the receiver's text. * * The image's vertical text alignment will be NIVerticalTextAlignmentBottom. * * @param image The image to add to the receiver. * @param index The index into the receiver's text at which to insert the image. * @param margins The space around the image on all sides in points. * @fn NIAttributedLabel::insertImage:atIndex:margins: */ /** * Inserts the given image inline at the given index in the receiver's text. * * @attention * Images do not currently support NIVerticalTextAlignmentTop and the receiver will fire * multiple debug assertions if you attempt to use it. * * @param image The image to add to the receiver. * @param index The index into the receiver's text at which to insert the image. * @param margins The space around the image on all sides in points. * @param verticalTextAlignment The position of the text relative to the image. * @fn NIAttributedLabel::insertImage:atIndex:margins:verticalTextAlignment: */ /** @name Accessibility */ /** * Invalidates this label's accessible elements. * * When a label is contained within another view and that parent view moves, the label will not be * informed of this change and any existing accessibility elements will still point to the old * screen location. If this happens you must call -invalidateAccessibleElements in order to force * the label to refresh its accessibile elements. * * @fn NIAttributedLabel::invalidateAccessibleElements */ /** @name Accessing the Delegate */ /** * The delegate of the attributed-label object. * * The delegate must adopt the NIAttributedLabelDelegate protocol. The NIAttributedLabel class, * which does not strong the delegate, invokes each protocol method the delegate implements. * * @fn NIAttributedLabel::delegate */
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/attributedlabel/src/NIAttributedLabel.m
Objective-C
// // Copyright 2011-2014 NimbusKit // Originally created by Roger Chapman // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NIAttributedLabel.h" #import "NSMutableAttributedString+NimbusAttributedLabel.h" #import <QuartzCore/QuartzCore.h> #if !defined(__has_feature) || !__has_feature(objc_arc) #error "Nimbus requires ARC support." #endif #if __IPHONE_OS_VERSION_MIN_REQUIRED < NIIOS_6_0 #error "NIAttributedLabel requires iOS 6 or higher." #endif // The number of seconds to wait before executing a long press action on the tapped link. static const NSTimeInterval kLongPressTimeInterval = 0.5; // The number of pixels the user's finger must move before cancelling the long press timer. static const CGFloat kLongPressGutter = 22; // The touch gutter is the amount of space around a link that will still register as tapping // "within" the link. static const CGFloat kTouchGutter = 22; static const CGFloat kVMargin = 5.0f; // \u2026 is the Unicode horizontal ellipsis character code static NSString* const kEllipsesCharacter = @"\u2026"; NSString* const NIAttributedLabelLinkAttributeName = @"NIAttributedLabel:Link"; // For supporting images. CGFloat NIImageDelegateGetAscentCallback(void* refCon); CGFloat NIImageDelegateGetDescentCallback(void* refCon); CGFloat NIImageDelegateGetWidthCallback(void* refCon); CGSize NISizeOfAttributedStringConstrainedToSize(NSAttributedString* attributedString, CGSize constraintSize, NSInteger numberOfLines) { if (nil == attributedString) { return CGSizeZero; } CFAttributedStringRef attributedStringRef = (__bridge CFAttributedStringRef)attributedString; CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(attributedStringRef); CFRange range = CFRangeMake(0, 0); // This logic adapted from @mattt's TTTAttributedLabel // https://github.com/mattt/TTTAttributedLabel if (numberOfLines == 1) { constraintSize = CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX); } else if (numberOfLines > 0 && nil != framesetter) { CGMutablePathRef path = CGPathCreateMutable(); CGPathAddRect(path, NULL, CGRectMake(0, 0, constraintSize.width, constraintSize.height)); CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, NULL); CFArrayRef lines = CTFrameGetLines(frame); if (nil != lines && CFArrayGetCount(lines) > 0) { NSInteger lastVisibleLineIndex = MIN(numberOfLines, CFArrayGetCount(lines)) - 1; CTLineRef lastVisibleLine = CFArrayGetValueAtIndex(lines, lastVisibleLineIndex); CFRange rangeToLayout = CTLineGetStringRange(lastVisibleLine); range = CFRangeMake(0, rangeToLayout.location + rangeToLayout.length); } CFRelease(frame); CFRelease(path); } CGSize newSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, range, NULL, constraintSize, NULL); if (nil != framesetter) { CFRelease(framesetter); framesetter = nil; } return CGSizeMake(NICGFloatCeil(newSize.width), NICGFloatCeil(newSize.height)); } @interface NIAttributedLabelImage : NSObject - (CGSize)boxSize; // imageSize + margins @property (nonatomic) NSInteger index; @property (nonatomic, strong) UIImage* image; @property (nonatomic) UIEdgeInsets margins; @property (nonatomic) NIVerticalTextAlignment verticalTextAlignment; @property (nonatomic) CGFloat fontAscent; @property (nonatomic) CGFloat fontDescent; @end @implementation NIAttributedLabelImage - (CGSize)boxSize { return CGSizeMake(self.image.size.width + self.margins.left + self.margins.right, self.image.size.height + self.margins.top + self.margins.bottom); } @end @interface NIAttributedLabel() <UIActionSheetDelegate> @property (nonatomic, strong) NSMutableAttributedString* mutableAttributedString; @property (nonatomic) CTFrameRef textFrame; // CFType, manually managed lifetime, see setter. @property (assign) BOOL detectingLinks; // Atomic. @property (nonatomic) BOOL linksHaveBeenDetected; @property (nonatomic, copy) NSArray* detectedlinkLocations; @property (nonatomic, strong) NSMutableArray* explicitLinkLocations; @property (nonatomic, strong) NSTextCheckingResult* originalLink; @property (nonatomic, strong) NSTextCheckingResult* touchedLink; @property (nonatomic, strong) NSTimer* longPressTimer; @property (nonatomic) CGPoint touchPoint; @property (nonatomic, strong) NSTextCheckingResult* actionSheetLink; @property (nonatomic, copy) NSArray* accessibleElements; @property (nonatomic, strong) NSMutableArray *images; @end @interface NIAttributedLabel (ConversionUtilities) + (CTTextAlignment)alignmentFromUITextAlignment:(NSTextAlignment)alignment; + (CTLineBreakMode)lineBreakModeFromUILineBreakMode:(NSLineBreakMode)lineBreakMode; + (NSMutableAttributedString *)mutableAttributedStringFromLabel:(UILabel *)label; @end @implementation NIAttributedLabel @synthesize textFrame = _textFrame; - (void)dealloc { [_longPressTimer invalidate]; // The property is marked 'assign', but retain count for this CFType is managed here and via // the setter. if (NULL != _textFrame) { CFRelease(_textFrame); } } - (CTFrameRef)textFrame { if (NULL == _textFrame) { NSMutableAttributedString* attributedStringWithLinks = [self mutableAttributedStringWithAdditions]; CFAttributedStringRef attributedString = (__bridge CFAttributedStringRef)attributedStringWithLinks; CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(attributedString); CGMutablePathRef path = CGPathCreateMutable(); CGPathAddRect(path, NULL, self.bounds); CTFrameRef textFrame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, NULL); self.textFrame = textFrame; if (textFrame) { CFRelease(textFrame); } CGPathRelease(path); CFRelease(framesetter); } return _textFrame; } - (void)setTextFrame:(CTFrameRef)textFrame { // The property is marked 'assign', but retain count for this CFType is managed via this setter // and -dealloc. if (textFrame != _textFrame) { if (NULL != _textFrame) { CFRelease(_textFrame); } if (NULL != textFrame) { CFRetain(textFrame); } _textFrame = textFrame; } } - (void)_configureDefaults { self.verticalTextAlignment = NIVerticalTextAlignmentTop; self.linkColor = NIIsTintColorGloballySupported() ? self.tintColor : [UIColor blueColor]; self.dataDetectorTypes = NSTextCheckingTypeLink; self.highlightedLinkBackgroundColor = [UIColor colorWithWhite:0.5f alpha:0.5f]; } - (id)initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])) { [self _configureDefaults]; } return self; } - (void)awakeFromNib { [super awakeFromNib]; [self _configureDefaults]; self.attributedText = [[self class] mutableAttributedStringFromLabel:self]; } - (void)resetTextFrame { self.textFrame = NULL; self.accessibleElements = nil; } - (void)attributedTextDidChange { [self resetTextFrame]; [self invalidateIntrinsicContentSize]; [self setNeedsDisplay]; } - (void)setFrame:(CGRect)frame { BOOL frameDidChange = !CGRectEqualToRect(self.frame, frame); [super setFrame:frame]; if (frameDidChange) { [self attributedTextDidChange]; } } - (CGSize)sizeThatFits:(CGSize)size { if (nil == self.mutableAttributedString) { return CGSizeZero; } return NISizeOfAttributedStringConstrainedToSize([self mutableAttributedStringWithAdditions], size, self.numberOfLines); } - (CGSize)intrinsicContentSize { return [self sizeThatFits:[super intrinsicContentSize]]; } #pragma mark - Public - (void)setText:(NSString *)text { [super setText:text]; self.attributedText = [[self class] mutableAttributedStringFromLabel:self]; // Apply NIAttributedLabel-specific styles. [self.mutableAttributedString setUnderlineStyle:_underlineStyle modifier:_underlineStyleModifier]; [self.mutableAttributedString setStrokeWidth:_strokeWidth]; [self.mutableAttributedString setStrokeColor:_strokeColor]; [self.mutableAttributedString setKern:_textKern]; } // Deprecated. - (void)setAttributedString:(NSAttributedString *)attributedString { self.attributedText = attributedString; } // Deprecated. - (NSAttributedString *)attributedString { return self.attributedText; } - (NSAttributedString *)attributedText { return [self.mutableAttributedString copy]; } - (void)setAttributedText:(NSAttributedString *)attributedText { if (self.mutableAttributedString != attributedText) { self.mutableAttributedString = [attributedText mutableCopy]; // Clear the link caches. self.detectedlinkLocations = nil; self.linksHaveBeenDetected = NO; [self removeAllExplicitLinks]; // Remove all images. self.images = nil; // Pull any explicit links from the attributed string itself [self _processLinksInAttributedString:self.mutableAttributedString]; [self attributedTextDidChange]; } } - (void)setAutoDetectLinks:(BOOL)autoDetectLinks { _autoDetectLinks = autoDetectLinks; [self attributedTextDidChange]; } - (void)addLink:(NSURL *)urlLink range:(NSRange)range { if (nil == self.explicitLinkLocations) { self.explicitLinkLocations = [[NSMutableArray alloc] init]; } NSTextCheckingResult* result = [NSTextCheckingResult linkCheckingResultWithRange:range URL:urlLink]; [self.explicitLinkLocations addObject:result]; [self attributedTextDidChange]; } - (void)removeAllExplicitLinks { self.explicitLinkLocations = nil; [self attributedTextDidChange]; } - (void)setTextAlignment:(NSTextAlignment)textAlignment { // We assume that the UILabel implementation will call setNeedsDisplay. Where we don't call super // we call setNeedsDisplay ourselves. if (NSTextAlignmentJustified == textAlignment) { // iOS 6.0 Beta 2 crashes when using justified text alignments for some reason. [super setTextAlignment:NSTextAlignmentLeft]; } else { [super setTextAlignment:textAlignment]; } if (nil != self.mutableAttributedString) { CTTextAlignment alignment = [self.class alignmentFromUITextAlignment:textAlignment]; CTLineBreakMode lineBreak = [self.class lineBreakModeFromUILineBreakMode:self.lineBreakMode]; [self.mutableAttributedString setTextAlignment:alignment lineBreakMode:lineBreak lineHeight:self.lineHeight]; } } - (void)setLineBreakMode:(NSLineBreakMode)lineBreakMode { [super setLineBreakMode:lineBreakMode]; if (nil != self.mutableAttributedString) { CTTextAlignment alignment = [self.class alignmentFromUITextAlignment:self.textAlignment]; CTLineBreakMode lineBreak = [self.class lineBreakModeFromUILineBreakMode:lineBreakMode]; [self.mutableAttributedString setTextAlignment:alignment lineBreakMode:lineBreak lineHeight:self.lineHeight]; } } - (void)setTextColor:(UIColor *)textColor { [super setTextColor:textColor]; [self.mutableAttributedString setTextColor:textColor]; [self attributedTextDidChange]; } - (void)setTextColor:(UIColor *)textColor range:(NSRange)range { [self.mutableAttributedString setTextColor:textColor range:range]; [self attributedTextDidChange]; } - (void)setFont:(UIFont *)font { [super setFont:font]; [self.mutableAttributedString setFont:font]; [self attributedTextDidChange]; } - (void)setFont:(UIFont *)font range:(NSRange)range { [self.mutableAttributedString setFont:font range:range]; [self attributedTextDidChange]; } - (void)setUnderlineStyle:(CTUnderlineStyle)style { if (style != _underlineStyle) { _underlineStyle = style; [self.mutableAttributedString setUnderlineStyle:style modifier:self.underlineStyleModifier]; [self attributedTextDidChange]; } } - (void)setUnderlineStyleModifier:(CTUnderlineStyleModifiers)modifier { if (modifier != _underlineStyleModifier) { _underlineStyleModifier = modifier; [self.mutableAttributedString setUnderlineStyle:self.underlineStyle modifier:modifier]; [self attributedTextDidChange]; } } - (void)setUnderlineStyle:(CTUnderlineStyle)style modifier:(CTUnderlineStyleModifiers)modifier range:(NSRange)range { [self.mutableAttributedString setUnderlineStyle:style modifier:modifier range:range]; [self attributedTextDidChange]; } - (void)setShadowBlur:(CGFloat)shadowBlur { if (_shadowBlur != shadowBlur) { _shadowBlur = shadowBlur; [self attributedTextDidChange]; } } - (void)setStrokeWidth:(CGFloat)strokeWidth { if (_strokeWidth != strokeWidth) { _strokeWidth = strokeWidth; [self.mutableAttributedString setStrokeWidth:strokeWidth]; [self attributedTextDidChange]; } } - (void)setStrokeWidth:(CGFloat)width range:(NSRange)range { [self.mutableAttributedString setStrokeWidth:width range:range]; [self attributedTextDidChange]; } - (void)setStrokeColor:(UIColor *)strokeColor { if (_strokeColor != strokeColor) { _strokeColor = strokeColor; [self.mutableAttributedString setStrokeColor:_strokeColor]; [self attributedTextDidChange]; } } - (void)setStrokeColor:(UIColor*)color range:(NSRange)range { [self.mutableAttributedString setStrokeColor:color range:range]; [self attributedTextDidChange]; } - (void)setTextKern:(CGFloat)textKern { if (_textKern != textKern) { _textKern = textKern; [self.mutableAttributedString setKern:_textKern]; [self attributedTextDidChange]; } } - (void)setTextKern:(CGFloat)kern range:(NSRange)range { [self.mutableAttributedString setKern:kern range:range]; [self attributedTextDidChange]; } - (void)setTailTruncationString:(NSString *)tailTruncationString { if (![_tailTruncationString isEqualToString:tailTruncationString]) { _tailTruncationString = [tailTruncationString copy]; [self attributedTextDidChange]; } } - (void)setLinkColor:(UIColor *)linkColor { if (_linkColor != linkColor) { _linkColor = linkColor; [self attributedTextDidChange]; } } - (void)setLineHeight:(CGFloat)lineHeight { _lineHeight = lineHeight; if (nil != self.mutableAttributedString) { CTTextAlignment alignment = [self.class alignmentFromUITextAlignment:self.textAlignment]; CTLineBreakMode lineBreak = [self.class lineBreakModeFromUILineBreakMode:self.lineBreakMode]; [self.mutableAttributedString setTextAlignment:alignment lineBreakMode:lineBreak lineHeight:self.lineHeight]; [self attributedTextDidChange]; } } - (void)setHighlightedLinkBackgroundColor:(UIColor *)highlightedLinkBackgroundColor { if (_highlightedLinkBackgroundColor != highlightedLinkBackgroundColor) { _highlightedLinkBackgroundColor = highlightedLinkBackgroundColor; [self attributedTextDidChange]; } } - (void)setLinksHaveUnderlines:(BOOL)linksHaveUnderlines { if (_linksHaveUnderlines != linksHaveUnderlines) { _linksHaveUnderlines = linksHaveUnderlines; [self attributedTextDidChange]; } } - (void)setAttributesForLinks:(NSDictionary *)attributesForLinks { if (_attributesForLinks != attributesForLinks) { _attributesForLinks = attributesForLinks; [self attributedTextDidChange]; } } - (void)setAttributesForHighlightedLink:(NSDictionary *)attributesForHighlightedLink { if (_attributesForHighlightedLink != attributesForHighlightedLink) { _attributesForHighlightedLink = attributesForHighlightedLink; [self attributedTextDidChange]; } } - (void)setExplicitLinkLocations:(NSMutableArray *)explicitLinkLocations { if (_explicitLinkLocations != explicitLinkLocations) { _explicitLinkLocations = explicitLinkLocations; self.accessibleElements = nil; } } - (void)setDetectedlinkLocations:(NSArray *)detectedlinkLocations{ if (_detectedlinkLocations != detectedlinkLocations) { _detectedlinkLocations = detectedlinkLocations; self.accessibleElements = nil; } } - (void)setHighlighted:(BOOL)highlighted { BOOL didChange = self.highlighted != highlighted; [super setHighlighted:highlighted]; if (didChange) { [self attributedTextDidChange]; } } - (void)setHighlightedTextColor:(UIColor *)highlightedTextColor { BOOL didChange = self.highlightedTextColor != highlightedTextColor; [super setHighlightedTextColor:highlightedTextColor]; if (didChange) { [self attributedTextDidChange]; } } - (NSArray *)_matchesFromAttributedString:(NSString *)string { NSError* error = nil; NSDataDetector* linkDetector = [NSDataDetector dataDetectorWithTypes:(NSTextCheckingTypes)self.dataDetectorTypes error:&error]; NSRange range = NSMakeRange(0, string.length); return [linkDetector matchesInString:string options:0 range:range]; } - (void)_deferLinkDetection { if (!self.detectingLinks) { self.detectingLinks = YES; NSString* string = [self.mutableAttributedString.string copy]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSArray* matches = [self _matchesFromAttributedString:string]; self.detectingLinks = NO; dispatch_async(dispatch_get_main_queue(), ^{ self.detectedlinkLocations = matches; self.linksHaveBeenDetected = YES; [self attributedTextDidChange]; }); }); } } // Use an NSDataDetector to find any implicit links in the text. The results are cached until // the text changes. - (void)detectLinks { if (nil == self.mutableAttributedString) { return; } if (self.autoDetectLinks && !self.linksHaveBeenDetected) { if (self.deferLinkDetection) { [self _deferLinkDetection]; } else { self.detectedlinkLocations = [self _matchesFromAttributedString:self.mutableAttributedString.string]; self.linksHaveBeenDetected = YES; } } } - (CGRect)getLineBounds:(CTLineRef)line point:(CGPoint) point { CGFloat ascent = 0.0f; CGFloat descent = 0.0f; CGFloat leading = 0.0f; CGFloat width = (CGFloat)CTLineGetTypographicBounds(line, &ascent, &descent, &leading); CGFloat height = ascent + descent; return CGRectMake(point.x, point.y - descent, width, height); } - (NSTextCheckingResult *)linkAtIndex:(CFIndex)i { NSTextCheckingResult* foundResult = nil; if (self.autoDetectLinks) { [self detectLinks]; for (NSTextCheckingResult* result in self.detectedlinkLocations) { if (NSLocationInRange(i, result.range)) { foundResult = result; break; } } } if (nil == foundResult) { for (NSTextCheckingResult* result in self.explicitLinkLocations) { if (NSLocationInRange(i, result.range)) { foundResult = result; break; } } } return foundResult; } - (void)_processLinksInAttributedString:(NSAttributedString *)attributedString { // Pull any attributes matching the link attribute from the attributed string and store them as // the current set of explicit links. This properly handles the value of the attribute being // either an NSURL or an NSString. __block NSMutableArray *links = [NSMutableArray array]; [attributedString enumerateAttribute:NIAttributedLabelLinkAttributeName inRange:NSMakeRange(0, attributedString.length) options:0 usingBlock:^(id value, NSRange range, BOOL *stop) { if (value != nil) { [links addObject:value]; } }]; self.explicitLinkLocations = links; } - (CGFloat)_verticalOffsetForBounds:(CGRect)bounds { CGFloat verticalOffset = 0; if (NIVerticalTextAlignmentTop != self.verticalTextAlignment) { // When the text is attached to the top we can easily just start drawing and leave the // remainder. This is the most performant case. // With other alignment modes we must calculate the size of the text first. CGSize textSize = [self sizeThatFits:CGSizeMake(bounds.size.width, CGFLOAT_MAX)]; if (NIVerticalTextAlignmentMiddle == self.verticalTextAlignment) { verticalOffset = floorf((bounds.size.height - textSize.height) / 2.f); } else if (NIVerticalTextAlignmentBottom == self.verticalTextAlignment) { verticalOffset = bounds.size.height - textSize.height; } } return verticalOffset; } - (CGAffineTransform)_transformForCoreText { // CoreText context coordinates are the opposite to UIKit so we flip the bounds return CGAffineTransformScale(CGAffineTransformMakeTranslation(0, self.bounds.size.height), 1.f, -1.f); } - (NSTextCheckingResult *)linkAtPoint:(CGPoint)point { if (!CGRectContainsPoint(CGRectInset(self.bounds, 0, -kVMargin), point)) { return nil; } CFArrayRef lines = CTFrameGetLines(self.textFrame); if (!lines) return nil; CFIndex count = CFArrayGetCount(lines); CGPoint origins[count]; CTFrameGetLineOrigins(self.textFrame, CFRangeMake(0,0), origins); CGAffineTransform transform = [self _transformForCoreText]; CGFloat verticalOffset = [self _verticalOffsetForBounds:self.bounds]; for (int i = 0; i < count; i++) { CGPoint linePoint = origins[i]; CTLineRef line = CFArrayGetValueAtIndex(lines, i); CGRect flippedRect = [self getLineBounds:line point:linePoint]; CGRect rect = CGRectApplyAffineTransform(flippedRect, transform); rect = CGRectInset(rect, 0, -kVMargin); rect = CGRectOffset(rect, 0, verticalOffset); if (CGRectContainsPoint(rect, point)) { CGPoint relativePoint = CGPointMake(point.x-CGRectGetMinX(rect), point.y-CGRectGetMinY(rect)); CFIndex idx = CTLineGetStringIndexForPosition(line, relativePoint); NSUInteger offset = 0; for (NIAttributedLabelImage *labelImage in self.images) { if (labelImage.index < idx) { offset++; } } NSTextCheckingResult* foundLink = [self linkAtIndex:idx - offset]; if (foundLink) { return foundLink; } } } return nil; } - (CGRect)_rectForRange:(NSRange)range inLine:(CTLineRef)line lineOrigin:(CGPoint)lineOrigin { CGRect rectForRange = CGRectZero; CFArrayRef runs = CTLineGetGlyphRuns(line); CFIndex runCount = CFArrayGetCount(runs); // Iterate through each of the "runs" (i.e. a chunk of text) and find the runs that // intersect with the range. for (CFIndex k = 0; k < runCount; k++) { CTRunRef run = CFArrayGetValueAtIndex(runs, k); CFRange stringRunRange = CTRunGetStringRange(run); NSRange lineRunRange = NSMakeRange(stringRunRange.location, stringRunRange.length); NSRange intersectedRunRange = NSIntersectionRange(lineRunRange, range); if (intersectedRunRange.length == 0) { // This run doesn't intersect the range, so skip it. continue; } CGFloat ascent = 0.0f; CGFloat descent = 0.0f; CGFloat leading = 0.0f; // Use of 'leading' doesn't properly highlight Japanese-character link. CGFloat width = (CGFloat)CTRunGetTypographicBounds(run, CFRangeMake(0, 0), &ascent, &descent, NULL); //&leading); CGFloat height = ascent + descent; CGFloat xOffset = CTLineGetOffsetForStringIndex(line, CTRunGetStringRange(run).location, nil); CGRect linkRect = CGRectMake(lineOrigin.x + xOffset - leading, lineOrigin.y - descent, width + leading, height); linkRect.origin.y = NICGFloatRound(linkRect.origin.y); linkRect.origin.x = NICGFloatRound(linkRect.origin.x); linkRect.size.width = NICGFloatRound(linkRect.size.width); linkRect.size.height = NICGFloatRound(linkRect.size.height); if (CGRectIsEmpty(rectForRange)) { rectForRange = linkRect; } else { rectForRange = CGRectUnion(rectForRange, linkRect); } } return rectForRange; } - (BOOL)isPoint:(CGPoint)point nearLink:(NSTextCheckingResult *)link { CFArrayRef lines = CTFrameGetLines(self.textFrame); if (nil == lines) { return NO; } CFIndex count = CFArrayGetCount(lines); CGPoint lineOrigins[count]; CTFrameGetLineOrigins(self.textFrame, CFRangeMake(0, 0), lineOrigins); CGAffineTransform transform = [self _transformForCoreText]; CGFloat verticalOffset = [self _verticalOffsetForBounds:self.bounds]; NSRange linkRange = link.range; BOOL isNearLink = NO; for (int i = 0; i < count; i++) { CTLineRef line = CFArrayGetValueAtIndex(lines, i); CGRect linkRect = [self _rectForRange:linkRange inLine:line lineOrigin:lineOrigins[i]]; if (!CGRectIsEmpty(linkRect)) { linkRect = CGRectApplyAffineTransform(linkRect, transform); linkRect = CGRectOffset(linkRect, 0, verticalOffset); linkRect = CGRectInset(linkRect, -kTouchGutter, -kTouchGutter); if (CGRectContainsPoint(linkRect, point)) { isNearLink = YES; break; } } } return isNearLink; } - (NSArray *)_rectsForLink:(NSTextCheckingResult *)link { CFArrayRef lines = CTFrameGetLines(self.textFrame); if (nil == lines) { return nil; } CFIndex count = CFArrayGetCount(lines); CGPoint lineOrigins[count]; CTFrameGetLineOrigins(self.textFrame, CFRangeMake(0, 0), lineOrigins); CGAffineTransform transform = [self _transformForCoreText]; CGFloat verticalOffset = [self _verticalOffsetForBounds:self.bounds]; NSRange linkRange = link.range; NSMutableArray* rects = [NSMutableArray array]; for (int i = 0; i < count; i++) { CTLineRef line = CFArrayGetValueAtIndex(lines, i); CGRect linkRect = [self _rectForRange:linkRange inLine:line lineOrigin:lineOrigins[i]]; if (!CGRectIsEmpty(linkRect)) { linkRect = CGRectApplyAffineTransform(linkRect, transform); linkRect = CGRectOffset(linkRect, 0, verticalOffset); [rects addObject:[NSValue valueWithCGRect:linkRect]]; } } return [rects copy]; } - (void)setTouchedLink:(NSTextCheckingResult *)touchedLink { if (_touchedLink != touchedLink) { _touchedLink = touchedLink; if (self.attributesForHighlightedLink.count > 0) { [self attributedTextDidChange]; } } } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch* touch = [touches anyObject]; CGPoint point = [touch locationInView:self]; self.touchedLink = [self linkAtPoint:point]; self.touchPoint = point; self.originalLink = self.touchedLink; if (self.originalLink) { [self.longPressTimer invalidate]; if (nil != self.touchedLink) { self.longPressTimer = [NSTimer scheduledTimerWithTimeInterval:kLongPressTimeInterval target:self selector:@selector(_longPressTimerDidFire:) userInfo:nil repeats:NO]; } } else { [super touchesBegan:touches withEvent:event]; } [self setNeedsDisplay]; } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { UITouch* touch = [touches anyObject]; CGPoint point = [touch locationInView:self]; if (self.originalLink) { // If the user moves their finger away from the original link, deselect it. // If the user moves their finger back to the original link, reselect it. // Don't allow other links to be selected other than the original link. if (nil != self.originalLink) { NSTextCheckingResult* oldTouchedLink = self.touchedLink; if ([self isPoint:point nearLink:self.originalLink]) { self.touchedLink = self.originalLink; } else { self.touchedLink = nil; } if (oldTouchedLink != self.touchedLink) { [self.longPressTimer invalidate]; self.longPressTimer = nil; [self setNeedsDisplay]; } } // If the user moves their finger within the link beyond a certain gutter amount, reset the // hold timer. The user must hold their finger still for the long press interval in order for // the long press action to fire. if (fabsf(self.touchPoint.x - point.x) >= kLongPressGutter || fabsf(self.touchPoint.y - point.y) >= kLongPressGutter) { [self.longPressTimer invalidate]; self.longPressTimer = nil; if (nil != self.touchedLink) { self.longPressTimer = [NSTimer scheduledTimerWithTimeInterval:kLongPressTimeInterval target:self selector:@selector(_longPressTimerDidFire:) userInfo:nil repeats:NO]; self.touchPoint = point; } } } else { [super touchesMoved:touches withEvent:event]; } } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { if (self.originalLink) { [self.longPressTimer invalidate]; self.longPressTimer = nil; UITouch* touch = [touches anyObject]; CGPoint point = [touch locationInView:self]; if (nil != self.originalLink) { if ([self isPoint:point nearLink:self.originalLink] && [self.delegate respondsToSelector:@selector(attributedLabel:didSelectTextCheckingResult:atPoint:)]) { [self.delegate attributedLabel:self didSelectTextCheckingResult:self.originalLink atPoint:point]; } } self.touchedLink = nil; self.originalLink = nil; [self setNeedsDisplay]; } else { [super touchesEnded:touches withEvent:event]; } } - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesCancelled:touches withEvent:event]; [self.longPressTimer invalidate]; self.longPressTimer = nil; self.touchedLink = nil; self.originalLink = nil; [self setNeedsDisplay]; } - (UIActionSheet *)actionSheetForResult:(NSTextCheckingResult *)result { UIActionSheet* actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil]; NSString* title = nil; if (NSTextCheckingTypeLink == result.resultType) { if ([result.URL.scheme isEqualToString:@"mailto"]) { title = result.URL.resourceSpecifier; [actionSheet addButtonWithTitle:NSLocalizedString(@"Open in Mail", @"")]; [actionSheet addButtonWithTitle:NSLocalizedString(@"Copy Email Address", @"")]; } else { title = result.URL.absoluteString; [actionSheet addButtonWithTitle:NSLocalizedString(@"Open in Safari", @"")]; [actionSheet addButtonWithTitle:NSLocalizedString(@"Copy URL", @"")]; } } else if (NSTextCheckingTypePhoneNumber == result.resultType) { title = result.phoneNumber; [actionSheet addButtonWithTitle:NSLocalizedString(@"Call", @"")]; [actionSheet addButtonWithTitle:NSLocalizedString(@"Copy Phone Number", @"")]; } else if (NSTextCheckingTypeAddress == result.resultType) { title = [self.mutableAttributedString.string substringWithRange:self.actionSheetLink.range]; [actionSheet addButtonWithTitle:NSLocalizedString(@"Open in Maps", @"")]; [actionSheet addButtonWithTitle:NSLocalizedString(@"Copy Address", @"")]; } else { // This type has not been implemented yet. NIDASSERT(NO); [actionSheet addButtonWithTitle:NSLocalizedString(@"Copy", @"")]; } actionSheet.title = title; if (!NIIsPad()) { [actionSheet setCancelButtonIndex:[actionSheet addButtonWithTitle:NSLocalizedString(@"Cancel", @"")]]; } return actionSheet; } - (void)_longPressTimerDidFire:(NSTimer *)timer { self.longPressTimer = nil; if (nil != self.touchedLink) { self.actionSheetLink = self.touchedLink; UIActionSheet* actionSheet = [self actionSheetForResult:self.actionSheetLink]; BOOL shouldPresent = YES; if ([self.delegate respondsToSelector:@selector(attributedLabel:shouldPresentActionSheet:withTextCheckingResult:atPoint:)]) { // Give the delegate the opportunity to not show the action sheet or to present their own. shouldPresent = [self.delegate attributedLabel:self shouldPresentActionSheet:actionSheet withTextCheckingResult:self.touchedLink atPoint:self.touchPoint]; } if (shouldPresent) { if (NIIsPad()) { [actionSheet showFromRect:CGRectMake(self.touchPoint.x - 22, self.touchPoint.y - 22, 44, 44) inView:self animated:YES]; } else { [actionSheet showInView:self]; } } else { self.actionSheetLink = nil; } } } - (void)_applyLinkStyleWithResults:(NSArray *)results toAttributedString:(NSMutableAttributedString *)attributedString { for (NSTextCheckingResult* result in results) { if (self.linkColor) { [attributedString setTextColor:self.linkColor range:result.range]; } // We add a no-op attribute in order to force a run to exist for each link. Otherwise the // runCount will be one in this line, causing the entire line to be highlighted rather than // just the link when when no special attributes are set. [attributedString removeAttribute:NIAttributedLabelLinkAttributeName range:result.range]; [attributedString addAttribute:NIAttributedLabelLinkAttributeName value:result range:result.range]; if (self.linksHaveUnderlines) { [attributedString setUnderlineStyle:kCTUnderlineStyleSingle modifier:kCTUnderlinePatternSolid range:result.range]; } if (self.attributesForLinks.count > 0) { [attributedString addAttributes:self.attributesForLinks range:result.range]; } if (self.attributesForHighlightedLink.count > 0 && NSEqualRanges(result.range, self.touchedLink.range)) { [attributedString addAttributes:self.attributesForHighlightedLink range:result.range]; } } } // We apply the additional styles immediately before we render the attributed string. This // composites the styles with the existing styles without losing any information. This // makes it possible to turn off links or remove them altogether without losing the existing // style information. - (NSMutableAttributedString *)mutableAttributedStringWithAdditions { NSMutableAttributedString* attributedString = [self.mutableAttributedString mutableCopy]; if (self.autoDetectLinks) { [self _applyLinkStyleWithResults:self.detectedlinkLocations toAttributedString:attributedString]; } [self _applyLinkStyleWithResults:self.explicitLinkLocations toAttributedString:attributedString]; if (self.images.count > 0) { // Sort the label images in reverse order by index so that when we add them the string's indices // remain relatively accurate to the original string. This is necessary because we're inserting // spaces into the string. [self.images sortUsingComparator:^NSComparisonResult(NIAttributedLabelImage* obj1, NIAttributedLabelImage* obj2) { if (obj1.index < obj2.index) { return NSOrderedDescending; } else if (obj1.index > obj2.index) { return NSOrderedAscending; } else { return NSOrderedSame; } }]; for (NIAttributedLabelImage *labelImage in self.images) { CTRunDelegateCallbacks callbacks; memset(&callbacks, 0, sizeof(CTRunDelegateCallbacks)); callbacks.version = kCTRunDelegateVersion1; callbacks.getAscent = NIImageDelegateGetAscentCallback; callbacks.getDescent = NIImageDelegateGetDescentCallback; callbacks.getWidth = NIImageDelegateGetWidthCallback; NSUInteger index = labelImage.index; if (index >= attributedString.length) { index = attributedString.length - 1; } NSDictionary *attributes = [attributedString attributesAtIndex:index effectiveRange:NULL]; CTFontRef font = (__bridge CTFontRef)[attributes valueForKey:(__bridge id)kCTFontAttributeName]; if (font != NULL) { labelImage.fontAscent = CTFontGetAscent(font); labelImage.fontDescent = CTFontGetDescent(font); } CTRunDelegateRef delegate = CTRunDelegateCreate(&callbacks, (__bridge void *)labelImage); // Character to use as recommended by kCTRunDelegateAttributeName documentation. unichar objectReplacementChar = 0xFFFC; NSString *objectReplacementString = [NSString stringWithCharacters:&objectReplacementChar length:1]; NSMutableAttributedString* space = [[NSMutableAttributedString alloc] initWithString:objectReplacementString]; CFRange range = CFRangeMake(0, 1); CFMutableAttributedStringRef spaceString = (__bridge_retained CFMutableAttributedStringRef)space; CFAttributedStringSetAttribute(spaceString, range, kCTRunDelegateAttributeName, delegate); // Explicitly set the writing direction of this string to LTR, because in 'drawImages' we draw // for LTR by drawing at offset to offset + width vs to offset - width as you would for RTL. CFAttributedStringSetAttribute(spaceString, range, kCTWritingDirectionAttributeName, (__bridge CFArrayRef)@[@(kCTWritingDirectionLeftToRight)]); CFRelease(delegate); CFRelease(spaceString); [attributedString insertAttributedString:space atIndex:labelImage.index]; } } if (self.isHighlighted) { [attributedString setTextColor:self.highlightedTextColor]; } return attributedString; } - (NSInteger)numberOfDisplayedLines { CFArrayRef lines = CTFrameGetLines(self.textFrame); return self.numberOfLines > 0 ? MIN(self.numberOfLines, CFArrayGetCount(lines)) : CFArrayGetCount(lines); } - (void)drawImages { if (0 == self.images.count) { return; } CGContextRef ctx = UIGraphicsGetCurrentContext(); CFArrayRef lines = CTFrameGetLines(self.textFrame); CFIndex lineCount = CFArrayGetCount(lines); CGPoint lineOrigins[lineCount]; CTFrameGetLineOrigins(self.textFrame, CFRangeMake(0, 0), lineOrigins); NSInteger numberOfLines = [self numberOfDisplayedLines]; for (CFIndex i = 0; i < numberOfLines; i++) { CTLineRef line = CFArrayGetValueAtIndex(lines, i); CFArrayRef runs = CTLineGetGlyphRuns(line); CFIndex runCount = CFArrayGetCount(runs); CGPoint lineOrigin = lineOrigins[i]; CGFloat lineAscent; CGFloat lineDescent; CTLineGetTypographicBounds(line, &lineAscent, &lineDescent, NULL); CGFloat lineHeight = lineAscent + lineDescent; CGFloat lineBottomY = lineOrigin.y - lineDescent; // Iterate through each of the "runs" (i.e. a chunk of text) and find the runs that // intersect with the range. for (CFIndex k = 0; k < runCount; k++) { CTRunRef run = CFArrayGetValueAtIndex(runs, k); NSDictionary *runAttributes = (__bridge NSDictionary *)CTRunGetAttributes(run); CTRunDelegateRef delegate = (__bridge CTRunDelegateRef)[runAttributes valueForKey:(__bridge id)kCTRunDelegateAttributeName]; if (nil == delegate) { continue; } NIAttributedLabelImage* labelImage = (__bridge NIAttributedLabelImage *)CTRunDelegateGetRefCon(delegate); CGFloat ascent = 0.0f; CGFloat descent = 0.0f; CGFloat width = (CGFloat)CTRunGetTypographicBounds(run, CFRangeMake(0, 0), &ascent, &descent, NULL); CGFloat imageBoxHeight = labelImage.boxSize.height; CGFloat xOffset = CTLineGetOffsetForStringIndex(line, CTRunGetStringRange(run).location, nil); CGFloat imageBoxOriginY = 0.0f; switch (labelImage.verticalTextAlignment) { case NIVerticalTextAlignmentTop: imageBoxOriginY = lineBottomY + (lineHeight - imageBoxHeight); break; case NIVerticalTextAlignmentMiddle: imageBoxOriginY = lineBottomY + (lineHeight - imageBoxHeight) / 2.f; break; case NIVerticalTextAlignmentBottom: imageBoxOriginY = lineBottomY; break; } CGRect rect = CGRectMake(lineOrigin.x + xOffset, imageBoxOriginY, width, imageBoxHeight); UIEdgeInsets flippedMargins = labelImage.margins; CGFloat top = flippedMargins.top; flippedMargins.top = flippedMargins.bottom; flippedMargins.bottom = top; CGRect imageRect = UIEdgeInsetsInsetRect(rect, flippedMargins); imageRect = CGRectOffset(imageRect, 0, -[self _verticalOffsetForBounds:self.bounds]); CGContextDrawImage(ctx, imageRect, labelImage.image.CGImage); } } } - (void)drawHighlightWithRect:(CGRect)rect { if ((nil == self.touchedLink && nil == self.actionSheetLink) || nil == self.highlightedLinkBackgroundColor) { return; } [self.highlightedLinkBackgroundColor setFill]; NSRange linkRange = nil != self.touchedLink ? self.touchedLink.range : self.actionSheetLink.range; CFArrayRef lines = CTFrameGetLines(self.textFrame); CFIndex count = CFArrayGetCount(lines); CGPoint lineOrigins[count]; CTFrameGetLineOrigins(self.textFrame, CFRangeMake(0, 0), lineOrigins); NSInteger numberOfLines = [self numberOfDisplayedLines]; CGContextRef ctx = UIGraphicsGetCurrentContext(); for (CFIndex i = 0; i < numberOfLines; i++) { CTLineRef line = CFArrayGetValueAtIndex(lines, i); CFRange stringRange = CTLineGetStringRange(line); NSRange lineRange = NSMakeRange(stringRange.location, stringRange.length); NSRange intersectedRange = NSIntersectionRange(lineRange, linkRange); if (intersectedRange.length == 0) { continue; } CGRect highlightRect = [self _rectForRange:linkRange inLine:line lineOrigin:lineOrigins[i]]; highlightRect = CGRectOffset(highlightRect, 0, -rect.origin.y); if (!CGRectIsEmpty(highlightRect)) { CGFloat pi = (CGFloat)M_PI; CGFloat radius = 1.0f; CGContextMoveToPoint(ctx, highlightRect.origin.x, highlightRect.origin.y + radius); CGContextAddLineToPoint(ctx, highlightRect.origin.x, highlightRect.origin.y + highlightRect.size.height - radius); CGContextAddArc(ctx, highlightRect.origin.x + radius, highlightRect.origin.y + highlightRect.size.height - radius, radius, pi, pi / 2.0f, 1.0f); CGContextAddLineToPoint(ctx, highlightRect.origin.x + highlightRect.size.width - radius, highlightRect.origin.y + highlightRect.size.height); CGContextAddArc(ctx, highlightRect.origin.x + highlightRect.size.width - radius, highlightRect.origin.y + highlightRect.size.height - radius, radius, pi / 2, 0.0f, 1.0f); CGContextAddLineToPoint(ctx, highlightRect.origin.x + highlightRect.size.width, highlightRect.origin.y + radius); CGContextAddArc(ctx, highlightRect.origin.x + highlightRect.size.width - radius, highlightRect.origin.y + radius, radius, 0.0f, -pi / 2.0f, 1.0f); CGContextAddLineToPoint(ctx, highlightRect.origin.x + radius, highlightRect.origin.y); CGContextAddArc(ctx, highlightRect.origin.x + radius, highlightRect.origin.y + radius, radius, -pi / 2, pi, 1); CGContextFillPath(ctx); } } } - (void)drawAttributedString:(NSAttributedString *)attributedString rect:(CGRect)rect { CGContextRef ctx = UIGraphicsGetCurrentContext(); // This logic adapted from @mattt's TTTAttributedLabel // https://github.com/mattt/TTTAttributedLabel CFArrayRef lines = CTFrameGetLines(self.textFrame); NSInteger numberOfLines = [self numberOfDisplayedLines]; BOOL truncatesLastLine = (self.lineBreakMode == NSLineBreakByTruncatingTail); CGPoint lineOrigins[numberOfLines]; CTFrameGetLineOrigins(self.textFrame, CFRangeMake(0, numberOfLines), lineOrigins); for (CFIndex lineIndex = 0; lineIndex < numberOfLines; lineIndex++) { CGPoint lineOrigin = lineOrigins[lineIndex]; lineOrigin.y -= rect.origin.y; // adjust for verticalTextAlignment CGContextSetTextPosition(ctx, lineOrigin.x, lineOrigin.y); CTLineRef line = CFArrayGetValueAtIndex(lines, lineIndex); BOOL shouldDrawLine = YES; if (truncatesLastLine && lineIndex == numberOfLines - 1) { // Does the last line need truncation? CFRange lastLineRange = CTLineGetStringRange(line); if (lastLineRange.location + lastLineRange.length < (CFIndex)attributedString.length) { CTLineTruncationType truncationType = kCTLineTruncationEnd; NSUInteger truncationAttributePosition = lastLineRange.location + lastLineRange.length - 1; NSAttributedString* tokenAttributedString; { NSDictionary *tokenAttributes = [attributedString attributesAtIndex:truncationAttributePosition effectiveRange:NULL]; NSString* tokenString = ((nil == self.tailTruncationString) ? kEllipsesCharacter : self.tailTruncationString); tokenAttributedString = [[NSAttributedString alloc] initWithString:tokenString attributes:tokenAttributes]; } CTLineRef truncationToken = CTLineCreateWithAttributedString((__bridge CFAttributedStringRef)tokenAttributedString); NSMutableAttributedString *truncationString = [[attributedString attributedSubstringFromRange:NSMakeRange(lastLineRange.location, lastLineRange.length)] mutableCopy]; if (lastLineRange.length > 0) { // Remove any whitespace at the end of the line. unichar lastCharacter = [[truncationString string] characterAtIndex:lastLineRange.length - 1]; if ([[NSCharacterSet whitespaceAndNewlineCharacterSet] characterIsMember:lastCharacter]) { [truncationString deleteCharactersInRange:NSMakeRange(lastLineRange.length - 1, 1)]; } } [truncationString appendAttributedString:tokenAttributedString]; CTLineRef truncationLine = CTLineCreateWithAttributedString((__bridge CFAttributedStringRef)truncationString); CTLineRef truncatedLine = CTLineCreateTruncatedLine(truncationLine, rect.size.width, truncationType, truncationToken); if (!truncatedLine) { // If the line is not as wide as the truncationToken, truncatedLine is NULL truncatedLine = CFRetain(truncationToken); } CFRelease(truncationLine); CFRelease(truncationToken); CTLineDraw(truncatedLine, ctx); CFRelease(truncatedLine); shouldDrawLine = NO; } } if (shouldDrawLine) { CTLineDraw(line, ctx); } } } - (void)drawTextInRect:(CGRect)rect { if (NIVerticalTextAlignmentTop != self.verticalTextAlignment) { rect.origin.y = [self _verticalOffsetForBounds:rect]; } if (self.autoDetectLinks) { [self detectLinks]; } NSMutableAttributedString* attributedStringWithLinks = [self mutableAttributedStringWithAdditions]; if (self.detectedlinkLocations.count > 0 || self.explicitLinkLocations.count > 0) { self.userInteractionEnabled = YES; } if (nil != attributedStringWithLinks) { CGContextRef ctx = UIGraphicsGetCurrentContext(); CGContextSaveGState(ctx); CGAffineTransform transform = [self _transformForCoreText]; CGContextConcatCTM(ctx, transform); [self drawImages]; [self drawHighlightWithRect:rect]; if (nil != self.shadowColor) { CGContextSetShadowWithColor(ctx, self.shadowOffset, self.shadowBlur, self.shadowColor.CGColor); } [self drawAttributedString:attributedStringWithLinks rect:rect]; CGContextRestoreGState(ctx); } else { [super drawTextInRect:rect]; } } #pragma mark - Accessibility - (void)invalidateAccessibleElements { self.accessibleElements = nil; } - (NSArray *)accessibleElements { if (nil != _accessibleElements) { return _accessibleElements; } NSMutableArray* accessibleElements = [NSMutableArray array]; // NSArray arrayWithArray:self.detectedlinkLocations ensures that we're not working with a nil // array. NSArray* allLinks = [[NSArray arrayWithArray:self.detectedlinkLocations] arrayByAddingObjectsFromArray:self.explicitLinkLocations]; for (NSTextCheckingResult* result in allLinks) { NSArray* rectsForLink = [self _rectsForLink:result]; if (!NIIsArrayWithObjects(rectsForLink)) { continue; } NSString* label = [self.mutableAttributedString.string substringWithRange:result.range]; for (NSValue* rectValue in rectsForLink) { UIAccessibilityElement* element = [[UIAccessibilityElement alloc] initWithAccessibilityContainer:self]; element.accessibilityLabel = label; element.accessibilityFrame = [self convertRect:rectValue.CGRectValue toView:self.window]; element.accessibilityTraits = UIAccessibilityTraitLink; [accessibleElements addObject:element]; } } // Add this label's text as the "bottom-most" accessibility element, i.e. the last element in the // array. This gives link priorities. UIAccessibilityElement* element = [[UIAccessibilityElement alloc] initWithAccessibilityContainer:self]; element.accessibilityLabel = self.attributedText.string; element.accessibilityFrame = [self convertRect:self.bounds toView:self.window]; element.accessibilityTraits = UIAccessibilityTraitNone; [accessibleElements addObject:element]; _accessibleElements = [accessibleElements copy]; return _accessibleElements; } - (BOOL)isAccessibilityElement { return NO; // We handle accessibility for this element in -accessibleElements. } - (NSInteger)accessibilityElementCount { return self.accessibleElements.count; } - (id)accessibilityElementAtIndex:(NSInteger)index { return [self.accessibleElements objectAtIndex:index]; } - (NSInteger)indexOfAccessibilityElement:(id)element { return [self.accessibleElements indexOfObject:element]; } #pragma mark - UIActionSheetDelegate - (void)actionSheet:(UIActionSheet*)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex { if (NSTextCheckingTypeLink == self.actionSheetLink.resultType) { if (buttonIndex == 0) { [[UIApplication sharedApplication] openURL:self.actionSheetLink.URL]; } else if (buttonIndex == 1) { if ([self.actionSheetLink.URL.scheme isEqualToString:@"mailto"]) { [[UIPasteboard generalPasteboard] setString:self.actionSheetLink.URL.resourceSpecifier]; } else { [[UIPasteboard generalPasteboard] setURL:self.actionSheetLink.URL]; } } } else if (NSTextCheckingTypePhoneNumber == self.actionSheetLink.resultType) { if (buttonIndex == 0) { [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[@"tel:" stringByAppendingString:self.actionSheetLink.phoneNumber]]]; } else if (buttonIndex == 1) { [[UIPasteboard generalPasteboard] setString:self.actionSheetLink.phoneNumber]; } } else if (NSTextCheckingTypeAddress == self.actionSheetLink.resultType) { NSString* address = [self.mutableAttributedString.string substringWithRange:self.actionSheetLink.range]; if (buttonIndex == 0) { [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[[@"http://maps.google.com/maps?q=" stringByAppendingString:address] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]; } else if (buttonIndex == 1) { [[UIPasteboard generalPasteboard] setString:address]; } } else { // Unsupported data type only allows the user to copy. if (buttonIndex == 0) { NSString* text = [self.mutableAttributedString.string substringWithRange:self.actionSheetLink.range]; [[UIPasteboard generalPasteboard] setString:text]; } } self.actionSheetLink = nil; [self setNeedsDisplay]; } - (void)actionSheetCancel:(UIActionSheet *)actionSheet { self.actionSheetLink = nil; [self setNeedsDisplay]; } #pragma mark - Inline Image Support CGFloat NIImageDelegateGetAscentCallback(void* refCon) { NIAttributedLabelImage *labelImage = (__bridge NIAttributedLabelImage *)refCon; switch (labelImage.verticalTextAlignment) { case NIVerticalTextAlignmentMiddle: { CGFloat ascent = labelImage.fontAscent; CGFloat descent = labelImage.fontDescent; CGFloat baselineFromMid = (ascent + descent) / 2 - descent; return labelImage.boxSize.height / 2 + baselineFromMid; } case NIVerticalTextAlignmentTop: return labelImage.fontAscent; case NIVerticalTextAlignmentBottom: default: return labelImage.boxSize.height - labelImage.fontDescent; } } CGFloat NIImageDelegateGetDescentCallback(void* refCon) { NIAttributedLabelImage *labelImage = (__bridge NIAttributedLabelImage *)refCon; switch (labelImage.verticalTextAlignment) { case NIVerticalTextAlignmentMiddle: { CGFloat ascent = labelImage.fontAscent; CGFloat descent = labelImage.fontDescent; CGFloat baselineFromMid = (ascent + descent) / 2 - descent; return labelImage.boxSize.height / 2 - baselineFromMid; } case NIVerticalTextAlignmentTop: return labelImage.boxSize.height - labelImage.fontAscent; case NIVerticalTextAlignmentBottom: default: return labelImage.fontDescent; } } CGFloat NIImageDelegateGetWidthCallback(void* refCon) { NIAttributedLabelImage *labelImage = (__bridge NIAttributedLabelImage *)refCon; return labelImage.image.size.width + labelImage.margins.left + labelImage.margins.right; } - (void)insertImage:(UIImage *)image atIndex:(NSInteger)index { [self insertImage:image atIndex:index margins:UIEdgeInsetsZero verticalTextAlignment:NIVerticalTextAlignmentBottom]; } - (void)insertImage:(UIImage *)image atIndex:(NSInteger)index margins:(UIEdgeInsets)margins { [self insertImage:image atIndex:index margins:margins verticalTextAlignment:NIVerticalTextAlignmentBottom]; } - (void)insertImage:(UIImage *)image atIndex:(NSInteger)index margins:(UIEdgeInsets)margins verticalTextAlignment:(NIVerticalTextAlignment)verticalTextAlignment { NIAttributedLabelImage* labelImage = [[NIAttributedLabelImage alloc] init]; labelImage.index = index; labelImage.image = image; labelImage.margins = margins; labelImage.verticalTextAlignment = verticalTextAlignment; if (nil == self.images) { self.images = [NSMutableArray array]; } [self.images addObject:labelImage]; } @end @implementation NIAttributedLabel (ConversionUtilities) + (CTTextAlignment)alignmentFromUITextAlignment:(NSTextAlignment)alignment { switch (alignment) { case NSTextAlignmentLeft: return kCTLeftTextAlignment; case NSTextAlignmentCenter: return kCTCenterTextAlignment; case NSTextAlignmentRight: return kCTRightTextAlignment; case NSTextAlignmentJustified: return kCTJustifiedTextAlignment; default: return kCTNaturalTextAlignment; } } + (CTLineBreakMode)lineBreakModeFromUILineBreakMode:(NSLineBreakMode)lineBreakMode { switch (lineBreakMode) { case NSLineBreakByWordWrapping: return kCTLineBreakByWordWrapping; case NSLineBreakByCharWrapping: return kCTLineBreakByCharWrapping; case NSLineBreakByClipping: return kCTLineBreakByClipping; case NSLineBreakByTruncatingHead: return kCTLineBreakByTruncatingHead; case NSLineBreakByTruncatingTail: return kCTLineBreakByWordWrapping; // We handle truncation ourself. case NSLineBreakByTruncatingMiddle: return kCTLineBreakByTruncatingMiddle; default: return 0; } } + (NSMutableAttributedString *)mutableAttributedStringFromLabel:(UILabel *)label { NSMutableAttributedString* attributedString = nil; if (label.text.length > 0) { attributedString = [[NSMutableAttributedString alloc] initWithString:label.text]; [attributedString setFont:label.font]; [attributedString setTextColor:label.textColor]; CTTextAlignment textAlignment = [self alignmentFromUITextAlignment:label.textAlignment]; CTLineBreakMode lineBreak = [self.class lineBreakModeFromUILineBreakMode:label.lineBreakMode]; CGFloat lineHeight = 0; if ([label isKindOfClass:[NIAttributedLabel class]]) { lineHeight = [(NIAttributedLabel *)label lineHeight]; } [attributedString setTextAlignment:textAlignment lineBreakMode:lineBreak lineHeight:lineHeight]; } return attributedString; } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/attributedlabel/src/NSMutableAttributedString+NimbusAttributedLabel.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // Originally created by Roger Chapman // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import <CoreText/CoreText.h> /** * For easier formatting of NSAttributedString. * * Most of these methods are called directly from NIAttributedLabel. Normally you should * not have to call these methods directly. Have a look at NIAttributedLabel first, it's most * likely what you're after. */ @interface NSMutableAttributedString (NimbusAttributedLabel) /** * Sets the text alignment and line break mode for a given range. */ - (void)setTextAlignment:(CTTextAlignment)textAlignment lineBreakMode:(CTLineBreakMode)lineBreakMode lineHeight:(CGFloat)lineHeight range:(NSRange)range; /** * Sets the text alignment and the line break mode for the entire string. */ - (void)setTextAlignment:(CTTextAlignment)textAlignment lineBreakMode:(CTLineBreakMode)lineBreakMode lineHeight:(CGFloat)lineHeight; /** * Sets the text color for a given range. */ - (void)setTextColor:(UIColor *)color range:(NSRange)range; /** * Sets the text color for the entire string. */ - (void)setTextColor:(UIColor *)color; /** * Sets the font for a given range. */ - (void)setFont:(UIFont *)font range:(NSRange)range; /** * Sets the font for the entire string. */ - (void)setFont:(UIFont *)font; /** * Sets the underline style and modifier for a given range. */ - (void)setUnderlineStyle:(CTUnderlineStyle)style modifier:(CTUnderlineStyleModifiers)modifier range:(NSRange)range; /** * Sets the underline style and modifier for the entire string. */ - (void)setUnderlineStyle:(CTUnderlineStyle)style modifier:(CTUnderlineStyleModifiers)modifier; /** * Sets the stroke width for a given range. */ - (void)setStrokeWidth:(CGFloat)width range:(NSRange)range; /** * Sets the stroke width for the entire string. */ - (void)setStrokeWidth:(CGFloat)width; /** * Sets the stroke color for a given range. */ - (void)setStrokeColor:(UIColor *)color range:(NSRange)range; /** * Sets the stroke color for the entire string. */ - (void)setStrokeColor:(UIColor *)color; /** * Sets the text kern for a given range. */ - (void)setKern:(CGFloat)kern range:(NSRange)range; /** * Sets the text kern for the entire string. */ - (void)setKern:(CGFloat)kern; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/attributedlabel/src/NSMutableAttributedString+NimbusAttributedLabel.m
Objective-C
// // Copyright 2011-2014 NimbusKit // Originally created by Roger Chapman // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NSMutableAttributedString+NimbusAttributedLabel.h" #import "NimbusCore.h" // For NI_FIX_CATEGORY_BUG #if !defined(__has_feature) || !__has_feature(objc_arc) #error "Nimbus requires ARC support." #endif #if __IPHONE_OS_VERSION_MIN_REQUIRED < NIIOS_6_0 #error "NIAttributedLabel requires iOS 6 or higher." #endif NI_FIX_CATEGORY_BUG(NSMutableAttributedStringNimbusAttributedLabel) @implementation NSMutableAttributedString (NimbusAttributedLabel) + (NSTextAlignment)alignmentFromCTTextAlignment:(CTTextAlignment)alignment { switch (alignment) { case kCTLeftTextAlignment: return NSTextAlignmentLeft; case kCTCenterTextAlignment: return NSTextAlignmentCenter; case kCTRightTextAlignment: return NSTextAlignmentRight; case kCTJustifiedTextAlignment: return NSTextAlignmentJustified; default: return NSTextAlignmentNatural; } } - (void)setTextAlignment:(CTTextAlignment)textAlignment lineBreakMode:(CTLineBreakMode)lineBreakMode lineHeight:(CGFloat)lineHeight range:(NSRange)range { NSMutableParagraphStyle* paragraphStyle = [[NSMutableParagraphStyle alloc] init]; paragraphStyle.alignment = [[self class] alignmentFromCTTextAlignment:textAlignment]; paragraphStyle.lineBreakMode = lineBreakMode; paragraphStyle.minimumLineHeight = lineHeight; paragraphStyle.maximumLineHeight = lineHeight; [self addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:range]; } - (void)setTextAlignment:(CTTextAlignment)textAlignment lineBreakMode:(CTLineBreakMode)lineBreakMode lineHeight:(CGFloat)lineHeight { [self setTextAlignment:textAlignment lineBreakMode:lineBreakMode lineHeight:lineHeight range:NSMakeRange(0, self.length)]; } - (void)setTextColor:(UIColor *)color range:(NSRange)range { [self removeAttribute:NSForegroundColorAttributeName range:range]; if (nil != color) { [self addAttribute:NSForegroundColorAttributeName value:color range:range]; } } - (void)setTextColor:(UIColor *)color { [self setTextColor:color range:NSMakeRange(0, self.length)]; } - (void)setFont:(UIFont *)font range:(NSRange)range { [self removeAttribute:NSFontAttributeName range:range]; if (nil != font) { [self addAttribute:NSFontAttributeName value:font range:range]; } } - (void)setFont:(UIFont*)font { [self setFont:font range:NSMakeRange(0, self.length)]; } - (void)setUnderlineStyle:(CTUnderlineStyle)style modifier:(CTUnderlineStyleModifiers)modifier range:(NSRange)range { [self removeAttribute:NSUnderlineStyleAttributeName range:range]; [self addAttribute:NSUnderlineStyleAttributeName value:@(style|modifier) range:range]; } - (void)setUnderlineStyle:(CTUnderlineStyle)style modifier:(CTUnderlineStyleModifiers)modifier { [self setUnderlineStyle:style modifier:modifier range:NSMakeRange(0, self.length)]; } - (void)setStrokeWidth:(CGFloat)width range:(NSRange)range { [self removeAttribute:NSStrokeWidthAttributeName range:range]; [self addAttribute:NSStrokeWidthAttributeName value:@(width) range:range]; } - (void)setStrokeWidth:(CGFloat)width { [self setStrokeWidth:width range:NSMakeRange(0, self.length)]; } - (void)setStrokeColor:(UIColor *)color range:(NSRange)range { [self removeAttribute:NSStrokeColorAttributeName range:range]; if (nil != color.CGColor) { [self addAttribute:NSStrokeColorAttributeName value:color range:range]; } } - (void)setStrokeColor:(UIColor *)color { [self setStrokeColor:color range:NSMakeRange(0, self.length)]; } - (void)setKern:(CGFloat)kern range:(NSRange)range { [self removeAttribute:NSKernAttributeName range:range]; [self addAttribute:NSKernAttributeName value:@(kern) range:range]; } - (void)setKern:(CGFloat)kern { [self setKern:kern range:NSMakeRange(0, self.length)]; } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/attributedlabel/src/NimbusAttributedLabel.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // Originally created by Roger Chapman // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /** * @defgroup NimbusAttributedLabel Nimbus Attributed Label * @{ * * <div id="github" feature="attributedlabel"></div> * * The Nimbus Attributed Label is a UILabel that uses NSAttributedString to render rich text labels * with links using CoreText. * * @image html NIAttributedLabelExample1.png "A mashup of possible label styles" * * <h2>Minimum Requirements</h2> * * Required frameworks: * * - Foundation.framework * - UIKit.framework * - CoreText.framework * - QuartzCore.framework * * Minimum Operating System: <b>iOS 6.0</b> * * Source located in <code>src/attributedlabel/src</code> * @code #import "NimbusAttributedLabel.h" @endcode * * <h2>Basic Use</h2> * * NIAttributedLabel is a subclass of UILabel. The attributed label maintains an <a href="http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSAttributedString_Class/Reference/Reference.html">NSAttributedString</a> * object internally which is used in conjunction with CoreText to draw rich-text labels. A number * of helper methods for modifying the text style are provided. If you need to directly modify the * internal NSAttributedString you may do so by accessing the @c attributedText property. * @code NIAttributedLabel* label = [[NIAttributedLabel alloc] initWithFrame:CGRectZero]; // The internal NSAttributedString will inherit all of UILabel's text attributes when we assign // text. label.text = @"Nimbus"; @endcode * * * <h2>Interface Builder</h2> * * You can use an attributed label within Interface Builder by creating a UILabel and changing its * class to NIAttributedLabel. This will allow you to set styles that apply to * the entire string. If you want to style specific parts of the string then you will * need to do this in code. * * @image html NIAttributedLabelIB.png "Configuring an attributed label in Interface Builder" * * * <h2>Feature Overview</h2> * * - Automatic link detection using data detectors * - Link attributes * - Explicit links * - Underlining * - Justifying paragraphs * - Stroking * - Kerning * - Setting rich text styles at specific ranges * * * <h3>Automatic Link Detection</h3> * * Automatic link detection is provided using <a href="https://developer.apple.com/library/mac/#documentation/Foundation/Reference/NSDataDetector_Class/Reference/Reference.html">NSDataDetector</a>. * Link detection is off by default and can be enabled by setting * @link NIAttributedLabel::autoDetectLinks autoDetectLinks@endlink to YES. You may configure * the types of data that are detected by modifying the * @link NIAttributedLabel::dataDetectorTypes dataDetectorTypes@endlink property. By default only * urls will be detected. * * @attention NIAttributedLabel is not designed to detect html anchor tags (i.e. &lt;a>). If * you want to attach a URL to a given range of text you must use * @link NIAttributedLabel::addLink:range: addLink:range:@endlink. * You can add links to the attributed string using the attribute * NIAttributedLabelLinkAttributeName. The NIAttributedLabelLinkAttributeName value * must be a NSTextCheckingResult. * * @image html NIAttributedLabel_autoDetectLinksOff.png "Before enabling autoDetectLinks" * @code // Enable link detection on the label. myLabel.autoDetectLinks = YES; @endcode * * @image html NIAttributedLabel_autoDetectLinksOn.png "After enabling autoDetectLinks" * * Enabling automatic link detection will automatically enable user interation with the label view * so that the user can tap the detected links. * * <h3>Link Attributes</h3> * * Detected links will use @link NIAttributedLabel::linkColor linkColor@endlink and * @link NIAttributedLabel::highlightedLinkColor highlightedLinkColor@endlink to differentiate * themselves from standard text. highlightedLinkColor is the color of the highlighting frame * around the text. You can easily add underlines to links by enabling * @link NIAttributedLabel::linksHaveUnderlines linksHaveUnderlines@endlink. You can customize link * attributes in more detail by directly modifying the * @link NIAttributedLabel::attributesForLinks attributesForLinks@endlink property. * * @image html NIAttributedLabelLinkAttributes.png "Link attributes" * * <h4>A note on performance</h4> * * Automatic link detection is expensive. You can choose to defer automatic link detection by * enabling @link NIAttributedLabel::deferLinkDetection deferLinkDetection@endlink. This will move * the link detection to a separate background thread. Once the links have been detected the label * will be redrawn. * * * <h3>Handling Taps on Links</h3> * * The NIAttributedLabelDelegate protocol allows you to handle when the user taps on a given link. * The protocol methods provide the tap point as well as the data pertaining to the tapped link. * @code - (void)attributedLabel:(NIAttributedLabel *)attributedLabel didSelectTextCheckingResult:(NSTextCheckingResult *)result atPoint:(CGPoint)point { [[UIApplication sharedApplication] openURL:result.URL]; } @endcode * * <h3>Explicit Links</h3> * * Links can be added explicitly using * @link NIAttributedLabel::addLink:range: addLink:range:@endlink. * @code // Add a link to the string 'nimbus' in myLabel. [myLabel addLink:[NSURL URLWithString:@"nimbus://custom/url"] range:[myLabel.text rangeOfString:@"nimbus"]]; @endcode * * * <h3>Underlining Text</h3> * * To underline an entire label: * @code // Underline the whole label with a single line. myLabel.underlineStyle = kCTUnderlineStyleSingle; @endcode * * Underline modifiers can also be added: * @code // Underline the whole label with a dash dot single line. myLabel.underlineStyle = kCTUnderlineStyleSingle; myLabel.underlineStyleModifier = kCTUnderlinePatternDashDot; @endcode * * Underline styles and modifiers can be mixed to create the desired effect, which is shown in * the following screenshot: * * @image html NIAttributedLabelExample2.png "Underline styles" * * @remarks Underline style kCTUnderlineStyleThick only over renders a single line. * * * <h3>Justifying Paragraphs</h3> * * NIAttributedLabel supports justified text using UITextAlignmentJustify. * @code myLabel.textAlignment = UITextAlignmentJustify; @endcode * * * <h3>Stroking Text</h3> * @code myLabel.strokeWidth = 3.0; myLabel.strokeColor = [UIColor blackColor]; @endcode * * A positive stroke width will render only the stroke. * * @image html NIAttributedLabelExample3.png "Black stroke of 3.0" * * A negative number will fill the stroke with textColor: * @code myLabel.strokeWidth = -3.0; myLabel.strokeColor = [UIColor blackColor]; @endcode * * @image html NIAttributedLabelExample4.png "Black stroke of -3.0" * * * <h3>Kerning Text</h3> * * Kerning is the space between characters in points. A positive kern will increase the space * between letters. Correspondingly a negative number will decrease the space. * @code myLabel.textKern = -6.0; @endcode * * @image html NIAttributedLabelExample5.png "Text kern of -6.0" * * * <h3>Setting Rich Text styles at specific ranges</h3> * * All styles that can be added to the whole label (as well as default UILabel styles like font and * text color) can be added to just a range of text. * @code [myLabel setTextColor:[UIColor orangeColor] range:[myLabel.text rangeOfString:@"Nimbus"]]; [myLabel setFont:[UIFont boldSystemFontOfSize:22] range:[myLabel.text rangeOfString:@"iOS"]]; @endcode * @} */ #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import <CoreText/CoreText.h> #import "NimbusCore.h" #import "NIAttributedLabel.h"
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/badge/src/NIBadgeView.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // Originally created by Roger Chapman // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <UIKit/UIKit.h> /** * A view that mimics the iOS notification badge style. * * Any NSString can be displayed in this view, though in practice you should only show numbers * ranging from 1...99 or the string @"99+". Apple is quite consistent about using the red badge * views to represent notification badges, so you should do your best not to attach additional * meaning to the red badge. * * On devices running operating systems that support the tintColor property on UIViews, these * badges will use the tintColor by default. This behavior may be overwritten by assigning a tint * color explicitly. * * @image html badge.png "A default NIBadgeView" * @image html badgetinted.png "A NIBadgeView on tintColor-supporting devices" * * @ingroup NimbusBadge */ @interface NIBadgeView : UIView // Text attributes @property (nonatomic, copy) NSString* text; @property (nonatomic, strong) UIFont* font; @property (nonatomic, strong) UIColor* textColor; // Badge attributes @property (nonatomic, strong) UIColor* tintColor; @property (nonatomic, strong) UIColor* shadowColor; @property (nonatomic, assign) CGSize shadowOffset; @property (nonatomic, assign) CGFloat shadowBlur; @end /** @name Accessing the Text Attributes */ /** * The text displayed within the badge. * * As with a UILabel you should call sizeToFit after setting the badgeView properties so that it * will update its frame to fit the contents. * * @fn NIBadgeView::text */ /** * The font of the text within the badge. * * The default font is: * * iOS 6: [UIFont boldSystemFontOfSize:17] * iOS 7: [UIFont systemFontOfSize:16] * * @sa text * @fn NIBadgeView::font */ /** * The color of the text in the badge. * * The default color is [UIColor whiteColor]. * * @fn NIBadgeView::textColor */ /** @name Accessing the Badge Attributes */ /** * The tint color of the badge. * * This is the color drawn within the badge's borders. * * The default color is * * iOS 6: [UIColor redColor]. * iOS 7: self.tintColor * * On devices that support global tintColor (iOS 7) the global tint color is used unless a tint * color has been explicitly assigned to this badge view, in which case the assigned tint color will be used. * * @fn NIBadgeView::tintColor */ /** * The shadow color of the badge. * * This is the shadow drawn beneath the badge's outline. * * The default color is * * iOS 6: [UIColor colorWithWhite:0 alpha:0.5]. * iOS 7: nil * * On devices that support global tintColor (iOS 7) it is possible, though not encouraged, to use * a shadow on badges. * * @sa shadowOffset * @sa shadowBlur * @fn NIBadgeView::shadowColor */ /** * The shadow offset (measured in points) for the badge. * * This is the offset of the shadow drawn beneath the badge's outline. * * The default value is CGSizeMake(0, 3.f). * * @sa shadowColor * @sa shadowBlur * @fn NIBadgeView::shadowOffset */ /** * The shadow blur (measured in points) for the badge. * * This is the blur of the shadow drawn beneath the badge's outline. * * The default value is 3. * * @sa shadowOffset * @sa shadowColor * @fn NIBadgeView::shadowBlur */
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/badge/src/NIBadgeView.m
Objective-C
// // Copyright 2011-2014 NimbusKit // Originally created by Roger Chapman // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NIBadgeView.h" #import "NimbusCore.h" // For NIScreenScale #if !defined(__has_feature) || !__has_feature(objc_arc) #error "Nimbus requires ARC support." #endif #if __IPHONE_OS_VERSION_MIN_REQUIRED < NIIOS_6_0 #error "NIBadgeView requires iOS 6 or higher." #endif static BOOL sUsesSolidTint = NO; static const CGFloat kMinimumWidth = 30.f; static const CGFloat kHorizontalMargins = 20.f; static const CGFloat kVerticalMargins = 10.f; static const CGFloat kBadgeLineSize = 2.0f; @implementation NIBadgeView @synthesize tintColor = _tintColor; + (void)initialize { sUsesSolidTint = NIIsTintColorGloballySupported(); } - (void)_configureDefaults { self.contentScaleFactor = NIScreenScale(); // We check for nil values so that defaults can be set in IB. if (nil == self.tintColor) { if (!sUsesSolidTint) { self.tintColor = [UIColor redColor]; } } if (nil == self.font) { self.font = sUsesSolidTint ? [UIFont systemFontOfSize:16] : [UIFont boldSystemFontOfSize:17]; } if (nil == self.textColor) { self.textColor = [UIColor whiteColor]; } if (nil == self.shadowColor) { if (!sUsesSolidTint) { self.shadowColor = [UIColor colorWithWhite:0 alpha:0.5]; } } if (CGSizeEqualToSize(self.shadowOffset, CGSizeZero)) { self.shadowOffset = CGSizeMake(0, 3); } if (0 == self.shadowBlur) { self.shadowBlur = 3; } } - (id)initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])) { [self _configureDefaults]; } return self; } - (void)awakeFromNib { [super awakeFromNib]; [self _configureDefaults]; } - (CGSize)sizeThatFits:(CGSize)size { CGSize stringSize = [self.text sizeWithFont:self.font]; CGSize zeroSize = [@"0" sizeWithFont:self.font]; CGFloat padding = 0; if (sUsesSolidTint) { padding = 2; } return CGSizeMake(MAX(zeroSize.width + kHorizontalMargins + padding, stringSize.width + kHorizontalMargins), stringSize.height + kVerticalMargins); } - (CGSize)intrinsicContentSize { return [self sizeThatFits:self.bounds.size]; } - (void)setText:(NSString *)text { _text = text; [self setNeedsDisplay]; if ([self respondsToSelector:@selector(invalidateIntrinsicContentSize)]) { [self invalidateIntrinsicContentSize]; } } - (void)setFont:(UIFont *)font { _font = font; [self setNeedsDisplay]; if ([self respondsToSelector:@selector(invalidateIntrinsicContentSize)]) { [self invalidateIntrinsicContentSize]; } } - (void)setTintColor:(UIColor *)tintColor { _tintColor = tintColor; [self setNeedsDisplay]; } - (UIColor *)tintColor { if (sUsesSolidTint) { return (nil != _tintColor) ? _tintColor : [super tintColor]; } else { return _tintColor; } } - (void)tintColorDidChange { [self setNeedsDisplay]; } - (void)setTextColor:(UIColor *)textColor { _textColor = textColor; [self setNeedsDisplay]; } - (void)drawRect:(CGRect)rect { CGContextRef context = UIGraphicsGetCurrentContext(); CGSize textSize = [self.text sizeWithFont:self.font]; // Used to suppress warning: Implicit conversion shortens 64-bit value into 32-bit value const CGFloat pi = (CGFloat)M_PI; const CGFloat kRadius = textSize.height / 2.f + (sUsesSolidTint ? 0.5f : 0); // The following constant offsets are chosen to make the badge match the system badge dimensions // pixel-for-pixel for the default font size. Any other font size is undefined as far as a // standard, so we just use these constants for everything.g CGFloat minX = CGRectGetMinX(rect) + (sUsesSolidTint ? 5.f : 4.f); CGFloat maxX = CGRectGetMaxX(rect) - (sUsesSolidTint ? 6.f : 5.f); CGFloat minY = CGRectGetMinY(rect) + (sUsesSolidTint ? 2.f : 3.5f); CGFloat maxY = CGRectGetMaxY(rect) - (sUsesSolidTint ? 6.f : 6.5f); if (sUsesSolidTint && self.text.length <= 1) { // For single digit badges we nudge the left edge slightly to match with the system badge // boundaries on iOS 7. minX--; } CGContextSaveGState(context); // Draw the main rounded rectangle CGContextBeginPath(context); CGContextSetFillColorWithColor(context, self.tintColor.CGColor); CGContextAddArc(context, maxX-kRadius, minY+kRadius, kRadius, pi+(pi/2), 0, 0); CGContextAddArc(context, maxX-kRadius, maxY-kRadius, kRadius, 0, pi/2, 0); CGContextAddArc(context, minX+kRadius, maxY-kRadius, kRadius, pi/2, pi, 0); CGContextAddArc(context, minX+kRadius, minY+kRadius, kRadius, pi, pi+pi/2, 0); if (self.shadowColor) { CGContextSetShadowWithColor(context, self.shadowOffset, self.shadowBlur, self.shadowColor.CGColor); } CGContextFillPath(context); CGContextRestoreGState(context); if (!sUsesSolidTint) { // Add the gloss effect CGContextSaveGState(context); CGContextBeginPath(context); CGContextAddArc(context, maxX-kRadius, minY+kRadius, kRadius, pi+(pi/2), 0, 0); CGContextAddArc(context, minX+kRadius, minY+kRadius, kRadius, pi, pi+pi/2, 0); CGContextAddRect(context, CGRectMake(minX, minY + kRadius, rect.size.width - kRadius + 1, CGRectGetMidY(rect) - kRadius)); CGContextClip(context); size_t num_locations = 2; CGFloat locations[] = { 0.0f, 1.f }; CGFloat components[] = { 1.f, 1.f, 1.f, 0.8f, 1.f, 1.f, 1.f, 0.0f }; CGColorSpaceRef cspace; CGGradientRef gradient; cspace = CGColorSpaceCreateDeviceRGB(); gradient = CGGradientCreateWithColorComponents (cspace, components, locations, num_locations); CGPoint sPoint, ePoint; sPoint.x = 0; sPoint.y = 4; ePoint.x = 0; ePoint.y = CGRectGetMidY(rect) - 2; CGContextDrawLinearGradient (context, gradient, sPoint, ePoint, 0); CGColorSpaceRelease(cspace); CGGradientRelease(gradient); CGContextRestoreGState(context); // Draw the border CGContextBeginPath(context); CGContextSetLineWidth(context, kBadgeLineSize); CGContextSetStrokeColorWithColor(context, [[UIColor whiteColor] CGColor]); CGContextAddArc(context, maxX-kRadius, minY+kRadius, kRadius, pi+(pi/2), 0, 0); CGContextAddArc(context, maxX-kRadius, maxY-kRadius, kRadius, 0, pi/2, 0); CGContextAddArc(context, minX+kRadius, maxY-kRadius, kRadius, pi/2, pi, 0); CGContextAddArc(context, minX+kRadius, minY+kRadius, kRadius, pi, pi+pi/2, 0); CGContextClosePath(context); CGContextStrokePath(context); } // Draw text [self.textColor set]; [self.text drawAtPoint:CGPointMake(floorf((rect.size.width - textSize.width) / 2.f) - 0.f, floorf((rect.size.height - textSize.height) / 2.f) - 2.f) withFont:self.font]; } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/badge/src/NimbusBadge.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // Originally created by Roger Chapman // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /** * @defgroup NimbusBadge Nimbus Badge * @{ * * <div id="github" feature="badge"></div> * * This Nimbus badge view is a UIView that draws a customizable notification badge-like view. * * @image html badge-iphone-example1.png "Screenshot of a Nimbus badge on the iPhone" * * <h2>Minimum Requirements</h2> * * Required frameworks: * * - Foundation.framework * - UIKit.framework * * Minimum Operating System: <b>iOS 4.0</b> * * Source located in <code>src/badge/src</code> * @code #import "NimbusBadge.h" @endcode * * <h2>Basic Use</h2> * * The badge view works much like UILabel. Once you've assigned text and configured the attributes * you should call sizeToFit to have the badge determine its ideal size. * @code NIBadgeView* badgeView = [[NIBadgeView alloc] initWithFrame:CGRectZero]; badgeView.text = @"7"; [badgeView sizeToFit]; [self.view addSubview:badgeView]; @endcode * * @} */ #import <Foundation/Foundation.h> #import "NimbusCore.h" #import "NIBadgeView.h"
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/collections/src/NICollectionViewActions.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <Foundation/Foundation.h> #import "NimbusCore.h" /** * The NICollectionViewActions class provides an interface for attaching actions to objects in a * NICollectionViewModel. * * <h2>Basic Use</h2> * * NICollectionViewModel and NICollectionViewActions cooperate to solve two related tasks: data * representation and user actions, respectively. A NICollectionViewModel is composed of objects and * NICollectionViewActions maintains a mapping of actions to these objects. The object's attached * actions are executed when the user interacts with the cell representing an object. * * <h2>Delegate Forwarding</h2> * * Your delegate implementation can call the listed collectionView: methods in order for the * collection view to respond to user actions. Notably shouldHighlightItemAtIndexPath: allows * cells to be highlighted only if the cell's object has an attached action. * didSelectItemAtIndexPath: will execute the object's attached tap actions. * * If you use the delegate forwarders your collection view's data source must be an instance of * NICollectionViewModel. * * @ingroup CollectionViewTools */ @interface NICollectionViewActions : NIActions - (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath; - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath; @end /** * Asks the receiver whether the object at the given index path is actionable. * * collectionView.dataSource must be a NICollectionViewModel. * * @returns YES if the object at the given index path is actionable. * @fn NICollectionViewActions::collectionView:shouldHighlightItemAtIndexPath: */ /** * Asks the receiver to perform the tap action for an object at the given indexPath. * * collectionView.dataSource must be a NICollectionViewModel. * * @fn NICollectionViewActions::collectionView:didSelectItemAtIndexPath: */
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/collections/src/NICollectionViewActions.m
Objective-C
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NICollectionViewActions.h" #import "NICollectionViewCellFactory.h" #import "NimbusCore.h" #import "NIActions+Subclassing.h" #import <objc/runtime.h> #if !defined(__has_feature) || !__has_feature(objc_arc) #error "Nimbus requires ARC support." #endif @implementation NICollectionViewActions #pragma mark - UICollectionViewDelegate - (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath { BOOL shouldHighlight = NO; NIDASSERT([collectionView.dataSource isKindOfClass:[NICollectionViewModel class]]); if ([collectionView.dataSource isKindOfClass:[NICollectionViewModel class]]) { NICollectionViewModel* model = (NICollectionViewModel *)collectionView.dataSource; id object = [model objectAtIndexPath:indexPath]; if ([self isObjectActionable:object]) { NIObjectActions* action = [self actionForObjectOrClassOfObject:object]; // If the cell is tappable, reflect that in the selection style. if (nil != action.tapAction || nil != action.tapSelector || nil != action.detailAction || nil != action.detailSelector || nil != action.navigateAction || nil != action.navigateSelector) { shouldHighlight = YES; } } } return shouldHighlight; } - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath { NIDASSERT([collectionView.dataSource isKindOfClass:[NICollectionViewModel class]]); if ([collectionView.dataSource isKindOfClass:[NICollectionViewModel class]]) { NICollectionViewModel* model = (NICollectionViewModel *)collectionView.dataSource; id object = [model objectAtIndexPath:indexPath]; if ([self isObjectActionable:object]) { NIObjectActions* action = [self actionForObjectOrClassOfObject:object]; BOOL shouldDeselect = NO; if (action.tapAction) { // Tap actions can deselect the cell if they return YES. shouldDeselect = action.tapAction(object, self.target, indexPath); } if (action.tapSelector && [self.target respondsToSelector:action.tapSelector]) { NSMethodSignature *methodSignature = [self.target methodSignatureForSelector:action.tapSelector]; NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature]; invocation.selector = action.tapSelector; if (methodSignature.numberOfArguments >= 3) { [invocation setArgument:&object atIndex:2]; } if (methodSignature.numberOfArguments >= 4) { [invocation setArgument:&indexPath atIndex:3]; } [invocation invokeWithTarget:self.target]; NSUInteger length = invocation.methodSignature.methodReturnLength; if (length > 0) { char *buffer = (void *)malloc(length); memset(buffer, 0, sizeof(char) * length); [invocation getReturnValue:buffer]; for (NSUInteger index = 0; index < length; ++index) { if (buffer[index]) { shouldDeselect = YES; break; } } free(buffer); } } if (action.detailAction) { // Tap actions can deselect the cell if they return YES. action.detailAction(object, self.target, indexPath); } if (action.detailSelector && [self.target respondsToSelector:action.detailSelector]) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Warc-performSelector-leaks" [self.target performSelector:action.detailSelector withObject:object withObject:indexPath]; #pragma clang diagnostic pop } if (action.navigateAction) { // Tap actions can deselect the cell if they return YES. action.navigateAction(object, self.target, indexPath); } if (action.navigateSelector && [self.target respondsToSelector:action.navigateSelector]) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Warc-performSelector-leaks" [self.target performSelector:action.navigateSelector withObject:object withObject:indexPath]; #pragma clang diagnostic pop } if (shouldDeselect) { [collectionView deselectItemAtIndexPath:indexPath animated:YES]; } } } } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/collections/src/NICollectionViewCellFactory.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import "NICollectionViewModel.h" /** * A simple factory for creating collection view cells from objects. * * This factory provides a single method that accepts an object and returns a UICollectionViewCell * for use in a UICollectionView. A cell will only be returned if the object passed to the factory * conforms to the NICollectionViewCellObject protocol. The created cell should ideally conform to * the NICollectionViewCell protocol. If it does, the object will be passed to it via * @link NICollectionViewCell::shouldUpdateCellWithObject: shouldUpdateCellWithObject:@endlink * before the factory method returns. * * This factory is designed to be used with NICollectionViewModel, though one could easily use * it with other collection view data source implementations simply by providing nil for the * collection view model argument. * * If you instantiate an NICollectionViewCellFactory then you can provide explicit mappings from * objects to cells. This is helpful if the effort required to implement the NICollectionViewCell * protocol on an object outweighs the benefit of using the factory, i.e. when you want to map * simple types such as NSString to cells. * * @ingroup CollectionViewCellFactory */ @interface NICollectionViewCellFactory : NSObject <NICollectionViewModelDelegate> /** * Creates a cell from a given object if and only if the object conforms to the * NICollectionViewCellObject protocol. * * This method signature matches the NICollectionViewModelDelegate method so that you can * set this factory as the model's delegate: * * @code // Must cast to id to avoid compiler warnings. _model.delegate = (id)[NICollectionViewCellFactory class]; * @endcode * * If you would like to customize the factory's output, implement the model's delegate method * and call the factory method. Remember that if the factory doesn't know how to map * the object to a cell it will return nil. * * @code - (UICollectionViewCell *)collectionViewModel:(NICollectionViewModel *)collectionViewModel cellForCollectionView:(UICollectionView *)collectionView atIndexPath:(NSIndexPath *)indexPath withObject:(id)object { UICollectionViewCell* cell = [NICollectionViewCellFactory collectionViewModel:collectionViewModel cellForCollectionView:collectionView atIndexPath:indexPath withObject:object]; if (nil == cell) { // Custom cell creation here. } return cell; } * @endcode */ + (UICollectionViewCell *)collectionViewModel:(NICollectionViewModel *)collectionViewModel cellForCollectionView:(UICollectionView *)collectionView atIndexPath:(NSIndexPath *)indexPath withObject:(id)object; /** * Map an object's class to a cell's class. * * If an object implements the NICollectionViewCell protocol AND is found in this factory * mapping, the factory mapping will take precedence. This allows you to * explicitly override the mapping on a case-by-case basis. */ - (void)mapObjectClass:(Class)objectClass toCellClass:(Class)collectionViewCellClass; /** * Returns the mapped cell class for an object at a given index path. * * Explicitly mapped classes in the receiver take precedence over implicitly mapped classes. * * This method is helpful when implementing layout calculation methods for your collection view. You * can fetch the cell class and then perform any selectors that are necessary for calculating the * dimensions of the cell before it is instantiated. */ - (Class)collectionViewCellClassForItemAtIndexPath:(NSIndexPath *)indexPath model:(NICollectionViewModel *)model; /** * Returns the mapped cell class for an object at a given index path. * * This method is helpful when implementing layout calculation methods for your collection view. You * can fetch the cell class and then perform any selectors that are necessary for calculating the * dimensions of the cell before it is instantiated. */ + (Class)collectionViewCellClassForItemAtIndexPath:(NSIndexPath *)indexPath model:(NICollectionViewModel *)model; @end /** * The protocol for an object that can be used in the NICollectionViewCellFactory. * * @ingroup CollectionViewCellFactory */ @protocol NICollectionViewCellObject <NSObject> @required /** The class of cell to be created when this object is passed to the cell factory. */ - (Class)collectionViewCellClass; @end /** * The protocol for an object that can be used in the NICollectionViewCellFactory with Interface * Builder nibs. * * @ingroup CollectionViewCellFactory */ @protocol NICollectionViewNibCellObject <NSObject> @required /** A nib that contains a collection view cell to display this object's contents. */ - (UINib *)collectionViewCellNib; @end /** * The protocol for a cell created in the NICollectionViewCellFactory. * * Cells that implement this protocol are given the object that implemented the * NICollectionViewCellObject protocol and returned this cell's class name in * @link NICollectionViewCellObject::collectionViewCellClass collectionViewCellClass@endlink. * * @ingroup CollectionViewCellFactory */ @protocol NICollectionViewCell <NSObject> @required /** * Called both when a cell is created and when it is reused. * * Implement this method to customize the cell's properties for display using the given object. */ - (BOOL)shouldUpdateCellWithObject:(id)object; @optional /** * Asks the receiver whether the mapped object class should be appended to the reuse identifier * in order to create a unique cell.object identifier key. * * This is useful when you have a cell that is intended to be used by a variety of different * objects. */ + (BOOL)shouldAppendObjectClassToReuseIdentifier; @end /** * A light-weight implementation of the NICollectionViewCellObject protocol. * * Use this object in cases where you can't set up a hard binding between an object and a cell, * or when you simply don't want to. * * For example, let's say that you want to show a cell that shows a loading indicator. * Rather than create a new interface, LoadMoreObject, simply for the cell and binding it * to the cell view, you can create an NICollectionViewCellObject and pass the class name of the cell. * @code [contents addObject:[NICollectionViewCellObject objectWithCellClass:[LoadMoreCell class]]]; @endcode */ @interface NICollectionViewCellObject : NSObject <NICollectionViewCellObject> // Designated initializer. - (id)initWithCellClass:(Class)collectionViewCellClass userInfo:(id)userInfo; - (id)initWithCellClass:(Class)collectionViewCellClass; + (id)objectWithCellClass:(Class)collectionViewCellClass userInfo:(id)userInfo; + (id)objectWithCellClass:(Class)collectionViewCellClass; @property (nonatomic, readonly, strong) id userInfo; @end /** * An object that can be used to populate information in the cell. * * @fn NICollectionViewCellObject::userInfo */
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/collections/src/NICollectionViewCellFactory.m
Objective-C
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NICollectionViewCellFactory.h" #import "NimbusCore.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "Nimbus requires ARC support." #endif @interface NICollectionViewCellFactory() @property (nonatomic, copy) NSMutableDictionary* objectToCellMap; @property (nonatomic, copy) NSMutableSet* registeredObjectClasses; @end @implementation NICollectionViewCellFactory - (id)init { if ((self = [super init])) { _objectToCellMap = [[NSMutableDictionary alloc] init]; _registeredObjectClasses = [[NSMutableSet alloc] init]; } return self; } + (UICollectionViewCell *)cellWithClass:(Class)collectionViewCellClass collectionView:(UICollectionView *)collectionView indexPath:(NSIndexPath *)indexPath object:(id)object { UICollectionViewCell* cell = nil; NSString* identifier = NSStringFromClass(collectionViewCellClass); if ([collectionViewCellClass respondsToSelector:@selector(shouldAppendObjectClassToReuseIdentifier)] && [collectionViewCellClass shouldAppendObjectClassToReuseIdentifier]) { identifier = [identifier stringByAppendingFormat:@".%@", NSStringFromClass([object class])]; } [collectionView registerClass:collectionViewCellClass forCellWithReuseIdentifier:identifier]; cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath]; // Allow the cell to configure itself with the object's information. if ([cell respondsToSelector:@selector(shouldUpdateCellWithObject:)]) { [(id<NICollectionViewCell>)cell shouldUpdateCellWithObject:object]; } return cell; } + (UICollectionViewCell *)cellWithNib:(UINib *)collectionViewCellNib collectionView:(UICollectionView *)collectionView indexPath:(NSIndexPath *)indexPath object:(id)object { UICollectionViewCell* cell = nil; NSString* identifier = NSStringFromClass([object class]); [collectionView registerNib:collectionViewCellNib forCellWithReuseIdentifier:identifier]; cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath]; // Allow the cell to configure itself with the object's information. if ([cell respondsToSelector:@selector(shouldUpdateCellWithObject:)]) { [(id<NICollectionViewCell>)cell shouldUpdateCellWithObject:object]; } return cell; } + (UICollectionViewCell *)collectionViewModel:(NICollectionViewModel *)collectionViewModel cellForCollectionView:(UICollectionView *)collectionView atIndexPath:(NSIndexPath *)indexPath withObject:(id)object { UICollectionViewCell* cell = nil; // Only NICollectionViewCellObject-conformant objects may pass. if ([object respondsToSelector:@selector(collectionViewCellClass)]) { Class collectionViewCellClass = [object collectionViewCellClass]; cell = [self cellWithClass:collectionViewCellClass collectionView:collectionView indexPath:indexPath object:object]; } else if ([object respondsToSelector:@selector(collectionViewCellNib)]) { UINib* nib = [object collectionViewCellNib]; cell = [self cellWithNib:nib collectionView:collectionView indexPath:indexPath object:object]; } // If this assertion fires then your app is about to crash. You need to either add an explicit // binding in a NICollectionViewCellFactory object or implement either // NICollectionViewCellObject or NICollectionViewNibCellObject on this object and return a cell // class. NIDASSERT(nil != cell); return cell; } - (Class)collectionViewCellClassFromObject:(id)object { if (nil == object) { return nil; } Class objectClass = [object class]; Class collectionViewCellClass = [self.objectToCellMap objectForKey:objectClass]; BOOL hasExplicitMapping = (nil != collectionViewCellClass && collectionViewCellClass != [NSNull class]); if (!hasExplicitMapping && [object respondsToSelector:@selector(collectionViewCellClass)]) { collectionViewCellClass = [object collectionViewCellClass]; } if (nil == collectionViewCellClass) { collectionViewCellClass = [NIActions objectFromKeyClass:objectClass map:self.objectToCellMap]; } return collectionViewCellClass; } - (UICollectionViewCell *)collectionViewModel:(NICollectionViewModel *)collectionViewModel cellForCollectionView:(UICollectionView *)collectionView atIndexPath:(NSIndexPath *)indexPath withObject:(id)object { UICollectionViewCell* cell = nil; Class collectionViewCellClass = [self collectionViewCellClassFromObject:object]; if (nil != collectionViewCellClass) { cell = [[self class] cellWithClass:collectionViewCellClass collectionView:collectionView indexPath:indexPath object:object]; } else if ([object respondsToSelector:@selector(collectionViewCellNib)]) { UINib* nib = [object collectionViewCellNib]; cell = [[self class] cellWithNib:nib collectionView:collectionView indexPath:indexPath object:object]; } // If this assertion fires then your app is about to crash. You need to either add an explicit // binding in a NICollectionViewCellFactory object or implement the NICollectionViewCellObject // protocol on this object and return a cell class. NIDASSERT(nil != cell); return cell; } - (void)mapObjectClass:(Class)objectClass toCellClass:(Class)collectionViewCellClass { [self.objectToCellMap setObject:collectionViewCellClass forKey:(id<NSCopying>)objectClass]; } - (Class)collectionViewCellClassForItemAtIndexPath:(NSIndexPath *)indexPath model:(NICollectionViewModel *)model { id object = [model objectAtIndexPath:indexPath]; return [self collectionViewCellClassFromObject:object]; } + (Class)collectionViewCellClassForItemAtIndexPath:(NSIndexPath *)indexPath model:(NICollectionViewModel *)model { id object = [model objectAtIndexPath:indexPath]; Class collectionViewCellClass = nil; if ([object respondsToSelector:@selector(collectionViewCellClass)]) { collectionViewCellClass = [object collectionViewCellClass]; } return collectionViewCellClass; } @end @interface NICollectionViewCellObject() @property (nonatomic, assign) Class collectionViewCellClass; @property (nonatomic, strong) id userInfo; @end @implementation NICollectionViewCellObject - (id)initWithCellClass:(Class)collectionViewCellClass userInfo:(id)userInfo { if ((self = [super init])) { _collectionViewCellClass = collectionViewCellClass; _userInfo = userInfo; } return self; } - (id)initWithCellClass:(Class)collectionViewCellClass { return [self initWithCellClass:collectionViewCellClass userInfo:nil]; } + (id)objectWithCellClass:(Class)collectionViewCellClass userInfo:(id)userInfo { return [[self alloc] initWithCellClass:collectionViewCellClass userInfo:userInfo]; } + (id)objectWithCellClass:(Class)collectionViewCellClass { return [[self alloc] initWithCellClass:collectionViewCellClass userInfo:nil]; } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/collections/src/NICollectionViewModel+Private.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <Foundation/Foundation.h> @interface NICollectionViewModel() @property (nonatomic, strong) NSArray* sections; // Array of NICollectionViewModelSection @property (nonatomic, strong) NSArray* sectionIndexTitles; @property (nonatomic, strong) NSDictionary* sectionPrefixToSectionIndex; - (void)_resetCompiledData; - (void)_compileDataWithListArray:(NSArray *)listArray; - (void)_compileDataWithSectionedArray:(NSArray *)sectionedArray; @end @interface NICollectionViewModelSection : NSObject + (id)section; @property (nonatomic, copy) NSString* headerTitle; @property (nonatomic, copy) NSString* footerTitle; @property (nonatomic, strong) NSArray* rows; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/collections/src/NICollectionViewModel.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import "NIPreprocessorMacros.h" /* for weak */ @protocol NICollectionViewModelDelegate; #pragma mark Sectioned Array Objects // Classes used when creating NICollectionViewModels. @class NICollectionViewModelFooter; // Provides the information for a footer. /** * A non-mutable collection view model that complies to the UICollectionViewDataSource protocol. * * This model allows you to easily create a data source for a UICollectionView without having to * implement the UICollectionViewDataSource methods in your controller. * * This base class is non-mutable, much like an NSArray. You must initialize this model with * the contents when you create it. * * This model simply manages the data relationship with your collection view. It is up to you to * implement the collection view's layout object. * * @ingroup CollectionViewModels */ @interface NICollectionViewModel : NSObject <UICollectionViewDataSource> #pragma mark Creating Collection View Models // Designated initializer. - (id)initWithDelegate:(id<NICollectionViewModelDelegate>)delegate; - (id)initWithListArray:(NSArray *)listArray delegate:(id<NICollectionViewModelDelegate>)delegate; // Each NSString in the array starts a new section. Any other object is a new row (with exception of certain model-specific objects). - (id)initWithSectionedArray:(NSArray *)sectionedArray delegate:(id<NICollectionViewModelDelegate>)delegate; #pragma mark Accessing Objects - (id)objectAtIndexPath:(NSIndexPath *)indexPath; // This method is not appropriate for performance critical codepaths. - (NSIndexPath *)indexPathForObject:(id)object; #pragma mark Creating Collection View Cells @property (nonatomic, weak) id<NICollectionViewModelDelegate> delegate; @end /** * A protocol for NICollectionViewModel to fetch rows to be displayed for the collection view. * * @ingroup CollectionViewModels */ @protocol NICollectionViewModelDelegate <NSObject> @required /** * Fetches a collection view cell at a given index path with a given object. * * The implementation of this method will generally use object to customize the cell. */ - (UICollectionViewCell *)collectionViewModel:(NICollectionViewModel *)collectionViewModel cellForCollectionView:(UICollectionView *)collectionView atIndexPath:(NSIndexPath *)indexPath withObject:(id)object; @optional /** * Fetches a supplementary collection view element at a given indexPath. * * The value of the kind property and indexPath are implementation-dependent * based on the type of UICollectionViewLayout being used. */ - (UICollectionReusableView *)collectionViewModel:(NICollectionViewModel *)collectionViewModel collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath; @end /** * An object used in sectioned arrays to denote a section footer title. * * Meant to be used in a sectioned array for NICollectionViewModel. * * <h3>Example</h3> * * @code * [NICollectionViewModelFooter footerWithTitle:@"Footer"] * @endcode */ @interface NICollectionViewModelFooter : NSObject + (id)footerWithTitle:(NSString *)title; - (id)initWithTitle:(NSString *)title; @property (nonatomic, copy) NSString* title; @end /** @name Creating Collection View Models */ /** * Initializes a newly allocated static model with the given delegate and empty contents. * * This method can be used to create an empty model. * * @fn NICollectionViewModel::initWithDelegate: */ /** * Initializes a newly allocated static model with the contents of a list array. * * A list array is a one-dimensional array that defines a flat list of rows. There will be * no sectioning of contents in any way. * * <h3>Example</h3> * * @code * NSArray* contents = * [NSArray arrayWithObjects: * [NSDictionary dictionaryWithObject:@"Row 1" forKey:@"title"], * [NSDictionary dictionaryWithObject:@"Row 2" forKey:@"title"], * [NSDictionary dictionaryWithObject:@"Row 3" forKey:@"title"], * nil]; * [[NICollectionViewModel alloc] initWithListArray:contents delegate:self]; * @endcode * * @fn NICollectionViewModel::initWithListArray:delegate: */ /** * Initializes a newly allocated static model with the contents of a sectioned array. * * A sectioned array is a one-dimensional array that defines a list of sections and each * section's contents. Each NSString begins a new section and any other object defines a * row for the current section. * * <h3>Example</h3> * * @code * NSArray* contents = * [NSArray arrayWithObjects: * @"Section 1", * [NSDictionary dictionaryWithObject:@"Row 1" forKey:@"title"], * [NSDictionary dictionaryWithObject:@"Row 2" forKey:@"title"], * @"Section 2", * // This section is empty. * @"Section 3", * [NSDictionary dictionaryWithObject:@"Row 3" forKey:@"title"], * [NICollectionViewModelFooter footerWithTitle:@"Footer"], * nil]; * [[NICollectionViewModel alloc] initWithSectionedArray:contents delegate:self]; * @endcode * * @fn NICollectionViewModel::initWithSectionedArray:delegate: */ /** @name Accessing Objects */ /** * Returns the object at the given index path. * * If no object exists at the given index path (an invalid index path, for example) then nil * will be returned. * * @fn NICollectionViewModel::objectAtIndexPath: */ /** * Returns the index path of the given object within the model. * * If the model does not contain the object then nil will be returned. * * @fn NICollectionViewModel::indexPathForObject: */ /** @name Creating Collection View Cells */ /** * A delegate used to fetch collection view cells for the data source. * * @fn NICollectionViewModel::delegate */
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/collections/src/NICollectionViewModel.m
Objective-C
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NICollectionViewModel.h" #import "NICollectionViewModel+Private.h" #import "NimbusCore.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "Nimbus requires ARC support." #endif @implementation NICollectionViewModel - (id)initWithDelegate:(id<NICollectionViewModelDelegate>)delegate { if ((self = [super init])) { self.delegate = delegate; [self _resetCompiledData]; } return self; } - (id)initWithListArray:(NSArray *)listArray delegate:(id<NICollectionViewModelDelegate>)delegate { if ((self = [self initWithDelegate:delegate])) { [self _compileDataWithListArray:listArray]; } return self; } - (id)initWithSectionedArray:(NSArray *)sectionedArray delegate:(id<NICollectionViewModelDelegate>)delegate { if ((self = [self initWithDelegate:delegate])) { [self _compileDataWithSectionedArray:sectionedArray]; } return self; } - (id)init { return [self initWithDelegate:nil]; } #pragma mark - Compiling Data - (void)_resetCompiledData { self.sections = nil; self.sectionIndexTitles = nil; self.sectionPrefixToSectionIndex = nil; } - (void)_compileDataWithListArray:(NSArray *)listArray { [self _resetCompiledData]; if (nil != listArray) { NICollectionViewModelSection* section = [NICollectionViewModelSection section]; section.rows = listArray; self.sections = [NSArray arrayWithObject:section]; } } - (void)_compileDataWithSectionedArray:(NSArray *)sectionedArray { [self _resetCompiledData]; NSMutableArray* sections = [NSMutableArray array]; NSString* currentSectionHeaderTitle = nil; NSString* currentSectionFooterTitle = nil; NSMutableArray* currentSectionRows = nil; for (id object in sectionedArray) { BOOL isSection = [object isKindOfClass:[NSString class]]; BOOL isSectionFooter = [object isKindOfClass:[NICollectionViewModelFooter class]]; NSString* nextSectionHeaderTitle = nil; if (isSection) { nextSectionHeaderTitle = object; } else if (isSectionFooter) { NICollectionViewModelFooter* footer = object; currentSectionFooterTitle = footer.title; } else { if (nil == currentSectionRows) { currentSectionRows = [[NSMutableArray alloc] init]; } [currentSectionRows addObject:object]; } // A section footer or title has been encountered, if (nil != nextSectionHeaderTitle || nil != currentSectionFooterTitle) { if (nil != currentSectionHeaderTitle || nil != currentSectionFooterTitle || nil != currentSectionRows) { NICollectionViewModelSection* section = [NICollectionViewModelSection section]; section.headerTitle = currentSectionHeaderTitle; section.footerTitle = currentSectionFooterTitle; section.rows = currentSectionRows; [sections addObject:section]; } currentSectionRows = nil; currentSectionHeaderTitle = nextSectionHeaderTitle; currentSectionFooterTitle = nil; } } // Commit any unfinished sections. if ([currentSectionRows count] > 0 || nil != currentSectionHeaderTitle) { NICollectionViewModelSection* section = [NICollectionViewModelSection section]; section.headerTitle = currentSectionHeaderTitle; section.footerTitle = currentSectionFooterTitle; section.rows = currentSectionRows; [sections addObject:section]; } currentSectionRows = nil; // Update the compiled information for this data source. self.sections = sections; } #pragma mark - UICollectionViewDataSource - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView { return self.sections.count; } - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { NIDASSERT((NSUInteger)section < self.sections.count || 0 == self.sections.count); if ((NSUInteger)section < self.sections.count) { return [[[self.sections objectAtIndex:section] rows] count]; } else { return 0; } } - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { id object = [self objectAtIndexPath:indexPath]; return [self.delegate collectionViewModel:self cellForCollectionView:collectionView atIndexPath:indexPath withObject:object]; } - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath { if ([self.delegate respondsToSelector: @selector(collectionViewModel:collectionView:viewForSupplementaryElementOfKind:atIndexPath:)]) { return [self.delegate collectionViewModel:self collectionView:collectionView viewForSupplementaryElementOfKind:kind atIndexPath:indexPath]; } return nil; } #pragma mark - Public - (id)objectAtIndexPath:(NSIndexPath *)indexPath { if (nil == indexPath) { return nil; } NSInteger section = [indexPath section]; NSInteger row = [indexPath row]; id object = nil; NIDASSERT((NSUInteger)section < self.sections.count); if ((NSUInteger)section < self.sections.count) { NSArray* rows = [[self.sections objectAtIndex:section] rows]; NIDASSERT((NSUInteger)row < rows.count); if ((NSUInteger)row < rows.count) { object = [rows objectAtIndex:row]; } } return object; } - (NSIndexPath *)indexPathForObject:(id)object { if (nil == object) { return nil; } NSArray *sections = self.sections; for (NSUInteger sectionIndex = 0; sectionIndex < [sections count]; sectionIndex++) { NSArray* rows = [[sections objectAtIndex:sectionIndex] rows]; for (NSUInteger rowIndex = 0; rowIndex < [rows count]; rowIndex++) { if ([object isEqual:[rows objectAtIndex:rowIndex]]) { return [NSIndexPath indexPathForRow:rowIndex inSection:sectionIndex]; } } } return nil; } @end @implementation NICollectionViewModelFooter + (NICollectionViewModelFooter *)footerWithTitle:(NSString *)title { return [[self alloc] initWithTitle:title]; } - (id)initWithTitle:(NSString *)title { if ((self = [super init])) { self.title = title; } return self; } @end @implementation NICollectionViewModelSection + (id)section { return [[self alloc] init]; } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/collections/src/NIMutableCollectionViewModel+Private.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NIMutableCollectionViewModel.h" @interface NIMutableCollectionViewModel (Private) @property (nonatomic, strong) NSMutableArray* sections; // Array of NICollectionViewModelSection @end @interface NICollectionViewModelSection (Mutable) - (NSMutableArray *)mutableRows; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/collections/src/NIMutableCollectionViewModel.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NICollectionViewModel.h" /** * The NIMutableCollectionViewModel class is a mutable collection view model. * * When modifications are made to the model there are two ways to reflect the changes in the * collection view. * * - Call reloadData on the collection view. This is the most destructive way to update the * collection view. * - Call insert/delete/reload methods on the collection view with the retuned index path arrays. * * The latter option is the recommended approach to adding new cells to a collection view. Each * method in the mutable collection view model returns a data structure that can be used to inform * the collection view of the exact modifications that have been made to the model. * * Example of adding a new section: @code // Appends a new section to the end of the model. NSIndexSet* indexSet = [self.model addSectionWithTitle:@"New section"]; // Appends a cell to the last section in the model (in this case, the new section we just created). [self.model addObject:[TestTextCollectionViewCellObject objectWithTitle:@"A cell"]]; // Inform the collection view that we've modified the model. [self.collectionView insertSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic]; @endcode * * @ingroup TableViewModels */ @interface NIMutableCollectionViewModel : NICollectionViewModel - (NSArray *)addObject:(id)object; - (NSArray *)addObject:(id)object toSection:(NSUInteger)section; - (NSArray *)addObjectsFromArray:(NSArray *)array; - (NSArray *)insertObject:(id)object atRow:(NSUInteger)row inSection:(NSUInteger)section; - (NSArray *)removeObjectAtIndexPath:(NSIndexPath *)indexPath; - (NSIndexSet *)addSectionWithTitle:(NSString *)title; - (NSIndexSet *)insertSectionWithTitle:(NSString *)title atIndex:(NSUInteger)index; - (NSIndexSet *)removeSectionAtIndex:(NSUInteger)index; @end /** @name Modifying Objects */ /** * Appends an object to the last section. * * If no sections exist, a section will be created without a title and the object will be added to * this new section. * * @param object The object to append to the last section. * @returns An array with a single NSIndexPath representing the index path of the new object * in the model. * @fn NIMutableCollectionViewModel::addObject: */ /** * Appends an object to the end of the given section. * * @param object The object to append to the section. * @param section The index of the section to which this object should be appended. * @returns An array with a single NSIndexPath representing the index path of the new object * in the model. * @fn NIMutableCollectionViewModel::addObject:toSection: */ /** * Appends an array of objects to the last section. * * If no section exists, a section will be created without a title and the objects will be added to * this new section. * * @param array The array of objects to append to the last section. * @returns An array of NSIndexPath objects representing the index paths of the objects in the * model. * @fn NIMutableCollectionViewModel::addObjectsFromArray: */ /** * Inserts an object into the given section at the given row. * * @param object The object to append to the section. * @param row The row within the section at which to insert the object. * @param section The index of the section in which the object should be inserted. * @returns An array with a single NSIndexPath representing the index path of the new object * in the model. * @fn NIMutableCollectionViewModel::insertObject:atRow:inSection: */ /** * Removes an object at the given index path. * * If the index path does not represent a valid object then a debug assertion will fire and the * method will return nil without removing any object. * * @param indexPath The index path at which to remove a single object. * @returns An array with a single NSIndexPath representing the index path of the object that * was removed from the model, or nil if no object exists at the given index path. * @fn NIMutableCollectionViewModel::removeObjectAtIndexPath: */ /** @name Modifying Sections */ /** * Appends a section with a given title to the model. * * @param title The title of the new section. * @returns An index set with a single index representing the index of the new section. * @fn NIMutableCollectionViewModel::addSectionWithTitle: */ /** * Inserts a section with a given title to the model at the given index. * * @param title The title of the new section. * @param index The index in the model at which to add the new section. * @returns An index set with a single index representing the index of the new section. * @fn NIMutableCollectionViewModel::insertSectionWithTitle:atIndex: */ /** * Removes a section at the given index. * * @param index The index in the model of the section to remove. * @returns An index set with a single index representing the index of the removed section. * @fn NIMutableCollectionViewModel::removeSectionAtIndex: */ /** @name Updating the Section Index */ /** * Updates the section index with the current section index settings. * * This method should be called after modifying the model if a section index is being used. * * @fn NIMutableCollectionViewModel::updateSectionIndex */
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/collections/src/NIMutableCollectionViewModel.m
Objective-C
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NIMutableCollectionViewModel.h" #import "NICollectionViewModel.h" #import "NICollectionViewModel+Private.h" #import "NIMutableCollectionViewModel+Private.h" #import "NimbusCore.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "Nimbus requires ARC support." #endif @implementation NIMutableCollectionViewModel #pragma mark - Public - (NSArray *)addObject:(id)object { NICollectionViewModelSection* section = self.sections.count == 0 ? [self _appendSection] : self.sections.lastObject; [section.mutableRows addObject:object]; return [NSArray arrayWithObject:[NSIndexPath indexPathForRow:section.mutableRows.count - 1 inSection:self.sections.count - 1]]; } - (NSArray *)addObject:(id)object toSection:(NSUInteger)sectionIndex { NIDASSERT(sectionIndex >= 0 && sectionIndex < self.sections.count); NICollectionViewModelSection *section = [self.sections objectAtIndex:sectionIndex]; [section.mutableRows addObject:object]; return [NSArray arrayWithObject:[NSIndexPath indexPathForRow:section.mutableRows.count - 1 inSection:sectionIndex]]; } - (NSArray *)addObjectsFromArray:(NSArray *)array { NSMutableArray* indices = [NSMutableArray array]; for (id object in array) { [indices addObject:[[self addObject:object] objectAtIndex:0]]; } return indices; } - (NSArray *)insertObject:(id)object atRow:(NSUInteger)row inSection:(NSUInteger)sectionIndex { NIDASSERT(sectionIndex >= 0 && sectionIndex < self.sections.count); NICollectionViewModelSection *section = [self.sections objectAtIndex:sectionIndex]; [section.mutableRows insertObject:object atIndex:row]; return [NSArray arrayWithObject:[NSIndexPath indexPathForRow:row inSection:sectionIndex]]; } - (NSArray *)removeObjectAtIndexPath:(NSIndexPath *)indexPath { NIDASSERT(indexPath.section < (NSInteger)self.sections.count); if (indexPath.section >= (NSInteger)self.sections.count) { return nil; } NICollectionViewModelSection* section = [self.sections objectAtIndex:indexPath.section]; NIDASSERT(indexPath.row < (NSInteger)section.mutableRows.count); if (indexPath.row >= (NSInteger)section.mutableRows.count) { return nil; } [section.mutableRows removeObjectAtIndex:indexPath.row]; return [NSArray arrayWithObject:indexPath]; } - (NSIndexSet *)addSectionWithTitle:(NSString *)title { NICollectionViewModelSection* section = [self _appendSection]; section.headerTitle = title; return [NSIndexSet indexSetWithIndex:self.sections.count - 1]; } - (NSIndexSet *)insertSectionWithTitle:(NSString *)title atIndex:(NSUInteger)index { NICollectionViewModelSection* section = [self _insertSectionAtIndex:index]; section.headerTitle = title; return [NSIndexSet indexSetWithIndex:index]; } - (NSIndexSet *)removeSectionAtIndex:(NSUInteger)index { NIDASSERT(index >= 0 && index < self.sections.count); [self.sections removeObjectAtIndex:index]; return [NSIndexSet indexSetWithIndex:index]; } #pragma mark - Private - (NICollectionViewModelSection *)_appendSection { if (nil == self.sections) { self.sections = [NSMutableArray array]; } NICollectionViewModelSection* section = nil; section = [[NICollectionViewModelSection alloc] init]; section.rows = [NSMutableArray array]; [self.sections addObject:section]; return section; } - (NICollectionViewModelSection *)_insertSectionAtIndex:(NSUInteger)index { if (nil == self.sections) { self.sections = [NSMutableArray array]; } NICollectionViewModelSection* section = nil; section = [[NICollectionViewModelSection alloc] init]; section.rows = [NSMutableArray array]; NIDASSERT(index >= 0 && index <= self.sections.count); [self.sections insertObject:section atIndex:index]; return section; } @end @implementation NICollectionViewModelSection (Mutable) - (NSMutableArray *)mutableRows { NIDASSERT([self.rows isKindOfClass:[NSMutableArray class]] || nil == self.rows); self.rows = nil == self.rows ? [NSMutableArray array] : self.rows; return (NSMutableArray *)self.rows; } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/collections/src/NimbusCollections.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #pragma mark - Nimbus Collections /** * @defgroup NimbusCollections Nimbus Collections * @{ * * <div id="github" feature="collections"></div> * * Collection views are a new feature in iOS 6 that enable powerful collections of views to be * built. * * Collection views introduce a new concept of "layout" alongside the existing data source and * delegate concepts. Nimbus Collections provides support only for the data source with the * NICollectionViewModel. NICollectionViewModel behaves similarly to NITableViewModel in that you * provide it with an array of objects which are mapped to cells using a factory. */ #pragma mark * Collection View Models /** * @defgroup CollectionViewModels Collection View Models */ #pragma mark * Collection View Cell Factory /** * @defgroup CollectionViewCellFactory Collection View Cell Factory */ #pragma mark * Model Tools /** * @defgroup CollectionViewTools Collection View Tools */ #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import "NICollectionViewActions.h" #import "NICollectionViewCellFactory.h" #import "NICollectionViewModel.h" #import "NIMutableCollectionViewModel.h" /**@}*/
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/core/src/NIActions+Subclassing.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NIActions.h" @interface NIObjectActions : NSObject @property (nonatomic, copy) NIActionBlock tapAction; @property (nonatomic, copy) NIActionBlock detailAction; @property (nonatomic, copy) NIActionBlock navigateAction; @property (nonatomic) SEL tapSelector; @property (nonatomic) SEL detailSelector; @property (nonatomic) SEL navigateSelector; @end @interface NIActions () @property (nonatomic, weak) id target; - (NIObjectActions *)actionForObjectOrClassOfObject:(id<NSObject>)object; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/core/src/NIActions.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <Foundation/Foundation.h> /** * For attaching actions to objects. * * @ingroup NimbusCore * @defgroup Actions Actions * @{ */ /** * @param object An action was performed on this object. * @param target The target that was attached to the NIActions instance. * @param indexPath The index path of the object. */ typedef BOOL (^NIActionBlock)(id object, id target, NSIndexPath* indexPath); /** * The NIActions class provides a generic interface for attaching actions to objects. * * NIActions are used to implement user interaction in UITableViews and UICollectionViews via the * corresponding classes (NITableViewActions and NICollectionViewActions) in the respective * feature. NIActions separates the necessity * * <h3>Types of Actions</h3> * * The three primary types of actions are: * * - buttons, * - detail views, * - and pushing a new controller onto the navigation controller. * * <h3>Attaching Actions</h3> * * Actions may be attached to specific instances of objects or to entire classes of objects. When * an action is attached to both a class of object and an instance of that class, only the instance * action should be executed. * * All attachment methods return the object that was provided. This makes it simple to attach * actions within an array creation statement. * * Actions come in two forms: blocks and selector invocations. Both can be attached to an object * for each type of action and both will be executed, with the block being executed first. Blocks * should be used for simple executions while selectors should be used when the action is complex. * * The following is an example of using NITableViewActions: * @code NSArray *objects = @[ [NITitleCellObject objectWithTitle:@"Implicit tap handler"], [self.actions attachToObject:[NITitleCellObject objectWithTitle:@"Explicit tap handler"] tapBlock: ^BOOL(id object, id target) { NSLog(@"Object was tapped with an explicit action: %@", object); }] ]; [self.actions attachToClass:[NITitleCellObject class] tapBlock: ^BOOL(id object, id target) { NSLog(@"Object was tapped: %@", object); }]; @endcode * */ @interface NIActions : NSObject // Designated initializer. - (id)initWithTarget:(id)target; #pragma mark Mapping Objects - (id)attachToObject:(id<NSObject>)object tapBlock:(NIActionBlock)action; - (id)attachToObject:(id<NSObject>)object detailBlock:(NIActionBlock)action; - (id)attachToObject:(id<NSObject>)object navigationBlock:(NIActionBlock)action; - (id)attachToObject:(id<NSObject>)object tapSelector:(SEL)selector; - (id)attachToObject:(id<NSObject>)object detailSelector:(SEL)selector; - (id)attachToObject:(id<NSObject>)object navigationSelector:(SEL)selector; #pragma mark Mapping Classes - (void)attachToClass:(Class)aClass tapBlock:(NIActionBlock)action; - (void)attachToClass:(Class)aClass detailBlock:(NIActionBlock)action; - (void)attachToClass:(Class)aClass navigationBlock:(NIActionBlock)action; - (void)attachToClass:(Class)aClass tapSelector:(SEL)selector; - (void)attachToClass:(Class)aClass detailSelector:(SEL)selector; - (void)attachToClass:(Class)aClass navigationSelector:(SEL)selector; #pragma mark Object State - (BOOL)isObjectActionable:(id<NSObject>)object; + (id)objectFromKeyClass:(Class)keyClass map:(NSMutableDictionary *)map; @end #if defined __cplusplus extern "C" { #endif /** * Returns a block that pushes an instance of the controllerClass onto the navigation stack. * * Allocates an instance of the controller class and calls the init selector. * * The target property of the NIActions instance must be an instance of UIViewController * with an attached navigationController. * * @param controllerClass The class of controller to instantiate. */ NIActionBlock NIPushControllerAction(Class controllerClass); #if defined __cplusplus }; #endif /** @name Creating Table View Actions */ /** * Initializes a newly allocated table view actions object with the given controller. * * @attention This method is deprecated. Use the new method * @link NIActions::initWithTarget: initWithTarget:@endlink. * * The controller is stored as a weak reference internally. * * @param controller The controller that will be used in action blocks. * @fn NIActions::initWithController: */ /** * Initializes a newly allocated table view actions object with the given target. * * This is the designated initializer. * * The target is stored as a weak reference internally. * * @param target The target that will be provided to action blocks and on which selectors will * be performed. * @fn NIActions::initWithTarget: */ /** @name Mapping Objects */ /** * Attaches a tap action to the given object. * * A cell with an attached tap action will have its selectionStyle set to * @c tableViewCellSelectionStyle when the cell is displayed. * * The action will be executed when the object's corresponding cell is tapped. The object argument * of the block will be the object to which this action was attached. The target argument of the * block will be this receiver's @c target. * * Return NO if the tap action is used to present a modal view controller. This provides a visual * reminder to the user when the modal controller is dismissed as to which cell was tapped to invoke * the modal controller. * * The tap action will be invoked first, followed by the navigation action if one is attached. * * @param object The object to attach the action to. This object must be contained within * an NITableViewModel. * @param action The tap action block. * @returns The object that you attached this action to. * @fn NIActions::attachToObject:tapBlock: * @sa NIActions::attachToObject:tapSelector: */ /** * Attaches a detail action to the given object. * * When a cell with a detail action is displayed, its accessoryType will be set to * UITableViewCellAccessoryDetailDisclosureButton. * * When a cell's detail button is tapped, the detail action block will be executed. The return * value of the block is ignored. * * @param object The object to attach the action to. This object must be contained within * an NITableViewModel. * @param action The detail action block. * @returns The object that you attached this action to. * @fn NIActions::attachToObject:detailBlock: */ /** * Attaches a navigation action to the given object. * * When a cell with a navigation action is displayed, its accessoryType will be set to * UITableViewCellAccessoryDisclosureIndicator if there is no detail action, otherwise the * detail disclosure indicator takes precedence. * * When a cell with a navigation action is tapped the navigation block will be executed. * * If a tap action also exists for this object then the tap action will be executed first, followed * by the navigation action. * * @param object The object to attach the action to. This object must be contained within * an NITableViewModel. * @param action The navigation action block. * @returns The object that you attached this action to. * @fn NIActions::attachToObject:navigationBlock: */ /** * Attaches a tap selector to the given object. * * The method signature for the selector is: @code - (BOOL)didTapObject:(id)object; @endcode * * A cell with an attached tap action will have its selectionStyle set to * @c tableViewCellSelectionStyle when the cell is displayed. * * The selector will be performed on the action object's target when a cell with a tap selector is * tapped, unless that selector does not exist on the @c target in which case nothing happens. * * If the selector invocation returns YES then the cell will be deselected immediately after the * invocation completes its execution. If NO is returned then the cell's selection will remain. * * Return NO if the tap action is used to present a modal view controller. This provides a visual * reminder to the user when the modal controller is dismissed as to which cell was tapped to invoke * the modal controller. * * The tap action will be invoked first, followed by the navigation action if one is attached. * * @param object The object to attach the selector to. This object must be contained within * an NITableViewModel. * @param selector The selector that will be invoked by this action. * @returns The object that you attached this action to. * @fn NIActions::attachToObject:tapSelector: * @sa NIActions::attachToObject:tapBlock: */ /** * Attaches a detail selector to the given object. * * The method signature for the selector is: @code - (void)didTapObject:(id)object; @endcode * * A cell with an attached tap action will have its selectionStyle set to * @c tableViewCellSelectionStyle and its accessoryType set to * @c UITableViewCellAccessoryDetailDisclosureButton when the cell is displayed. * * The selector will be performed on the action object's target when a cell with a detail selector's * accessory indicator is tapped, unless that selector does not exist on the @c target in which * case nothing happens. * * @param object The object to attach the selector to. This object must be contained within * an NITableViewModel. * @param selector The selector that will be invoked by this action. * @returns The object that you attached this action to. * @fn NIActions::attachToObject:detailSelector: * @sa NIActions::attachToObject:detailBlock: */ /** * Attaches a navigation selector to the given object. * * The method signature for the selector is: @code - (void)didTapObject:(id)object; @endcode * * A cell with an attached navigation action will have its selectionStyle set to * @c tableViewCellSelectionStyle and its accessoryType set to * @c UITableViewCellAccessoryDetailDisclosureButton, unless it also has an attached detail action, * in which case its accessoryType will be set to @c UITableViewCellAccessoryDisclosureIndicator * when the cell is displayed. * * The selector will be performed on the action object's target when a cell with a navigation * selector is tapped, unless that selector does not exist on the @c target in which case nothing * happens. * * @param object The object to attach the selector to. This object must be contained within * an NITableViewModel. * @param selector The selector that will be invoked by this action. * @returns The object that you attached this action to. * @fn NIActions::attachToObject:navigationSelector: * @sa NIActions::attachToObject:navigationBlock: */ /** @name Mapping Classes */ /** * Attaches a tap block to a class. * * This method behaves similarly to attachToObject:tapBlock: except it attaches a tap action to * all instances and subclassed instances of a given class. * * @param aClass The class to attach the action to. * @param action The tap action block. * @fn NIActions::attachToClass:tapBlock: */ /** * Attaches a detail block to a class. * * This method behaves similarly to attachToObject:detailBlock: except it attaches a detail action * to all instances and subclassed instances of a given class. * * @param aClass The class to attach the action to. * @param action The detail action block. * @fn NIActions::attachToClass:detailBlock: */ /** * Attaches a navigation block to a class. * * This method behaves similarly to attachToObject:navigationBlock: except it attaches a navigation * action to all instances and subclassed instances of a given class. * * @param aClass The class to attach the action to. * @param action The navigation action block. * @fn NIActions::attachToClass:navigationBlock: */ /** * Attaches a tap selector to a class. * * This method behaves similarly to attachToObject:tapBlock: except it attaches a tap action to * all instances and subclassed instances of a given class. * * @param aClass The class to attach the action to. * @param selector The tap selector. * @fn NIActions::attachToClass:tapSelector: */ /** * Attaches a detail selector to a class. * * This method behaves similarly to attachToObject:detailBlock: except it attaches a detail action * to all instances and subclassed instances of a given class. * * @param aClass The class to attach the action to. * @param selector The tap selector. * @fn NIActions::attachToClass:detailSelector: */ /** * Attaches a navigation selector to a class. * * This method behaves similarly to attachToObject:navigationBlock: except it attaches a navigation * action to all instances and subclassed instances of a given class. * * @param aClass The class to attach the action to. * @param selector The tap selector. * @fn NIActions::attachToClass:navigationSelector: */ /** @name Object State */ /** * Returns whether or not the object has any actions attached to it. * * @fn NIActions::isObjectActionable: */ /** * Returns a mapped object from the given key class. * * If the key class is a subclass of any mapped key classes, the nearest ancestor class's mapped * object will be returned and keyClass will be added to the map for future accesses. * * @param keyClass The key class that will be used to find the mapping in map. * @param map A map of key classes to classes. May be modified if keyClass is a subclass of * any existing key classes. * @returns The mapped object if a match for keyClass was found in map. nil is returned * otherwise. * @fn NIActions::objectFromKeyClass:map: */ /**@}*/// End of Actions //////////////////////////////////////////////////////////////////////////
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/core/src/NIActions.m
Objective-C
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NIActions.h" #import "NIActions+Subclassing.h" #import "NIDebuggingTools.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "Nimbus requires ARC support." #endif @interface NIActions () @property (nonatomic, strong) NSMutableDictionary* objectToAction; @property (nonatomic, strong) NSMutableDictionary* classToAction; @property (nonatomic, strong) NSMutableSet* objectSet; @end @implementation NIActions - (id)initWithTarget:(id)target { if ((self = [super init])) { _target = target; _objectToAction = [[NSMutableDictionary alloc] init]; _classToAction = [[NSMutableDictionary alloc] init]; _objectSet = [[NSMutableSet alloc] init]; } return self; } - (id)init { return [self initWithTarget:nil]; } #pragma mark - Private - (id)keyForObject:(id<NSObject>)object { return @(object.hash); } // // actionForObject: and actionForClass: are used when attaching actions to objects and classes and // will always return an NIObjectActions object. These methods should not be used for determining // whether an action is attached to a given object or class. // // actionForObjectOrClassOfObject: determines whether an action has been attached to an object // or class of object and then returns the NIObjectActions or nil if no actions have been attached. // // Retrieves an NIObjectActions object for the given object or creates one if it doesn't yet exist // so that actions may be attached. - (NIObjectActions *)actionForObject:(id<NSObject>)object { id key = [self keyForObject:object]; NIObjectActions* action = [self.objectToAction objectForKey:key]; if (nil == action) { action = [[NIObjectActions alloc] init]; [self.objectToAction setObject:action forKey:key]; } return action; } // Retrieves an NIObjectActions object for the given class or creates one if it doesn't yet exist // so that actions may be attached. - (NIObjectActions *)actionForClass:(Class)class { NIObjectActions* action = [self.classToAction objectForKey:class]; if (nil == action) { action = [[NIObjectActions alloc] init]; [self.classToAction setObject:action forKey:(id<NSCopying>)class]; } return action; } // Fetches any attached actions for a given object. - (NIObjectActions *)actionForObjectOrClassOfObject:(id<NSObject>)object { id key = [self keyForObject:object]; NIObjectActions* action = [self.objectToAction objectForKey:key]; if (nil == action) { action = [self.class objectFromKeyClass:object.class map:self.classToAction]; } return action; } #pragma mark - Public - (id)attachToObject:(id<NSObject>)object tapBlock:(NIActionBlock)action { [self.objectSet addObject:object]; [self actionForObject:object].tapAction = action; return object; } - (id)attachToObject:(id<NSObject>)object detailBlock:(NIActionBlock)action { [self.objectSet addObject:object]; [self actionForObject:object].detailAction = action; return object; } - (id)attachToObject:(id<NSObject>)object navigationBlock:(NIActionBlock)action { [self.objectSet addObject:object]; [self actionForObject:object].navigateAction = action; return object; } - (id)attachToObject:(id<NSObject>)object tapSelector:(SEL)selector { [self.objectSet addObject:object]; [self actionForObject:object].tapSelector = selector; return object; } - (id)attachToObject:(id<NSObject>)object detailSelector:(SEL)selector { [self.objectSet addObject:object]; [self actionForObject:object].detailSelector = selector; return object; } - (id)attachToObject:(id<NSObject>)object navigationSelector:(SEL)selector { [self.objectSet addObject:object]; [self actionForObject:object].navigateSelector = selector; return object; } - (void)attachToClass:(Class)aClass tapBlock:(NIActionBlock)action { [self actionForClass:aClass].tapAction = action; } - (void)attachToClass:(Class)aClass detailBlock:(NIActionBlock)action { [self actionForClass:aClass].detailAction = action; } - (void)attachToClass:(Class)aClass navigationBlock:(NIActionBlock)action { [self actionForClass:aClass].navigateAction = action; } - (void)attachToClass:(Class)aClass tapSelector:(SEL)selector { [self actionForClass:aClass].tapSelector = selector; } - (void)attachToClass:(Class)aClass detailSelector:(SEL)selector { [self actionForClass:aClass].detailSelector = selector; } - (void)attachToClass:(Class)aClass navigationSelector:(SEL)selector { [self actionForClass:aClass].navigateSelector = selector; } - (BOOL)isObjectActionable:(id<NSObject>)object { if (nil == object) { return NO; } BOOL objectIsActionable = [self.objectSet containsObject:object]; if (!objectIsActionable) { objectIsActionable = (nil != [self.class objectFromKeyClass:object.class map:self.classToAction]); } return objectIsActionable; } + (id)objectFromKeyClass:(Class)keyClass map:(NSMutableDictionary *)map { id object = [map objectForKey:keyClass]; if (nil == object) { // No mapping found for this key class, but it may be a subclass of another object that does // have a mapping, so let's see what we can find. Class superClass = nil; for (Class class in map.allKeys) { // We want to find the lowest node in the class hierarchy so that we pick the lowest ancestor // in the hierarchy tree. if ([keyClass isSubclassOfClass:class] && (nil == superClass || [keyClass isSubclassOfClass:superClass])) { superClass = class; } } if (nil != superClass) { object = [map objectForKey:superClass]; // Add this subclass to the map so that next time this result is instant. [map setObject:object forKey:(id<NSCopying>)keyClass]; } } if (nil == object) { // We couldn't find a mapping at all so let's add an empty mapping. [map setObject:[NSNull class] forKey:(id<NSCopying>)keyClass]; } else if (object == [NSNull class]) { // Don't return null mappings. object = nil; } return object; } @end @implementation NIObjectActions @end NIActionBlock NIPushControllerAction(Class controllerClass) { return [^(id object, id target, NSIndexPath* indexPath) { // You must initialize the actions object with initWithTarget: and pass a valid // controller. NIDASSERT(nil != target); NIDASSERT([target isKindOfClass:[UIViewController class]]); UIViewController *controller = target; if (nil != controller && [controller isKindOfClass:[UIViewController class]]) { // No navigation controller to push this new controller; this controller // is going to be lost. NIDASSERT(nil != controller.navigationController); UIViewController* controllerToPush = [[controllerClass alloc] init]; [controller.navigationController pushViewController:controllerToPush animated:YES]; } return NO; } copy]; }
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/core/src/NIButtonUtilities.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #if defined __cplusplus extern "C" { #endif /** * For manipulating UIButton objects. * * @ingroup NimbusCore * @defgroup Button-Utilities Button Utilities * @{ * * The methods provided here make it possible to specify different properties for different button * states in a scalable way. For example, you can define a stylesheet class that has a number of * class methods that return the various properties for buttons. * @code @implementation Stylesheet + (UIImage *)backgroundImageForButtonWithState:(UIControlState)state { if (state & UIControlStateHighlighted) { return [UIImage imageNamed:@"button_highlighted"]; } else if (state == UIControlStateNormal) { return [UIImage imageNamed:@"button"]; } return nil; } @end // The result of the implementation above will set the background images for the button's // highlighted and default states. NIApplyBackgroundImageSelectorToButton(@selector(backgroundImageForButtonWithState:), [Stylesheet class], button); @endcode */ /** * Sets the images for a button's states. * * @param selector A selector of the form: * (UIImage *)imageWithControlState:(UIControlState)controlState * @param target The target upon which the selector will be invoked. * @param button The button object whose properties should be modified. */ void NIApplyImageSelectorToButton(SEL selector, id target, UIButton* button); /** * Sets the background images for a button's states. * * @param selector A selector of the form: * (UIImage *)backgroundImageWithControlState:(UIControlState)controlState * @param target The target upon which the selector will be invoked. * @param button The button object whose properties should be modified. */ void NIApplyBackgroundImageSelectorToButton(SEL selector, id target, UIButton* button); /** * Sets the title colors for a button's states. * * @param selector A selector of the form: * (UIColor *)colorWithControlState:(UIControlState)controlState * @param target The target upon which the selector will be invoked. * @param button The button object whose properties should be modified. */ void NIApplyTitleColorSelectorToButton(SEL selector, id target, UIButton* button); /**@}*/// End of Button Utilities ///////////////////////////////////////////////////////////////// #if defined __cplusplus }; #endif
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/core/src/NIButtonUtilities.m
Objective-C
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NIButtonUtilities.h" void NIApplyImageSelectorToButton(SEL selector, id target, UIButton* button) { IMP method = [target methodForSelector:selector]; UIImage* image = nil; image = method(target, selector, UIControlStateNormal); [button setImage:image forState:UIControlStateNormal]; image = method(target, selector, UIControlStateHighlighted); [button setImage:image forState:UIControlStateHighlighted]; image = method(target, selector, UIControlStateDisabled); [button setImage:image forState:UIControlStateDisabled]; image = method(target, selector, UIControlStateSelected); [button setImage:image forState:UIControlStateSelected]; UIControlState selectedHighlightState = UIControlStateSelected | UIControlStateHighlighted; image = method(target, selector, selectedHighlightState); [button setImage:image forState:selectedHighlightState]; } void NIApplyBackgroundImageSelectorToButton(SEL selector, id target, UIButton* button) { IMP method = [target methodForSelector:selector]; UIImage* image = nil; image = method(target, selector, UIControlStateNormal); [button setBackgroundImage:image forState:UIControlStateNormal]; image = method(target, selector, UIControlStateHighlighted); [button setBackgroundImage:image forState:UIControlStateHighlighted]; image = method(target, selector, UIControlStateDisabled); [button setBackgroundImage:image forState:UIControlStateDisabled]; image = method(target, selector, UIControlStateSelected); [button setBackgroundImage:image forState:UIControlStateSelected]; UIControlState selectedHighlightState = UIControlStateSelected | UIControlStateHighlighted; image = method(target, selector, selectedHighlightState); [button setBackgroundImage:image forState:selectedHighlightState]; } void NIApplyTitleColorSelectorToButton(SEL selector, id target, UIButton* button) { IMP method = [target methodForSelector:selector]; UIColor* color = nil; color = method(target, selector, UIControlStateNormal); [button setTitleColor:color forState:UIControlStateNormal]; color = method(target, selector, UIControlStateHighlighted); [button setTitleColor:color forState:UIControlStateHighlighted]; color = method(target, selector, UIControlStateDisabled); [button setTitleColor:color forState:UIControlStateDisabled]; color = method(target, selector, UIControlStateSelected); [button setTitleColor:color forState:UIControlStateSelected]; UIControlState selectedHighlightState = UIControlStateSelected | UIControlStateHighlighted; color = method(target, selector, selectedHighlightState); [button setTitleColor:color forState:selectedHighlightState]; }
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/core/src/NICommonMetrics.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #if defined __cplusplus extern "C" { #endif /** * For common system metrics. * * If you work with system metrics in any way it can be a pain in the ass to figure out what the * exact metrics are. Figuring out how long it takes the status bar to animate is not something you * should be spending your time on. The metrics in this file are provided as a means of unifying a * number of system metrics for use in your applications. * * <h2>What Qualifies as a Common Metric</h2> * * Common metrics are system components, such as the dimensions of a toolbar in * a particular orientation or the duration of a standard animation. This is * not the place to put feature-specific metrics, such as the height of a photo scrubber * view. * * <h2>Examples</h2> * * <h3>Positioning a Toolbar</h3> * * The following example updates the position and height of a toolbar when the device * orientation is changing. This ensures that, in landscape mode on the iPhone, the toolbar * is slightly shorter to accomodate the smaller height of the screen. * * @code * - (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation * duration:(NSTimeInterval)duration { * [super willAnimateRotationToInterfaceOrientation:toInterfaceOrientation duration:duration]; * * CGRect toolbarFrame = self.toolbar.frame; * toolbarFrame.size.height = NIToolbarHeightForOrientation(toInterfaceOrientation); * toolbarFrame.origin.y = self.view.bounds.size.height - toolbarFrame.size.height; * self.toolbar.frame = toolbarFrame; * } * @endcode * * @ingroup NimbusCore * @defgroup Common-Metrics Common Metrics * @{ */ #ifndef UIViewAutoresizingFlexibleMargins #define UIViewAutoresizingFlexibleMargins (UIViewAutoresizingFlexibleLeftMargin \ | UIViewAutoresizingFlexibleTopMargin \ | UIViewAutoresizingFlexibleRightMargin \ | UIViewAutoresizingFlexibleBottomMargin) #endif #ifndef UIViewAutoresizingFlexibleDimensions #define UIViewAutoresizingFlexibleDimensions (UIViewAutoresizingFlexibleWidth \ | UIViewAutoresizingFlexibleHeight) #endif #ifndef UIViewAutoresizingNavigationBar #define UIViewAutoresizingNavigationBar (UIViewAutoresizingFlexibleWidth \ | UIViewAutoresizingFlexibleBottomMargin) #endif #ifndef UIViewAutoresizingToolbar #define UIViewAutoresizingToolbar (UIViewAutoresizingFlexibleWidth \ | UIViewAutoresizingFlexibleTopMargin) #endif /** * The recommended number of points for a minimum tappable area. * * Value: 44 */ CGFloat NIMinimumTapDimension(void); /** * Fetch the height of a toolbar in a given orientation. * * On the iPhone: * - Portrait: 44 * - Landscape: 33 * * On the iPad: always 44 */ CGFloat NIToolbarHeightForOrientation(UIInterfaceOrientation orientation); /** * The animation curve used when changing the status bar's visibility. * * This is the curve of the animation used by * <code>-[[UIApplication sharedApplication] setStatusBarHidden:withAnimation:].</code> * * Value: UIViewAnimationCurveEaseIn */ UIViewAnimationCurve NIStatusBarAnimationCurve(void); /** * The animation duration used when changing the status bar's visibility. * * This is the duration of the animation used by * <code>-[[UIApplication sharedApplication] setStatusBarHidden:withAnimation:].</code> * * Value: 0.3 seconds */ NSTimeInterval NIStatusBarAnimationDuration(void); /** * The animation curve used when the status bar's bounds change (when a call is received, * for example). * * Value: UIViewAnimationCurveEaseInOut */ UIViewAnimationCurve NIStatusBarBoundsChangeAnimationCurve(void); /** * The animation duration used when the status bar's bounds change (when a call is received, * for example). * * Value: 0.35 seconds */ NSTimeInterval NIStatusBarBoundsChangeAnimationDuration(void); /** * Get the status bar's current height. * * If the status bar is hidden this will return 0. * * This is generally 20 when the status bar is its normal height. */ CGFloat NIStatusBarHeight(void); /** * The animation duration when the device is rotating to a new orientation. * * Value: 0.4 seconds if the device is being rotated 90 degrees. * 0.8 seconds if the device is being rotated 180 degrees. * * @param isFlippingUpsideDown YES if the device is being flipped upside down. */ NSTimeInterval NIDeviceRotationDuration(BOOL isFlippingUpsideDown); /** * The padding around a standard cell in a table view. * * Value: 10 pixels on all sides. */ UIEdgeInsets NICellContentPadding(void); #if defined __cplusplus }; #endif /**@}*/// End of Common Metrics ///////////////////////////////////////////////////////////////////
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/core/src/NICommonMetrics.m
Objective-C
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NICommonMetrics.h" #import "NISDKAvailability.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "Nimbus requires ARC support." #endif CGFloat NIMinimumTapDimension(void) { return 44; } CGFloat NIToolbarHeightForOrientation(UIInterfaceOrientation orientation) { return (NIIsPad() ? 44 : (UIInterfaceOrientationIsPortrait(orientation) ? 44 : 33)); } UIViewAnimationCurve NIStatusBarAnimationCurve(void) { return UIViewAnimationCurveEaseIn; } NSTimeInterval NIStatusBarAnimationDuration(void) { return 0.3; } UIViewAnimationCurve NIStatusBarBoundsChangeAnimationCurve(void) { return UIViewAnimationCurveEaseInOut; } NSTimeInterval NIStatusBarBoundsChangeAnimationDuration(void) { return 0.35; } CGFloat NIStatusBarHeight(void) { CGRect statusBarFrame = [[UIApplication sharedApplication] statusBarFrame]; // We take advantage of the fact that the status bar will always be wider than it is tall // in order to avoid having to check the status bar orientation. CGFloat statusBarHeight = MIN(statusBarFrame.size.width, statusBarFrame.size.height); return statusBarHeight; } NSTimeInterval NIDeviceRotationDuration(BOOL isFlippingUpsideDown) { return isFlippingUpsideDown ? 0.8 : 0.4; } UIEdgeInsets NICellContentPadding(void) { return UIEdgeInsetsMake(10, 10, 10, 10); }
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/core/src/NIDataStructures.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <Foundation/Foundation.h> #import "NIPreprocessorMacros.h" /** * For classic computer science data structures. * * NILinkedList has been deprecated and will soon be removed altogether. Use NSMutableOrderedSet * instead. * * iOS provides most of the important data structures such as arrays, dictionaries, and sets. * However, it is missing some lesser-used data structures such as linked lists. Nimbus makes * use of the linked list data structure to provide an efficient, least-recently-used cache * removal policy for its in-memory cache, NIMemoryCache. * * * <h2>Comparison of Data Structures</h2> * *<pre> * Requirement | NILinkedList | NSArray | NSSet | NSDictionary * ===================================================================== * Instant arbitrary | YES | NO | YES | YES * insertion/deletion | [1] | | | * --------------------------------------------------------------------- * Consistent object | YES | YES | NO | NO * ordering | | | | * --------------------------------------------------------------------- * Checking for object | NO | NO | YES | NO * existence quickly | | | | * --------------------------------------------------------------------- * Instant object access | YES | NO | YES | YES * | [1] | | | [2] * ---------------------------------------------------------------------</pre> * * - [1] Note that being able to instantly remove and access objects in a NILinkedList * requires additional overhead of maintaining NILinkedListLocation objects in your * code. If this is your only requirement, then it's likely simpler to use an NSSet. * A linked list <i>is</i> worth using if you also need consistent ordering, seeing * as neither NSSet nor NSDictionary provide this. * - [2] This assumes you are accessing the object with its key. * * * <h2>Why NILinkedList was Built</h2> * * NILinkedList was built to solve a specific need in Nimbus' in-memory caches of having * a collection that guaranteed ordering, constant-time appending, and constant * time removal of arbitrary objects. * NSArray does not guarantee constant-time removal of objects, NSSet does not enforce ordering * (though the new NSOrderedSet introduced in iOS 5 does), and NSDictionary also does not * enforce ordering. * * * @ingroup NimbusCore * @defgroup Data-Structures Data Structures * @{ */ @class NILinkedListNode; __NI_DEPRECATED_METHOD // Use NSMutableOrderedSet instead. MAINTENANCE: Remove by Feb 28, 2014. @interface NILinkedListLocation : NSObject @end /** * A singly linked list implementation. * * This data structure provides constant time insertion and deletion of objects * in a collection. * * A linked list is different from an NSMutableArray solely in the runtime of adding and * removing objects. It is always possible to remove objects from both the beginning and end of * a linked list in constant time, contrasted with an NSMutableArray where removing an object * from the beginning of the list could result in O(N) linear time, where * N is the number of objects in the collection when the action is performed. * If an object's location is known, it is possible to get O(1) constant time removal * with a linked list, where an NSMutableArray would get at best O(N) linear time. * * This collection implements NSFastEnumeration which allows you to use foreach-style * iteration on the linked list. If you would like more control over the iteration of the * linked list you can use * <code>-[NILinkedList @link NILinkedList::objectEnumerator objectEnumerator@endlink]</code> * * * <h2>When You Should Use a Linked List</h2> * * Linked lists should be used when you need guaranteed constant-time performance characteristics * for adding arbitrary objects to and removing arbitrary objects from a collection that * also enforces consistent ordering. * * Linked lists are used in NIMemoryCache to implement an efficient, least-recently used * collection for in-memory caches. It is important that these caches use a collection with * guaranteed constant-time properties because in-memory caches must operate as fast as * possible in order to avoid locking up the UI. Specifically, in-memory caches could * potentially have thousands of objects. Every time we access one of these objects we move * its lru placement to the end of the lru list. If we were to use an NSArray for this data * structure we could easily run into an O(N^2) exponential-time operation which is * absolutely unacceptable. */ __NI_DEPRECATED_METHOD // Use NSMutableOrderedSet instead. MAINTENANCE: Remove by Feb 28, 2014. @interface NILinkedList : NSObject <NSCopying, NSCoding, NSFastEnumeration> - (NSUInteger)count; - (id)firstObject; - (id)lastObject; #pragma mark Linked List Creation + (NILinkedList *)linkedList; + (NILinkedList *)linkedListWithArray:(NSArray *)array; - (id)initWithArray:(NSArray *)anArray; #pragma mark Extended Methods - (NSArray *)allObjects; - (NSEnumerator *)objectEnumerator; - (BOOL)containsObject:(id)anObject; - (NSString *)description; #pragma mark Methods for constant-time access. - (NILinkedListLocation *)locationOfObject:(id)object; - (id)objectAtLocation:(NILinkedListLocation *)location; - (void)removeObjectAtLocation:(NILinkedListLocation *)location; #pragma mark Mutable Operations // TODO (jverkoey August 3, 2011): Consider creating an NIMutableLinkedList implementation. - (NILinkedListLocation *)addObject:(id)object; - (void)addObjectsFromArray:(NSArray *)array; - (void)removeAllObjects; - (void)removeObject:(id)object; - (void)removeFirstObject; - (void)removeLastObject; @end /**@}*/// End of Data Structures ////////////////////////////////////////////////////////////////// /** * @class NILinkedList * * <h2>Modifying a linked list</h2> * * To add an object to a linked list, you may use @link NILinkedList::addObject: addObject:@endlink. * * @code * [ll addObject:object]; * @endcode * * To remove some arbitrary object in linear time (meaning we must perform a scan of the list), use * @link NILinkedList::removeObject: removeObject:@endlink * * @code * [ll removeObject:object]; * @endcode * * Note that using a linked list in this way is way is identical to using an * NSMutableArray in performance time. * * * <h2>Accessing a Linked List</h2> * * You can access the first and last objects with constant time by using * @link NILinkedList::firstObject firstObject@endlink and * @link NILinkedList::lastObject lastObject@endlink. * * @code * id firstObject = ll.firstObject; * id lastObject = ll.lastObject; * @endcode * * * <h2>Traversing a Linked List</h2> * * NILinkedList implements the NSFastEnumeration protocol, allowing you to use foreach-style * iteration over the objects of a linked list. Note that you cannot modify a linked list * during fast iteration and doing so will fire an assertion. * * @code * for (id object in ll) { * // perform operations on the object * } * @endcode * * If you need to modify the linked list while traversing it, an acceptable algorithm is to * successively remove either the head or tail object, depending on the order in which you wish * to traverse the linked list. * * <h3>Traversing Forward by Removing Objects from the List</h3> * * @code * while (nil != ll.firstObject) { * id object = [ll firstObject]; * * // Remove the head of the linked list in constant time. * [ll removeFirstObject]; * } * @endcode * * <h3>Traversing Backward by Removing Objects from the List</h3> * * @code * while (nil != ll.lastObject) { * id object = [ll lastObject]; * * // Remove the tail of the linked list in constant time. * [ll removeLastObject]; * } * @endcode * * * <h2>Examples</h2> * * * <h3>Building a first-in-first-out list of operations</h3> * * @code * NILinkedList* ll = [NILinkedList linkedList]; * * // Add the operations to the linked list like you would an array. * [ll addObject:operation1]; * * // Each addObject call appends the object to the end of the linked list. * [ll addObject:operation2]; * * while (nil != ll.firstObject) { * NSOperation* op1 = [ll firstObject]; * // Process the operation... * * // Remove the head of the linked list in constant time. * [ll removeFirstObject]; * } * @endcode * * * <h3>Removing an item from the middle of the list</h3> * * @code * NILinkedList* ll = [NILinkedList linkedList]; * * [ll addObject:obj1]; * [ll addObject:obj2]; * [ll addObject:obj3]; * [ll addObject:obj4]; * * // Find an object in the linked list in linear time. * NILinkedListLocation* location = [ll locationOfObject:obj3]; * * // Remove the object in constant time. * [ll removeObjectAtLocation:location]; * * // Location is no longer valid at this point. * location = nil; * * // Remove an object in linear time. This is simply a more concise version of the above. * [ll removeObject:obj4]; * * // We would use the NILinkedListLocation to remove the object if we were storing the location * // in an external data structure and wanted constant time removal, for example. See * // NIMemoryCache for an example of this in action. * @endcode * * @sa NIMemoryCache * * * <h3>Using the location object for constant time operations</h3> * * @code * NILinkedList* ll = [NILinkedList linkedList]; * * [ll addObject:obj1]; * NILinkedListLocation* location = [ll addObject:obj2]; * [ll addObject:obj3]; * [ll addObject:obj4]; * * // Remove the second object in constant time. * [ll removeObjectAtLocation:location]; * * // Location is no longer valid at this point. * location = nil; * @endcode */ /** @name Creating a Linked List */ /** * Returns a newly allocated and autoreleased linked list. * * Identical to [[[NILinkedList alloc] init] autorelease]; * * @fn NILinkedList::linkedList */ /** * Returns a newly allocated and autoreleased linked list filled with the objects from an array. * * Identical to [[[NILinkedList alloc] initWithArray:array] autorelease]; * * @fn NILinkedList::linkedListWithArray: */ /** * Initializes a newly allocated linked list by placing in it the objects contained * in a given array. * * @fn NILinkedList::initWithArray: * @param anArray An array. * @returns A linked list initialized to contain the objects in anArray. */ /** @name Querying a Linked List */ /** * Returns the number of objects currently in the linked list. * * @fn NILinkedList::count * @returns The number of objects currently in the linked list. */ /** * Returns the first object in the linked list. * * @fn NILinkedList::firstObject * @returns The first object in the linked list. If the linked list is empty, returns nil. */ /** * Returns the last object in the linked list. * * @fn NILinkedList::lastObject * @returns The last object in the linked list. If the linked list is empty, returns nil. */ /** * Returns an array containing the linked list's objects, or an empty array if the linked list * has no objects. * * @fn NILinkedList::allObjects * @returns An array containing the linked list's objects, or an empty array if the linked * list has no objects. The objects will be in the same order as the linked list. */ /** * Returns an enumerator object that lets you access each object in the linked list. * * @fn NILinkedList::objectEnumerator * @returns An enumerator object that lets you access each object in the linked list, in * order, from the first object to the last. * @attention When you use this method you must not modify the linked list during enumeration. */ /** * Returns a Boolean value that indicates whether a given object is present in the linked list. * * Run-time: O(count) linear * * @fn NILinkedList::containsObject: * @returns YES if anObject is present in the linked list, otherwise NO. */ /** * Returns a string that represents the contents of the linked list, formatted as a property list. * * @fn NILinkedList::description * @returns A string that represents the contents of the linked list, * formatted as a property list. */ /** @name Adding Objects */ /** * Appends an object to the linked list. * * Run-time: O(1) constant * * @fn NILinkedList::addObject: * @returns A location within the linked list. */ /** * Appends an array of objects to the linked list. * * Run-time: O(l) linear with the length of the given array * * @fn NILinkedList::addObjectsFromArray: */ /** @name Removing Objects */ /** * Removes all objects from the linked list. * * Run-time: Theta(count) linear * * @fn NILinkedList::removeAllObjects */ /** * Removes an object from the linked list. * * Run-time: O(count) linear * * @fn NILinkedList::removeObject: */ /** * Removes the first object from the linked list. * * Run-time: O(1) constant * * @fn NILinkedList::removeFirstObject */ /** * Removes the last object from the linked list. * * Run-time: O(1) constant * * @fn NILinkedList::removeLastObject */ /** @name Constant-Time Access */ /** * Searches for an object in the linked list. * * The NILinkedListLocation object will remain valid as long as the object is still in the * linked list. Once the object is removed from the linked list, however, the location object * is released from memory and should no longer be used. * * TODO (jverkoey July 1, 2011): Consider creating a wrapper object for the location so that * we can deal with incorrect usage more safely. * * Run-time: O(count) linear * * @fn NILinkedList::locationOfObject: * @returns A location within the linked list. */ /** * Retrieves the object at a specific location. * * Run-time: O(1) constant * * @fn NILinkedList::objectAtLocation: */ /** * Removes an object at a predetermined location. * * It is assumed that this location still exists in the linked list. If the object this * location refers to has since been removed then this method will have undefined results. * * This is provided as an optimization over the O(n) removal method but should be used with care. * * Run-time: O(1) constant * * @fn NILinkedList::removeObjectAtLocation: */
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/core/src/NIDataStructures.m
Objective-C
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NIDataStructures.h" #import "NIDebuggingTools.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "Nimbus requires ARC support." #endif // The internal representation of a single node. @interface NILinkedListNode : NSObject @property (nonatomic, strong) id object; @property (nonatomic, strong) NILinkedListNode* prev; @property (nonatomic, strong) NILinkedListNode* next; @end @implementation NILinkedListNode @end @interface NILinkedListLocation() + (id)locationWithNode:(NILinkedListNode *)node; - (id)initWithNode:(NILinkedListNode *)node; @property (nonatomic, weak) NILinkedListNode* node; @end @implementation NILinkedListLocation + (id)locationWithNode:(NILinkedListNode *)node { return [[self alloc] initWithNode:node]; } - (id)initWithNode:(NILinkedListNode *)node { if ((self = [super init])) { _node = node; } return self; } - (BOOL)isEqual:(id)object { return ([object isKindOfClass:[NILinkedListLocation class]] && [object node] == self.node); } @end @interface NILinkedList() // Exposed so that the linked list enumerator can iterate over the nodes directly. @property (nonatomic, readonly, strong) NILinkedListNode* head; @property (nonatomic, readonly, strong) NILinkedListNode* tail; @property (nonatomic) NSUInteger count; @property (nonatomic) unsigned long modificationNumber; @end /** * @internal * * A implementation of NSEnumerator for NILinkedList. * * This class simply implements the nextObject NSEnumerator method and traverses a linked list. * The linked list is retained when this enumerator is created and released once the enumerator * is either released or deallocated. */ @interface NILinkedListEnumerator : NSEnumerator { @private NILinkedList* _ll; NILinkedListNode* _iterator; } /** * Designated initializer. Retains the linked list. */ - (id)initWithLinkedList:(NILinkedList *)ll; @end @implementation NILinkedListEnumerator - (void)dealloc { _iterator = nil; } - (id)initWithLinkedList:(NILinkedList *)ll { if ((self = [super init])) { _ll = ll; _iterator = ll.head; } return self; } - (id)nextObject { id object = nil; // Iteration step. if (nil != _iterator) { object = _iterator.object; _iterator = _iterator.next; // Completion step. } else { // As per the guidelines in the Objective-C docs for enumerators, we release the linked // list when we are finished enumerating. _ll = nil; // We don't have to set _iterator to nil here because is already is. } return object; } @end #pragma mark - @implementation NILinkedList - (void)dealloc { [self removeAllObjects]; } #pragma mark - Linked List Creation + (NILinkedList *)linkedList { return [[[self class] alloc] init]; } + (NILinkedList *)linkedListWithArray:(NSArray *)array { return [[[self class] alloc] initWithArray:array]; } - (id)initWithArray:(NSArray *)anArray { if ((self = [self init])) { for (id object in anArray) { [self addObject:object]; } } return self; } #pragma mark - Private - (void)_setCount:(NSUInteger)count { _count = count; } - (void)_removeNode:(NILinkedListNode *)node { if (nil == node) { return; } if (nil != node.prev) { node.prev.next = node.next; } else { _head = node.next; } if (nil != node.next) { node.next.prev = node.prev; } else { _tail = node.prev; } node.next = nil; node.prev = nil; --_count; ++_modificationNumber; } #pragma mark - NSCopying - (id)copyWithZone:(NSZone *)zone { NILinkedList* copy = [[[self class] allocWithZone:zone] init]; NILinkedListNode* node = _head; while (0 != node) { [copy addObject:node.object]; node = node.next; } copy.count = self.count; return copy; } #pragma mark - NSCoding - (void)encodeWithCoder:(NSCoder *)coder { [coder encodeValueOfObjCType:@encode(NSUInteger) at:&_count]; NILinkedListNode* node = _head; while (0 != node) { [coder encodeObject:node.object]; node = node.next; } } - (id)initWithCoder:(NSCoder *)decoder { if ((self = [super init])) { // We'll let addObject modify the count, so create a local count here so that we don't // double count every object. NSUInteger count = 0; [decoder decodeValueOfObjCType:@encode(NSUInteger) at:&count]; for (NSUInteger ix = 0; ix < count; ++ix) { id object = [decoder decodeObject]; [self addObject:object]; } // Sanity check. NIDASSERT(count == self.count); } return self; } #pragma mark - NSFastEnumeration - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(__unsafe_unretained id *)stackbuf count:(NSUInteger)len { // Initialization condition. if (0 == state->state) { // Whenever the linked list is modified, the modification number increases. This allows // enumeration to bail out if the linked list is modified mid-flight. state->mutationsPtr = &_modificationNumber; } NSUInteger numberOfItemsReturned = 0; // If there is no _tail (i.e. this is an empty list) then this will end immediately. if ((void *)state->state != (__bridge void *)_tail) { state->itemsPtr = stackbuf; if (0 == state->state) { // Initialize the state here instead of above when we check 0 == state.state because // for single item linked lists head == tail. If we initialized it in the initialization // condition, state.state != _tail check would fail and we wouldn't return the single // object. state->state = (unsigned long)_head; } // Return *at most* the number of request objects. while ((0 != state->state) && (numberOfItemsReturned < len)) { NILinkedListNode* node = (__bridge NILinkedListNode *)(void *)state->state; stackbuf[numberOfItemsReturned] = node.object; state->state = (unsigned long)node.next; ++numberOfItemsReturned; } if (0 == state->state) { // Final step condition. We allow the above loop to overstep the end one iteration, // because we rewind it one step here (to ensure that the next time enumeration occurs, // state == _tail. state->state = (unsigned long)_tail; } } // else we've returned all of the items that we can; leave numberOfItemsReturned as 0 to // signal that there is nothing left to be done. return numberOfItemsReturned; } #pragma mark - Public - (id)firstObject { return (nil != _head) ? _head.object : nil; } - (id)lastObject { return (nil != _tail) ? _tail.object : nil; } #pragma mark - Extended Methods - (NSArray *)allObjects { NSMutableArray* mutableArrayOfObjects = [[NSMutableArray alloc] initWithCapacity:self.count]; for (id object in self) { [mutableArrayOfObjects addObject:object]; } return [mutableArrayOfObjects copy]; } - (BOOL)containsObject:(id)anObject { for (id object in self) { if (object == anObject) { return YES; } } return NO; } - (NSString *)description { // In general we should try to avoid cheating by using allObjects for memory performance reasons, // but the description method is complex enough that it's not worth reinventing the wheel here. return [[self allObjects] description]; } - (id)objectAtLocation:(NILinkedListLocation *)location { return location.node.object; } - (NSEnumerator *)objectEnumerator { return [[NILinkedListEnumerator alloc] initWithLinkedList:self]; } - (NILinkedListLocation *)locationOfObject:(id)object { NILinkedListNode* node = _head; while (0 != node) { if (node.object == object) { return [NILinkedListLocation locationWithNode:node]; } node = node.next; } return 0; } - (void)removeObjectAtLocation:(NILinkedListLocation *)location { if (nil == location) { return; } [self _removeNode:location.node]; } - (NILinkedListLocation *)addObject:(id)object { // nil objects can not be added to a linked list. NIDASSERT(nil != object); if (nil == object) { return nil; } NILinkedListNode* node = [[NILinkedListNode alloc] init]; node.object = object; // Empty condition. if (nil == _tail) { _head = node; _tail = node; } else { // Non-empty condition. _tail.next = node; node.prev = _tail; _tail = node; } ++self.count; ++_modificationNumber; return [NILinkedListLocation locationWithNode:node]; } - (void)addObjectsFromArray:(NSArray *)array { for (id object in array) { [self addObject:object]; } } #pragma mark - Mutable Methods - (void)removeAllObjects { NILinkedListNode* node = _head; while (nil != node) { NILinkedListNode* next = node.next; node.prev = nil; node.next = nil; node = next; } _head = nil; _tail = nil; self.count = 0; ++_modificationNumber; } - (void)removeObject:(id)object { NILinkedListLocation* location = [self locationOfObject:object]; if (0 != location) { [self removeObjectAtLocation:location]; } } - (void)removeFirstObject { [self _removeNode:_head]; } - (void)removeLastObject { [self _removeNode:_tail]; } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/core/src/NIDebuggingTools.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Forked from Three20 June 10, 2011 - Copyright 2009-2011 Facebook // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <Foundation/Foundation.h> /** * For inspecting code and writing to logs in debug builds. * * Nearly all of the following macros will only do anything if the DEBUG macro is defined. * The recommended way to enable the debug tools is to specify DEBUG in the "Preprocessor Macros" * field in your application's Debug target settings. Be careful not to set this for your release * or app store builds because this will enable code that may cause your app to be rejected. * * * <h2>Debug Assertions</h2> * * Debug assertions are a lightweight "sanity check". They won't crash the app, nor will they * be included in release builds. They <i>will</i> halt the app's execution when debugging so * that you can inspect the values that caused the failure. * * @code * NIDASSERT(statement); * @endcode * * If <i>statement</i> is false, the statement will be written to the log and if a debugger is * attached, the app will break on the assertion line. * * * <h2>Debug Logging</h2> * * @code * NIDPRINT(@"formatted log text %d", param1); * @endcode * * Print the given formatted text to the log. * * @code * NIDPRINTMETHODNAME(); * @endcode * * Print the current method name to the log. * * @code * NIDCONDITIONLOG(statement, @"formatted log text %d", param1); * @endcode * * If statement is true, then the formatted text will be written to the log. * * @code * NIDINFO/NIDWARNING/NIDERROR(@"formatted log text %d", param1); * @endcode * * Will only write the formatted text to the log if NIMaxLogLevel is greater than the respective * NID* method's log level. See below for log levels. * * The default maximum log level is NILOGLEVEL_WARNING. * * <h3>Turning up the log level while the app is running</h3> * * NIMaxLogLevel is declared a non-const extern so that you can modify it at runtime. This can * be helpful for turning logging on while the application is running. * * @code * NIMaxLogLevel = NILOGLEVEL_INFO; * @endcode * * @ingroup NimbusCore * @defgroup Debugging-Tools Debugging Tools * @{ */ #if defined(DEBUG) || defined(NI_DEBUG) /** * Assertions that only fire when DEBUG is defined. * * An assertion is like a programmatic breakpoint. Use it for sanity checks to save headache while * writing your code. */ #import <TargetConditionals.h> #if defined __cplusplus extern "C" { #endif int NIIsInDebugger(void); #if defined __cplusplus } #endif #if TARGET_IPHONE_SIMULATOR // We leave the __asm__ in this macro so that when a break occurs, we don't have to step out of // a "breakInDebugger" function. #define NIDASSERT(xx) { if (!(xx)) { NIDPRINT(@"NIDASSERT failed: %s", #xx); \ if (NIDebugAssertionsShouldBreak && NIIsInDebugger()) { __asm__("int $3\n" : : ); } } \ } ((void)0) #else #define NIDASSERT(xx) { if (!(xx)) { NIDPRINT(@"NIDASSERT failed: %s", #xx); \ if (NIDebugAssertionsShouldBreak && NIIsInDebugger()) { raise(SIGTRAP); } } \ } ((void)0) #endif // #if TARGET_IPHONE_SIMULATOR #else #define NIDASSERT(xx) ((void)0) #endif // #if defined(DEBUG) || defined(NI_DEBUG) #define NILOGLEVEL_INFO 5 #define NILOGLEVEL_WARNING 3 #define NILOGLEVEL_ERROR 1 /** * The maximum log level to output for Nimbus debug logs. * * This value may be changed at run-time. * * The default value is NILOGLEVEL_WARNING. */ extern NSInteger NIMaxLogLevel; /** * Whether or not debug assertions should halt program execution like a breakpoint when they fail. * * An example of when this is used is in unit tests, when failure cases are tested that will * fire debug assertions. * * The default value is YES. */ extern BOOL NIDebugAssertionsShouldBreak; /** * Only writes to the log when DEBUG is defined. * * This log method will always write to the log, regardless of log levels. It is used by all * of the other logging methods in Nimbus' debugging library. */ #if defined(DEBUG) || defined(NI_DEBUG) #define NIDPRINT(xx, ...) NSLog(@"%s(%d): " xx, __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__) #else #define NIDPRINT(xx, ...) ((void)0) #endif // #if defined(DEBUG) || defined(NI_DEBUG) /** * Write the containing method's name to the log using NIDPRINT. */ #define NIDPRINTMETHODNAME() NIDPRINT(@"%s", __PRETTY_FUNCTION__) #if defined(DEBUG) || defined(NI_DEBUG) /** * Only writes to the log if condition is satisified. * * This macro powers the level-based loggers. It can also be used for conditionally enabling * families of logs. */ #define NIDCONDITIONLOG(condition, xx, ...) { if ((condition)) { NIDPRINT(xx, ##__VA_ARGS__); } \ } ((void)0) #else #define NIDCONDITIONLOG(condition, xx, ...) ((void)0) #endif // #if defined(DEBUG) || defined(NI_DEBUG) /** * Only writes to the log if NIMaxLogLevel >= NILOGLEVEL_ERROR. */ #define NIDERROR(xx, ...) NIDCONDITIONLOG((NILOGLEVEL_ERROR <= NIMaxLogLevel), xx, ##__VA_ARGS__) /** * Only writes to the log if NIMaxLogLevel >= NILOGLEVEL_WARNING. */ #define NIDWARNING(xx, ...) NIDCONDITIONLOG((NILOGLEVEL_WARNING <= NIMaxLogLevel), \ xx, ##__VA_ARGS__) /** * Only writes to the log if NIMaxLogLevel >= NILOGLEVEL_INFO. */ #define NIDINFO(xx, ...) NIDCONDITIONLOG((NILOGLEVEL_INFO <= NIMaxLogLevel), xx, ##__VA_ARGS__) /**@}*/// End of Debugging Tools //////////////////////////////////////////////////////////////////
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/core/src/NIDebuggingTools.m
Objective-C
// // Copyright 2011-2014 NimbusKit // Copyright 2009-2011 Facebook // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NIDebuggingTools.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "Nimbus requires ARC support." #endif NSInteger NIMaxLogLevel = NILOGLEVEL_WARNING; BOOL NIDebugAssertionsShouldBreak = YES; #if defined(DEBUG) || defined(NI_DEBUG) #import <unistd.h> #import <sys/sysctl.h> // From: http://developer.apple.com/mac/library/qa/qa2004/qa1361.html int NIIsInDebugger(void) { int mib[4]; struct kinfo_proc info; size_t size; // Initialize the flags so that, if sysctl fails for some bizarre // reason, we get a predictable result. info.kp_proc.p_flag = 0; // Initialize mib, which tells sysctl the info we want, in this case // we're looking for information about a specific process ID. mib[0] = CTL_KERN; mib[1] = KERN_PROC; mib[2] = KERN_PROC_PID; mib[3] = getpid(); // Call sysctl. size = sizeof(info); sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, NULL, 0); // We're being debugged if the P_TRACED flag is set. return (info.kp_proc.p_flag & P_TRACED) != 0; } #endif // #if defined(DEBUG) || defined(NI_DEBUG)
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/core/src/NIDeviceOrientation.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Forked from Three20 June 10, 2011 - Copyright 2009-2011 Facebook // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #if defined __cplusplus extern "C" { #endif /** * For dealing with device orientations. * * <h2>Examples</h2> * * <h3>Use NIIsSupportedOrientation to Enable Autorotation</h3> * * @code * - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation { * return NIIsSupportedOrientation(toInterfaceOrientation); * } * @endcode * * @ingroup NimbusCore * @defgroup Device-Orientation Device Orientation * @{ */ /** * For use in shouldAutorotateToInterfaceOrientation: * * On iPhone/iPod touch: * * Returns YES if the orientation is portrait, landscape left, or landscape right. * This helps to ignore upside down and flat orientations. * * On iPad: * * Always returns YES. */ BOOL NIIsSupportedOrientation(UIInterfaceOrientation orientation); /** * Returns the application's current interface orientation. * * This is simply a convenience method for [UIApplication sharedApplication].statusBarOrientation. * * @returns The current interface orientation. */ UIInterfaceOrientation NIInterfaceOrientation(void); /** * Returns YES if the device is a phone and the orientation is landscape. * * This is a useful check for phone landscape mode which often requires * additional logic to handle the smaller vertical real estate. * * @returns YES if the device is a phone and orientation is landscape. */ BOOL NIIsLandscapePhoneOrientation(UIInterfaceOrientation orientation); /** * Creates an affine transform for the given device orientation. * * This is useful for creating a transformation matrix for a view that has been added * directly to the window and doesn't automatically have its transformation modified. */ CGAffineTransform NIRotateTransformForOrientation(UIInterfaceOrientation orientation); #if defined __cplusplus }; #endif /**@}*/// End of Device Orientation ///////////////////////////////////////////////////////////////
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/core/src/NIDeviceOrientation.m
Objective-C
// // Copyright 2011-2014 NimbusKit // // Forked from Three20 June 10, 2011 - Copyright 2009-2011 Facebook // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NIDeviceOrientation.h" #import <QuartzCore/QuartzCore.h> #import "NIDebuggingTools.h" #import "NISDKAvailability.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "Nimbus requires ARC support." #endif BOOL NIIsSupportedOrientation(UIInterfaceOrientation orientation) { if (NIIsPad()) { return YES; } else { switch (orientation) { case UIInterfaceOrientationPortrait: case UIInterfaceOrientationLandscapeLeft: case UIInterfaceOrientationLandscapeRight: return YES; default: return NO; } } } UIInterfaceOrientation NIInterfaceOrientation(void) { UIInterfaceOrientation orient = [UIApplication sharedApplication].statusBarOrientation; // This code used to use the Three20 navigator to find the currently visible view controller and // fall back to checking its orientation if we didn't know the status bar's orientation. // It's unclear when this was actually necessary, though, so this assertion is here to try // to find that case. If this assertion fails then the repro case needs to be analyzed and // this method made more robust to handle that case. NIDASSERT(UIDeviceOrientationUnknown != orient); return orient; } BOOL NIIsLandscapePhoneOrientation(UIInterfaceOrientation orientation) { return NIIsPhone() && UIInterfaceOrientationIsLandscape(orientation); } CGAffineTransform NIRotateTransformForOrientation(UIInterfaceOrientation orientation) { if (orientation == UIInterfaceOrientationLandscapeLeft) { return CGAffineTransformMakeRotation((CGFloat)(M_PI * 1.5)); } else if (orientation == UIInterfaceOrientationLandscapeRight) { return CGAffineTransformMakeRotation((CGFloat)(M_PI / 2.0)); } else if (orientation == UIInterfaceOrientationPortraitUpsideDown) { return CGAffineTransformMakeRotation((CGFloat)(-M_PI)); } else { return CGAffineTransformIdentity; } }
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay