diff --git a/CustomKeyboard/Masonry/LICENSE b/CustomKeyboard/Masonry/LICENSE new file mode 100755 index 0000000..a843c00 --- /dev/null +++ b/CustomKeyboard/Masonry/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2011-2012 Masonry Team - https://github.com/Masonry + +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. \ No newline at end of file diff --git a/CustomKeyboard/Masonry/Masonry/MASCompositeConstraint.h b/CustomKeyboard/Masonry/Masonry/MASCompositeConstraint.h new file mode 100755 index 0000000..934c6f1 --- /dev/null +++ b/CustomKeyboard/Masonry/Masonry/MASCompositeConstraint.h @@ -0,0 +1,26 @@ +// +// MASCompositeConstraint.h +// Masonry +// +// Created by Jonas Budelmann on 21/07/13. +// Copyright (c) 2013 cloudling. All rights reserved. +// + +#import "MASConstraint.h" +#import "MASUtilities.h" + +/** + * A group of MASConstraint objects + */ +@interface MASCompositeConstraint : MASConstraint + +/** + * Creates a composite with a predefined array of children + * + * @param children child MASConstraints + * + * @return a composite constraint + */ +- (id)initWithChildren:(NSArray *)children; + +@end diff --git a/CustomKeyboard/Masonry/Masonry/MASCompositeConstraint.m b/CustomKeyboard/Masonry/Masonry/MASCompositeConstraint.m new file mode 100755 index 0000000..2002a40 --- /dev/null +++ b/CustomKeyboard/Masonry/Masonry/MASCompositeConstraint.m @@ -0,0 +1,183 @@ +// +// MASCompositeConstraint.m +// Masonry +// +// Created by Jonas Budelmann on 21/07/13. +// Copyright (c) 2013 cloudling. All rights reserved. +// + +#import "MASCompositeConstraint.h" +#import "MASConstraint+Private.h" + +@interface MASCompositeConstraint () + +@property (nonatomic, strong) id mas_key; +@property (nonatomic, strong) NSMutableArray *childConstraints; + +@end + +@implementation MASCompositeConstraint + +- (id)initWithChildren:(NSArray *)children { + self = [super init]; + if (!self) return nil; + + _childConstraints = [children mutableCopy]; + for (MASConstraint *constraint in _childConstraints) { + constraint.delegate = self; + } + + return self; +} + +#pragma mark - MASConstraintDelegate + +- (void)constraint:(MASConstraint *)constraint shouldBeReplacedWithConstraint:(MASConstraint *)replacementConstraint { + NSUInteger index = [self.childConstraints indexOfObject:constraint]; + NSAssert(index != NSNotFound, @"Could not find constraint %@", constraint); + [self.childConstraints replaceObjectAtIndex:index withObject:replacementConstraint]; +} + +- (MASConstraint *)constraint:(MASConstraint __unused *)constraint addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute { + id strongDelegate = self.delegate; + MASConstraint *newConstraint = [strongDelegate constraint:self addConstraintWithLayoutAttribute:layoutAttribute]; + newConstraint.delegate = self; + [self.childConstraints addObject:newConstraint]; + return newConstraint; +} + +#pragma mark - NSLayoutConstraint multiplier proxies + +- (MASConstraint * (^)(CGFloat))multipliedBy { + return ^id(CGFloat multiplier) { + for (MASConstraint *constraint in self.childConstraints) { + constraint.multipliedBy(multiplier); + } + return self; + }; +} + +- (MASConstraint * (^)(CGFloat))dividedBy { + return ^id(CGFloat divider) { + for (MASConstraint *constraint in self.childConstraints) { + constraint.dividedBy(divider); + } + return self; + }; +} + +#pragma mark - MASLayoutPriority proxy + +- (MASConstraint * (^)(MASLayoutPriority))priority { + return ^id(MASLayoutPriority priority) { + for (MASConstraint *constraint in self.childConstraints) { + constraint.priority(priority); + } + return self; + }; +} + +#pragma mark - NSLayoutRelation proxy + +- (MASConstraint * (^)(id, NSLayoutRelation))equalToWithRelation { + return ^id(id attr, NSLayoutRelation relation) { + for (MASConstraint *constraint in self.childConstraints.copy) { + constraint.equalToWithRelation(attr, relation); + } + return self; + }; +} + +#pragma mark - attribute chaining + +- (MASConstraint *)addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute { + [self constraint:self addConstraintWithLayoutAttribute:layoutAttribute]; + return self; +} + +#pragma mark - Animator proxy + +#if TARGET_OS_MAC && !(TARGET_OS_IPHONE || TARGET_OS_TV) + +- (MASConstraint *)animator { + for (MASConstraint *constraint in self.childConstraints) { + [constraint animator]; + } + return self; +} + +#endif + +#pragma mark - debug helpers + +- (MASConstraint * (^)(id))key { + return ^id(id key) { + self.mas_key = key; + int i = 0; + for (MASConstraint *constraint in self.childConstraints) { + constraint.key([NSString stringWithFormat:@"%@[%d]", key, i++]); + } + return self; + }; +} + +#pragma mark - NSLayoutConstraint constant setters + +- (void)setInsets:(MASEdgeInsets)insets { + for (MASConstraint *constraint in self.childConstraints) { + constraint.insets = insets; + } +} + +- (void)setInset:(CGFloat)inset { + for (MASConstraint *constraint in self.childConstraints) { + constraint.inset = inset; + } +} + +- (void)setOffset:(CGFloat)offset { + for (MASConstraint *constraint in self.childConstraints) { + constraint.offset = offset; + } +} + +- (void)setSizeOffset:(CGSize)sizeOffset { + for (MASConstraint *constraint in self.childConstraints) { + constraint.sizeOffset = sizeOffset; + } +} + +- (void)setCenterOffset:(CGPoint)centerOffset { + for (MASConstraint *constraint in self.childConstraints) { + constraint.centerOffset = centerOffset; + } +} + +#pragma mark - MASConstraint + +- (void)activate { + for (MASConstraint *constraint in self.childConstraints) { + [constraint activate]; + } +} + +- (void)deactivate { + for (MASConstraint *constraint in self.childConstraints) { + [constraint deactivate]; + } +} + +- (void)install { + for (MASConstraint *constraint in self.childConstraints) { + constraint.updateExisting = self.updateExisting; + [constraint install]; + } +} + +- (void)uninstall { + for (MASConstraint *constraint in self.childConstraints) { + [constraint uninstall]; + } +} + +@end diff --git a/CustomKeyboard/Masonry/Masonry/MASConstraint+Private.h b/CustomKeyboard/Masonry/Masonry/MASConstraint+Private.h new file mode 100755 index 0000000..ee0fd96 --- /dev/null +++ b/CustomKeyboard/Masonry/Masonry/MASConstraint+Private.h @@ -0,0 +1,66 @@ +// +// MASConstraint+Private.h +// Masonry +// +// Created by Nick Tymchenko on 29/04/14. +// Copyright (c) 2014 cloudling. All rights reserved. +// + +#import "MASConstraint.h" + +@protocol MASConstraintDelegate; + + +@interface MASConstraint () + +/** + * Whether or not to check for an existing constraint instead of adding constraint + */ +@property (nonatomic, assign) BOOL updateExisting; + +/** + * Usually MASConstraintMaker but could be a parent MASConstraint + */ +@property (nonatomic, weak) id delegate; + +/** + * Based on a provided value type, is equal to calling: + * NSNumber - setOffset: + * NSValue with CGPoint - setPointOffset: + * NSValue with CGSize - setSizeOffset: + * NSValue with MASEdgeInsets - setInsets: + */ +- (void)setLayoutConstantWithValue:(NSValue *)value; + +@end + + +@interface MASConstraint (Abstract) + +/** + * Sets the constraint relation to given NSLayoutRelation + * returns a block which accepts one of the following: + * MASViewAttribute, UIView, NSValue, NSArray + * see readme for more details. + */ +- (MASConstraint * (^)(id, NSLayoutRelation))equalToWithRelation; + +/** + * Override to set a custom chaining behaviour + */ +- (MASConstraint *)addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute; + +@end + + +@protocol MASConstraintDelegate + +/** + * Notifies the delegate when the constraint needs to be replaced with another constraint. For example + * A MASViewConstraint may turn into a MASCompositeConstraint when an array is passed to one of the equality blocks + */ +- (void)constraint:(MASConstraint *)constraint shouldBeReplacedWithConstraint:(MASConstraint *)replacementConstraint; + +- (MASConstraint *)constraint:(MASConstraint *)constraint addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute; + +@end diff --git a/CustomKeyboard/Masonry/Masonry/MASConstraint.h b/CustomKeyboard/Masonry/Masonry/MASConstraint.h new file mode 100755 index 0000000..3eaa8a1 --- /dev/null +++ b/CustomKeyboard/Masonry/Masonry/MASConstraint.h @@ -0,0 +1,272 @@ +// +// MASConstraint.h +// Masonry +// +// Created by Jonas Budelmann on 22/07/13. +// Copyright (c) 2013 cloudling. All rights reserved. +// + +#import "MASUtilities.h" + +/** + * Enables Constraints to be created with chainable syntax + * Constraint can represent single NSLayoutConstraint (MASViewConstraint) + * or a group of NSLayoutConstraints (MASComposisteConstraint) + */ +@interface MASConstraint : NSObject + +// Chaining Support + +/** + * Modifies the NSLayoutConstraint constant, + * only affects MASConstraints in which the first item's NSLayoutAttribute is one of the following + * NSLayoutAttributeTop, NSLayoutAttributeLeft, NSLayoutAttributeBottom, NSLayoutAttributeRight + */ +- (MASConstraint * (^)(MASEdgeInsets insets))insets; + +/** + * Modifies the NSLayoutConstraint constant, + * only affects MASConstraints in which the first item's NSLayoutAttribute is one of the following + * NSLayoutAttributeTop, NSLayoutAttributeLeft, NSLayoutAttributeBottom, NSLayoutAttributeRight + */ +- (MASConstraint * (^)(CGFloat inset))inset; + +/** + * Modifies the NSLayoutConstraint constant, + * only affects MASConstraints in which the first item's NSLayoutAttribute is one of the following + * NSLayoutAttributeWidth, NSLayoutAttributeHeight + */ +- (MASConstraint * (^)(CGSize offset))sizeOffset; + +/** + * Modifies the NSLayoutConstraint constant, + * only affects MASConstraints in which the first item's NSLayoutAttribute is one of the following + * NSLayoutAttributeCenterX, NSLayoutAttributeCenterY + */ +- (MASConstraint * (^)(CGPoint offset))centerOffset; + +/** + * Modifies the NSLayoutConstraint constant + */ +- (MASConstraint * (^)(CGFloat offset))offset; + +/** + * Modifies the NSLayoutConstraint constant based on a value type + */ +- (MASConstraint * (^)(NSValue *value))valueOffset; + +/** + * Sets the NSLayoutConstraint multiplier property + */ +- (MASConstraint * (^)(CGFloat multiplier))multipliedBy; + +/** + * Sets the NSLayoutConstraint multiplier to 1.0/dividedBy + */ +- (MASConstraint * (^)(CGFloat divider))dividedBy; + +/** + * Sets the NSLayoutConstraint priority to a float or MASLayoutPriority + */ +- (MASConstraint * (^)(MASLayoutPriority priority))priority; + +/** + * Sets the NSLayoutConstraint priority to MASLayoutPriorityLow + */ +- (MASConstraint * (^)(void))priorityLow; + +/** + * Sets the NSLayoutConstraint priority to MASLayoutPriorityMedium + */ +- (MASConstraint * (^)(void))priorityMedium; + +/** + * Sets the NSLayoutConstraint priority to MASLayoutPriorityHigh + */ +- (MASConstraint * (^)(void))priorityHigh; + +/** + * Sets the constraint relation to NSLayoutRelationEqual + * returns a block which accepts one of the following: + * MASViewAttribute, UIView, NSValue, NSArray + * see readme for more details. + */ +- (MASConstraint * (^)(id attr))equalTo; + +/** + * Sets the constraint relation to NSLayoutRelationGreaterThanOrEqual + * returns a block which accepts one of the following: + * MASViewAttribute, UIView, NSValue, NSArray + * see readme for more details. + */ +- (MASConstraint * (^)(id attr))greaterThanOrEqualTo; + +/** + * Sets the constraint relation to NSLayoutRelationLessThanOrEqual + * returns a block which accepts one of the following: + * MASViewAttribute, UIView, NSValue, NSArray + * see readme for more details. + */ +- (MASConstraint * (^)(id attr))lessThanOrEqualTo; + +/** + * Optional semantic property which has no effect but improves the readability of constraint + */ +- (MASConstraint *)with; + +/** + * Optional semantic property which has no effect but improves the readability of constraint + */ +- (MASConstraint *)and; + +/** + * Creates a new MASCompositeConstraint with the called attribute and reciever + */ +- (MASConstraint *)left; +- (MASConstraint *)top; +- (MASConstraint *)right; +- (MASConstraint *)bottom; +- (MASConstraint *)leading; +- (MASConstraint *)trailing; +- (MASConstraint *)width; +- (MASConstraint *)height; +- (MASConstraint *)centerX; +- (MASConstraint *)centerY; +- (MASConstraint *)baseline; + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + +- (MASConstraint *)firstBaseline; +- (MASConstraint *)lastBaseline; + +#endif + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) + +- (MASConstraint *)leftMargin; +- (MASConstraint *)rightMargin; +- (MASConstraint *)topMargin; +- (MASConstraint *)bottomMargin; +- (MASConstraint *)leadingMargin; +- (MASConstraint *)trailingMargin; +- (MASConstraint *)centerXWithinMargins; +- (MASConstraint *)centerYWithinMargins; + +#endif + + +/** + * Sets the constraint debug name + */ +- (MASConstraint * (^)(id key))key; + +// NSLayoutConstraint constant Setters +// for use outside of mas_updateConstraints/mas_makeConstraints blocks + +/** + * Modifies the NSLayoutConstraint constant, + * only affects MASConstraints in which the first item's NSLayoutAttribute is one of the following + * NSLayoutAttributeTop, NSLayoutAttributeLeft, NSLayoutAttributeBottom, NSLayoutAttributeRight + */ +- (void)setInsets:(MASEdgeInsets)insets; + +/** + * Modifies the NSLayoutConstraint constant, + * only affects MASConstraints in which the first item's NSLayoutAttribute is one of the following + * NSLayoutAttributeTop, NSLayoutAttributeLeft, NSLayoutAttributeBottom, NSLayoutAttributeRight + */ +- (void)setInset:(CGFloat)inset; + +/** + * Modifies the NSLayoutConstraint constant, + * only affects MASConstraints in which the first item's NSLayoutAttribute is one of the following + * NSLayoutAttributeWidth, NSLayoutAttributeHeight + */ +- (void)setSizeOffset:(CGSize)sizeOffset; + +/** + * Modifies the NSLayoutConstraint constant, + * only affects MASConstraints in which the first item's NSLayoutAttribute is one of the following + * NSLayoutAttributeCenterX, NSLayoutAttributeCenterY + */ +- (void)setCenterOffset:(CGPoint)centerOffset; + +/** + * Modifies the NSLayoutConstraint constant + */ +- (void)setOffset:(CGFloat)offset; + + +// NSLayoutConstraint Installation support + +#if TARGET_OS_MAC && !(TARGET_OS_IPHONE || TARGET_OS_TV) +/** + * Whether or not to go through the animator proxy when modifying the constraint + */ +@property (nonatomic, copy, readonly) MASConstraint *animator; +#endif + +/** + * Activates an NSLayoutConstraint if it's supported by an OS. + * Invokes install otherwise. + */ +- (void)activate; + +/** + * Deactivates previously installed/activated NSLayoutConstraint. + */ +- (void)deactivate; + +/** + * Creates a NSLayoutConstraint and adds it to the appropriate view. + */ +- (void)install; + +/** + * Removes previously installed NSLayoutConstraint + */ +- (void)uninstall; + +@end + + +/** + * Convenience auto-boxing macros for MASConstraint methods. + * + * Defining MAS_SHORTHAND_GLOBALS will turn on auto-boxing for default syntax. + * A potential drawback of this is that the unprefixed macros will appear in global scope. + */ +#define mas_equalTo(...) equalTo(MASBoxValue((__VA_ARGS__))) +#define mas_greaterThanOrEqualTo(...) greaterThanOrEqualTo(MASBoxValue((__VA_ARGS__))) +#define mas_lessThanOrEqualTo(...) lessThanOrEqualTo(MASBoxValue((__VA_ARGS__))) + +#define mas_offset(...) valueOffset(MASBoxValue((__VA_ARGS__))) + + +#ifdef MAS_SHORTHAND_GLOBALS + +#define equalTo(...) mas_equalTo(__VA_ARGS__) +#define greaterThanOrEqualTo(...) mas_greaterThanOrEqualTo(__VA_ARGS__) +#define lessThanOrEqualTo(...) mas_lessThanOrEqualTo(__VA_ARGS__) + +#define offset(...) mas_offset(__VA_ARGS__) + +#endif + + +@interface MASConstraint (AutoboxingSupport) + +/** + * Aliases to corresponding relation methods (for shorthand macros) + * Also needed to aid autocompletion + */ +- (MASConstraint * (^)(id attr))mas_equalTo; +- (MASConstraint * (^)(id attr))mas_greaterThanOrEqualTo; +- (MASConstraint * (^)(id attr))mas_lessThanOrEqualTo; + +/** + * A dummy method to aid autocompletion + */ +- (MASConstraint * (^)(id offset))mas_offset; + +@end diff --git a/CustomKeyboard/Masonry/Masonry/MASConstraint.m b/CustomKeyboard/Masonry/Masonry/MASConstraint.m new file mode 100755 index 0000000..52de590 --- /dev/null +++ b/CustomKeyboard/Masonry/Masonry/MASConstraint.m @@ -0,0 +1,301 @@ +// +// MASConstraint.m +// Masonry +// +// Created by Nick Tymchenko on 1/20/14. +// + +#import "MASConstraint.h" +#import "MASConstraint+Private.h" + +#define MASMethodNotImplemented() \ + @throw [NSException exceptionWithName:NSInternalInconsistencyException \ + reason:[NSString stringWithFormat:@"You must override %@ in a subclass.", NSStringFromSelector(_cmd)] \ + userInfo:nil] + +@implementation MASConstraint + +#pragma mark - Init + +- (id)init { + NSAssert(![self isMemberOfClass:[MASConstraint class]], @"MASConstraint is an abstract class, you should not instantiate it directly."); + return [super init]; +} + +#pragma mark - NSLayoutRelation proxies + +- (MASConstraint * (^)(id))equalTo { + return ^id(id attribute) { + return self.equalToWithRelation(attribute, NSLayoutRelationEqual); + }; +} + +- (MASConstraint * (^)(id))mas_equalTo { + return ^id(id attribute) { + return self.equalToWithRelation(attribute, NSLayoutRelationEqual); + }; +} + +- (MASConstraint * (^)(id))greaterThanOrEqualTo { + return ^id(id attribute) { + return self.equalToWithRelation(attribute, NSLayoutRelationGreaterThanOrEqual); + }; +} + +- (MASConstraint * (^)(id))mas_greaterThanOrEqualTo { + return ^id(id attribute) { + return self.equalToWithRelation(attribute, NSLayoutRelationGreaterThanOrEqual); + }; +} + +- (MASConstraint * (^)(id))lessThanOrEqualTo { + return ^id(id attribute) { + return self.equalToWithRelation(attribute, NSLayoutRelationLessThanOrEqual); + }; +} + +- (MASConstraint * (^)(id))mas_lessThanOrEqualTo { + return ^id(id attribute) { + return self.equalToWithRelation(attribute, NSLayoutRelationLessThanOrEqual); + }; +} + +#pragma mark - MASLayoutPriority proxies + +- (MASConstraint * (^)(void))priorityLow { + return ^id{ + self.priority(MASLayoutPriorityDefaultLow); + return self; + }; +} + +- (MASConstraint * (^)(void))priorityMedium { + return ^id{ + self.priority(MASLayoutPriorityDefaultMedium); + return self; + }; +} + +- (MASConstraint * (^)(void))priorityHigh { + return ^id{ + self.priority(MASLayoutPriorityDefaultHigh); + return self; + }; +} + +#pragma mark - NSLayoutConstraint constant proxies + +- (MASConstraint * (^)(MASEdgeInsets))insets { + return ^id(MASEdgeInsets insets){ + self.insets = insets; + return self; + }; +} + +- (MASConstraint * (^)(CGFloat))inset { + return ^id(CGFloat inset){ + self.inset = inset; + return self; + }; +} + +- (MASConstraint * (^)(CGSize))sizeOffset { + return ^id(CGSize offset) { + self.sizeOffset = offset; + return self; + }; +} + +- (MASConstraint * (^)(CGPoint))centerOffset { + return ^id(CGPoint offset) { + self.centerOffset = offset; + return self; + }; +} + +- (MASConstraint * (^)(CGFloat))offset { + return ^id(CGFloat offset){ + self.offset = offset; + return self; + }; +} + +- (MASConstraint * (^)(NSValue *value))valueOffset { + return ^id(NSValue *offset) { + NSAssert([offset isKindOfClass:NSValue.class], @"expected an NSValue offset, got: %@", offset); + [self setLayoutConstantWithValue:offset]; + return self; + }; +} + +- (MASConstraint * (^)(id offset))mas_offset { + // Will never be called due to macro + return nil; +} + +#pragma mark - NSLayoutConstraint constant setter + +- (void)setLayoutConstantWithValue:(NSValue *)value { + if ([value isKindOfClass:NSNumber.class]) { + self.offset = [(NSNumber *)value doubleValue]; + } else if (strcmp(value.objCType, @encode(CGPoint)) == 0) { + CGPoint point; + [value getValue:&point]; + self.centerOffset = point; + } else if (strcmp(value.objCType, @encode(CGSize)) == 0) { + CGSize size; + [value getValue:&size]; + self.sizeOffset = size; + } else if (strcmp(value.objCType, @encode(MASEdgeInsets)) == 0) { + MASEdgeInsets insets; + [value getValue:&insets]; + self.insets = insets; + } else { + NSAssert(NO, @"attempting to set layout constant with unsupported value: %@", value); + } +} + +#pragma mark - Semantic properties + +- (MASConstraint *)with { + return self; +} + +- (MASConstraint *)and { + return self; +} + +#pragma mark - Chaining + +- (MASConstraint *)addConstraintWithLayoutAttribute:(NSLayoutAttribute __unused)layoutAttribute { + MASMethodNotImplemented(); +} + +- (MASConstraint *)left { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeft]; +} + +- (MASConstraint *)top { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTop]; +} + +- (MASConstraint *)right { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeRight]; +} + +- (MASConstraint *)bottom { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBottom]; +} + +- (MASConstraint *)leading { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeading]; +} + +- (MASConstraint *)trailing { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTrailing]; +} + +- (MASConstraint *)width { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeWidth]; +} + +- (MASConstraint *)height { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeHeight]; +} + +- (MASConstraint *)centerX { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterX]; +} + +- (MASConstraint *)centerY { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterY]; +} + +- (MASConstraint *)baseline { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBaseline]; +} + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + +- (MASConstraint *)firstBaseline { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeFirstBaseline]; +} +- (MASConstraint *)lastBaseline { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLastBaseline]; +} + +#endif + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) + +- (MASConstraint *)leftMargin { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeftMargin]; +} + +- (MASConstraint *)rightMargin { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeRightMargin]; +} + +- (MASConstraint *)topMargin { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTopMargin]; +} + +- (MASConstraint *)bottomMargin { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBottomMargin]; +} + +- (MASConstraint *)leadingMargin { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeadingMargin]; +} + +- (MASConstraint *)trailingMargin { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTrailingMargin]; +} + +- (MASConstraint *)centerXWithinMargins { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterXWithinMargins]; +} + +- (MASConstraint *)centerYWithinMargins { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterYWithinMargins]; +} + +#endif + +#pragma mark - Abstract + +- (MASConstraint * (^)(CGFloat multiplier))multipliedBy { MASMethodNotImplemented(); } + +- (MASConstraint * (^)(CGFloat divider))dividedBy { MASMethodNotImplemented(); } + +- (MASConstraint * (^)(MASLayoutPriority priority))priority { MASMethodNotImplemented(); } + +- (MASConstraint * (^)(id, NSLayoutRelation))equalToWithRelation { MASMethodNotImplemented(); } + +- (MASConstraint * (^)(id key))key { MASMethodNotImplemented(); } + +- (void)setInsets:(MASEdgeInsets __unused)insets { MASMethodNotImplemented(); } + +- (void)setInset:(CGFloat __unused)inset { MASMethodNotImplemented(); } + +- (void)setSizeOffset:(CGSize __unused)sizeOffset { MASMethodNotImplemented(); } + +- (void)setCenterOffset:(CGPoint __unused)centerOffset { MASMethodNotImplemented(); } + +- (void)setOffset:(CGFloat __unused)offset { MASMethodNotImplemented(); } + +#if TARGET_OS_MAC && !(TARGET_OS_IPHONE || TARGET_OS_TV) + +- (MASConstraint *)animator { MASMethodNotImplemented(); } + +#endif + +- (void)activate { MASMethodNotImplemented(); } + +- (void)deactivate { MASMethodNotImplemented(); } + +- (void)install { MASMethodNotImplemented(); } + +- (void)uninstall { MASMethodNotImplemented(); } + +@end diff --git a/CustomKeyboard/Masonry/Masonry/MASConstraintMaker.h b/CustomKeyboard/Masonry/Masonry/MASConstraintMaker.h new file mode 100755 index 0000000..d9b58f4 --- /dev/null +++ b/CustomKeyboard/Masonry/Masonry/MASConstraintMaker.h @@ -0,0 +1,146 @@ +// +// MASConstraintMaker.h +// Masonry +// +// Created by Jonas Budelmann on 20/07/13. +// Copyright (c) 2013 cloudling. All rights reserved. +// + +#import "MASConstraint.h" +#import "MASUtilities.h" + +typedef NS_OPTIONS(NSInteger, MASAttribute) { + MASAttributeLeft = 1 << NSLayoutAttributeLeft, + MASAttributeRight = 1 << NSLayoutAttributeRight, + MASAttributeTop = 1 << NSLayoutAttributeTop, + MASAttributeBottom = 1 << NSLayoutAttributeBottom, + MASAttributeLeading = 1 << NSLayoutAttributeLeading, + MASAttributeTrailing = 1 << NSLayoutAttributeTrailing, + MASAttributeWidth = 1 << NSLayoutAttributeWidth, + MASAttributeHeight = 1 << NSLayoutAttributeHeight, + MASAttributeCenterX = 1 << NSLayoutAttributeCenterX, + MASAttributeCenterY = 1 << NSLayoutAttributeCenterY, + MASAttributeBaseline = 1 << NSLayoutAttributeBaseline, + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + + MASAttributeFirstBaseline = 1 << NSLayoutAttributeFirstBaseline, + MASAttributeLastBaseline = 1 << NSLayoutAttributeLastBaseline, + +#endif + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) + + MASAttributeLeftMargin = 1 << NSLayoutAttributeLeftMargin, + MASAttributeRightMargin = 1 << NSLayoutAttributeRightMargin, + MASAttributeTopMargin = 1 << NSLayoutAttributeTopMargin, + MASAttributeBottomMargin = 1 << NSLayoutAttributeBottomMargin, + MASAttributeLeadingMargin = 1 << NSLayoutAttributeLeadingMargin, + MASAttributeTrailingMargin = 1 << NSLayoutAttributeTrailingMargin, + MASAttributeCenterXWithinMargins = 1 << NSLayoutAttributeCenterXWithinMargins, + MASAttributeCenterYWithinMargins = 1 << NSLayoutAttributeCenterYWithinMargins, + +#endif + +}; + +/** + * Provides factory methods for creating MASConstraints. + * Constraints are collected until they are ready to be installed + * + */ +@interface MASConstraintMaker : NSObject + +/** + * The following properties return a new MASViewConstraint + * with the first item set to the makers associated view and the appropriate MASViewAttribute + */ +@property (nonatomic, strong, readonly) MASConstraint *left; +@property (nonatomic, strong, readonly) MASConstraint *top; +@property (nonatomic, strong, readonly) MASConstraint *right; +@property (nonatomic, strong, readonly) MASConstraint *bottom; +@property (nonatomic, strong, readonly) MASConstraint *leading; +@property (nonatomic, strong, readonly) MASConstraint *trailing; +@property (nonatomic, strong, readonly) MASConstraint *width; +@property (nonatomic, strong, readonly) MASConstraint *height; +@property (nonatomic, strong, readonly) MASConstraint *centerX; +@property (nonatomic, strong, readonly) MASConstraint *centerY; +@property (nonatomic, strong, readonly) MASConstraint *baseline; + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + +@property (nonatomic, strong, readonly) MASConstraint *firstBaseline; +@property (nonatomic, strong, readonly) MASConstraint *lastBaseline; + +#endif + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) + +@property (nonatomic, strong, readonly) MASConstraint *leftMargin; +@property (nonatomic, strong, readonly) MASConstraint *rightMargin; +@property (nonatomic, strong, readonly) MASConstraint *topMargin; +@property (nonatomic, strong, readonly) MASConstraint *bottomMargin; +@property (nonatomic, strong, readonly) MASConstraint *leadingMargin; +@property (nonatomic, strong, readonly) MASConstraint *trailingMargin; +@property (nonatomic, strong, readonly) MASConstraint *centerXWithinMargins; +@property (nonatomic, strong, readonly) MASConstraint *centerYWithinMargins; + +#endif + +/** + * Returns a block which creates a new MASCompositeConstraint with the first item set + * to the makers associated view and children corresponding to the set bits in the + * MASAttribute parameter. Combine multiple attributes via binary-or. + */ +@property (nonatomic, strong, readonly) MASConstraint *(^attributes)(MASAttribute attrs); + +/** + * Creates a MASCompositeConstraint with type MASCompositeConstraintTypeEdges + * which generates the appropriate MASViewConstraint children (top, left, bottom, right) + * with the first item set to the makers associated view + */ +@property (nonatomic, strong, readonly) MASConstraint *edges; + +/** + * Creates a MASCompositeConstraint with type MASCompositeConstraintTypeSize + * which generates the appropriate MASViewConstraint children (width, height) + * with the first item set to the makers associated view + */ +@property (nonatomic, strong, readonly) MASConstraint *size; + +/** + * Creates a MASCompositeConstraint with type MASCompositeConstraintTypeCenter + * which generates the appropriate MASViewConstraint children (centerX, centerY) + * with the first item set to the makers associated view + */ +@property (nonatomic, strong, readonly) MASConstraint *center; + +/** + * Whether or not to check for an existing constraint instead of adding constraint + */ +@property (nonatomic, assign) BOOL updateExisting; + +/** + * Whether or not to remove existing constraints prior to installing + */ +@property (nonatomic, assign) BOOL removeExisting; + +/** + * initialises the maker with a default view + * + * @param view any MASConstraint are created with this view as the first item + * + * @return a new MASConstraintMaker + */ +- (id)initWithView:(MAS_VIEW *)view; + +/** + * Calls install method on any MASConstraints which have been created by this maker + * + * @return an array of all the installed MASConstraints + */ +- (NSArray *)install; + +- (MASConstraint * (^)(dispatch_block_t))group; + +@end diff --git a/CustomKeyboard/Masonry/Masonry/MASConstraintMaker.m b/CustomKeyboard/Masonry/Masonry/MASConstraintMaker.m new file mode 100755 index 0000000..f11492a --- /dev/null +++ b/CustomKeyboard/Masonry/Masonry/MASConstraintMaker.m @@ -0,0 +1,273 @@ +// +// MASConstraintMaker.m +// Masonry +// +// Created by Jonas Budelmann on 20/07/13. +// Copyright (c) 2013 cloudling. All rights reserved. +// + +#import "MASConstraintMaker.h" +#import "MASViewConstraint.h" +#import "MASCompositeConstraint.h" +#import "MASConstraint+Private.h" +#import "MASViewAttribute.h" +#import "View+MASAdditions.h" + +@interface MASConstraintMaker () + +@property (nonatomic, weak) MAS_VIEW *view; +@property (nonatomic, strong) NSMutableArray *constraints; + +@end + +@implementation MASConstraintMaker + +- (id)initWithView:(MAS_VIEW *)view { + self = [super init]; + if (!self) return nil; + + self.view = view; + self.constraints = NSMutableArray.new; + + return self; +} + +- (NSArray *)install { + if (self.removeExisting) { + NSArray *installedConstraints = [MASViewConstraint installedConstraintsForView:self.view]; + for (MASConstraint *constraint in installedConstraints) { + [constraint uninstall]; + } + } + NSArray *constraints = self.constraints.copy; + for (MASConstraint *constraint in constraints) { + constraint.updateExisting = self.updateExisting; + [constraint install]; + } + [self.constraints removeAllObjects]; + return constraints; +} + +#pragma mark - MASConstraintDelegate + +- (void)constraint:(MASConstraint *)constraint shouldBeReplacedWithConstraint:(MASConstraint *)replacementConstraint { + NSUInteger index = [self.constraints indexOfObject:constraint]; + NSAssert(index != NSNotFound, @"Could not find constraint %@", constraint); + [self.constraints replaceObjectAtIndex:index withObject:replacementConstraint]; +} + +- (MASConstraint *)constraint:(MASConstraint *)constraint addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute { + MASViewAttribute *viewAttribute = [[MASViewAttribute alloc] initWithView:self.view layoutAttribute:layoutAttribute]; + MASViewConstraint *newConstraint = [[MASViewConstraint alloc] initWithFirstViewAttribute:viewAttribute]; + if ([constraint isKindOfClass:MASViewConstraint.class]) { + //replace with composite constraint + NSArray *children = @[constraint, newConstraint]; + MASCompositeConstraint *compositeConstraint = [[MASCompositeConstraint alloc] initWithChildren:children]; + compositeConstraint.delegate = self; + [self constraint:constraint shouldBeReplacedWithConstraint:compositeConstraint]; + return compositeConstraint; + } + if (!constraint) { + newConstraint.delegate = self; + [self.constraints addObject:newConstraint]; + } + return newConstraint; +} + +- (MASConstraint *)addConstraintWithAttributes:(MASAttribute)attrs { + __unused MASAttribute anyAttribute = (MASAttributeLeft | MASAttributeRight | MASAttributeTop | MASAttributeBottom | MASAttributeLeading + | MASAttributeTrailing | MASAttributeWidth | MASAttributeHeight | MASAttributeCenterX + | MASAttributeCenterY | MASAttributeBaseline +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + | MASAttributeFirstBaseline | MASAttributeLastBaseline +#endif +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) + | MASAttributeLeftMargin | MASAttributeRightMargin | MASAttributeTopMargin | MASAttributeBottomMargin + | MASAttributeLeadingMargin | MASAttributeTrailingMargin | MASAttributeCenterXWithinMargins + | MASAttributeCenterYWithinMargins +#endif + ); + + NSAssert((attrs & anyAttribute) != 0, @"You didn't pass any attribute to make.attributes(...)"); + + NSMutableArray *attributes = [NSMutableArray array]; + + if (attrs & MASAttributeLeft) [attributes addObject:self.view.mas_left]; + if (attrs & MASAttributeRight) [attributes addObject:self.view.mas_right]; + if (attrs & MASAttributeTop) [attributes addObject:self.view.mas_top]; + if (attrs & MASAttributeBottom) [attributes addObject:self.view.mas_bottom]; + if (attrs & MASAttributeLeading) [attributes addObject:self.view.mas_leading]; + if (attrs & MASAttributeTrailing) [attributes addObject:self.view.mas_trailing]; + if (attrs & MASAttributeWidth) [attributes addObject:self.view.mas_width]; + if (attrs & MASAttributeHeight) [attributes addObject:self.view.mas_height]; + if (attrs & MASAttributeCenterX) [attributes addObject:self.view.mas_centerX]; + if (attrs & MASAttributeCenterY) [attributes addObject:self.view.mas_centerY]; + if (attrs & MASAttributeBaseline) [attributes addObject:self.view.mas_baseline]; + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + + if (attrs & MASAttributeFirstBaseline) [attributes addObject:self.view.mas_firstBaseline]; + if (attrs & MASAttributeLastBaseline) [attributes addObject:self.view.mas_lastBaseline]; + +#endif + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) + + if (attrs & MASAttributeLeftMargin) [attributes addObject:self.view.mas_leftMargin]; + if (attrs & MASAttributeRightMargin) [attributes addObject:self.view.mas_rightMargin]; + if (attrs & MASAttributeTopMargin) [attributes addObject:self.view.mas_topMargin]; + if (attrs & MASAttributeBottomMargin) [attributes addObject:self.view.mas_bottomMargin]; + if (attrs & MASAttributeLeadingMargin) [attributes addObject:self.view.mas_leadingMargin]; + if (attrs & MASAttributeTrailingMargin) [attributes addObject:self.view.mas_trailingMargin]; + if (attrs & MASAttributeCenterXWithinMargins) [attributes addObject:self.view.mas_centerXWithinMargins]; + if (attrs & MASAttributeCenterYWithinMargins) [attributes addObject:self.view.mas_centerYWithinMargins]; + +#endif + + NSMutableArray *children = [NSMutableArray arrayWithCapacity:attributes.count]; + + for (MASViewAttribute *a in attributes) { + [children addObject:[[MASViewConstraint alloc] initWithFirstViewAttribute:a]]; + } + + MASCompositeConstraint *constraint = [[MASCompositeConstraint alloc] initWithChildren:children]; + constraint.delegate = self; + [self.constraints addObject:constraint]; + return constraint; +} + +#pragma mark - standard Attributes + +- (MASConstraint *)addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute { + return [self constraint:nil addConstraintWithLayoutAttribute:layoutAttribute]; +} + +- (MASConstraint *)left { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeft]; +} + +- (MASConstraint *)top { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTop]; +} + +- (MASConstraint *)right { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeRight]; +} + +- (MASConstraint *)bottom { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBottom]; +} + +- (MASConstraint *)leading { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeading]; +} + +- (MASConstraint *)trailing { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTrailing]; +} + +- (MASConstraint *)width { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeWidth]; +} + +- (MASConstraint *)height { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeHeight]; +} + +- (MASConstraint *)centerX { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterX]; +} + +- (MASConstraint *)centerY { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterY]; +} + +- (MASConstraint *)baseline { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBaseline]; +} + +- (MASConstraint *(^)(MASAttribute))attributes { + return ^(MASAttribute attrs){ + return [self addConstraintWithAttributes:attrs]; + }; +} + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + +- (MASConstraint *)firstBaseline { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeFirstBaseline]; +} + +- (MASConstraint *)lastBaseline { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLastBaseline]; +} + +#endif + + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) + +- (MASConstraint *)leftMargin { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeftMargin]; +} + +- (MASConstraint *)rightMargin { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeRightMargin]; +} + +- (MASConstraint *)topMargin { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTopMargin]; +} + +- (MASConstraint *)bottomMargin { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBottomMargin]; +} + +- (MASConstraint *)leadingMargin { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeadingMargin]; +} + +- (MASConstraint *)trailingMargin { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTrailingMargin]; +} + +- (MASConstraint *)centerXWithinMargins { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterXWithinMargins]; +} + +- (MASConstraint *)centerYWithinMargins { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterYWithinMargins]; +} + +#endif + + +#pragma mark - composite Attributes + +- (MASConstraint *)edges { + return [self addConstraintWithAttributes:MASAttributeTop | MASAttributeLeft | MASAttributeRight | MASAttributeBottom]; +} + +- (MASConstraint *)size { + return [self addConstraintWithAttributes:MASAttributeWidth | MASAttributeHeight]; +} + +- (MASConstraint *)center { + return [self addConstraintWithAttributes:MASAttributeCenterX | MASAttributeCenterY]; +} + +#pragma mark - grouping + +- (MASConstraint *(^)(dispatch_block_t group))group { + return ^id(dispatch_block_t group) { + NSInteger previousCount = self.constraints.count; + group(); + + NSArray *children = [self.constraints subarrayWithRange:NSMakeRange(previousCount, self.constraints.count - previousCount)]; + MASCompositeConstraint *constraint = [[MASCompositeConstraint alloc] initWithChildren:children]; + constraint.delegate = self; + return constraint; + }; +} + +@end diff --git a/CustomKeyboard/Masonry/Masonry/MASLayoutConstraint.h b/CustomKeyboard/Masonry/Masonry/MASLayoutConstraint.h new file mode 100755 index 0000000..699041c --- /dev/null +++ b/CustomKeyboard/Masonry/Masonry/MASLayoutConstraint.h @@ -0,0 +1,22 @@ +// +// MASLayoutConstraint.h +// Masonry +// +// Created by Jonas Budelmann on 3/08/13. +// Copyright (c) 2013 Jonas Budelmann. All rights reserved. +// + +#import "MASUtilities.h" + +/** + * When you are debugging or printing the constraints attached to a view this subclass + * makes it easier to identify which constraints have been created via Masonry + */ +@interface MASLayoutConstraint : NSLayoutConstraint + +/** + * a key to associate with this constraint + */ +@property (nonatomic, strong) id mas_key; + +@end diff --git a/CustomKeyboard/Masonry/Masonry/MASLayoutConstraint.m b/CustomKeyboard/Masonry/Masonry/MASLayoutConstraint.m new file mode 100755 index 0000000..3483f02 --- /dev/null +++ b/CustomKeyboard/Masonry/Masonry/MASLayoutConstraint.m @@ -0,0 +1,13 @@ +// +// MASLayoutConstraint.m +// Masonry +// +// Created by Jonas Budelmann on 3/08/13. +// Copyright (c) 2013 Jonas Budelmann. All rights reserved. +// + +#import "MASLayoutConstraint.h" + +@implementation MASLayoutConstraint + +@end diff --git a/CustomKeyboard/Masonry/Masonry/MASUtilities.h b/CustomKeyboard/Masonry/Masonry/MASUtilities.h new file mode 100755 index 0000000..1dbfd93 --- /dev/null +++ b/CustomKeyboard/Masonry/Masonry/MASUtilities.h @@ -0,0 +1,136 @@ +// +// MASUtilities.h +// Masonry +// +// Created by Jonas Budelmann on 19/08/13. +// Copyright (c) 2013 Jonas Budelmann. All rights reserved. +// + +#import + + + +#if TARGET_OS_IPHONE || TARGET_OS_TV + + #import + #define MAS_VIEW UIView + #define MAS_VIEW_CONTROLLER UIViewController + #define MASEdgeInsets UIEdgeInsets + + typedef UILayoutPriority MASLayoutPriority; + static const MASLayoutPriority MASLayoutPriorityRequired = UILayoutPriorityRequired; + static const MASLayoutPriority MASLayoutPriorityDefaultHigh = UILayoutPriorityDefaultHigh; + static const MASLayoutPriority MASLayoutPriorityDefaultMedium = 500; + static const MASLayoutPriority MASLayoutPriorityDefaultLow = UILayoutPriorityDefaultLow; + static const MASLayoutPriority MASLayoutPriorityFittingSizeLevel = UILayoutPriorityFittingSizeLevel; + +#elif TARGET_OS_MAC + + #import + #define MAS_VIEW NSView + #define MASEdgeInsets NSEdgeInsets + + typedef NSLayoutPriority MASLayoutPriority; + static const MASLayoutPriority MASLayoutPriorityRequired = NSLayoutPriorityRequired; + static const MASLayoutPriority MASLayoutPriorityDefaultHigh = NSLayoutPriorityDefaultHigh; + static const MASLayoutPriority MASLayoutPriorityDragThatCanResizeWindow = NSLayoutPriorityDragThatCanResizeWindow; + static const MASLayoutPriority MASLayoutPriorityDefaultMedium = 501; + static const MASLayoutPriority MASLayoutPriorityWindowSizeStayPut = NSLayoutPriorityWindowSizeStayPut; + static const MASLayoutPriority MASLayoutPriorityDragThatCannotResizeWindow = NSLayoutPriorityDragThatCannotResizeWindow; + static const MASLayoutPriority MASLayoutPriorityDefaultLow = NSLayoutPriorityDefaultLow; + static const MASLayoutPriority MASLayoutPriorityFittingSizeCompression = NSLayoutPriorityFittingSizeCompression; + +#endif + +/** + * Allows you to attach keys to objects matching the variable names passed. + * + * view1.mas_key = @"view1", view2.mas_key = @"view2"; + * + * is equivalent to: + * + * MASAttachKeys(view1, view2); + */ +#define MASAttachKeys(...) \ + { \ + NSDictionary *keyPairs = NSDictionaryOfVariableBindings(__VA_ARGS__); \ + for (id key in keyPairs.allKeys) { \ + id obj = keyPairs[key]; \ + NSAssert([obj respondsToSelector:@selector(setMas_key:)], \ + @"Cannot attach mas_key to %@", obj); \ + [obj setMas_key:key]; \ + } \ + } + +/** + * Used to create object hashes + * Based on http://www.mikeash.com/pyblog/friday-qa-2010-06-18-implementing-equality-and-hashing.html + */ +#define MAS_NSUINT_BIT (CHAR_BIT * sizeof(NSUInteger)) +#define MAS_NSUINTROTATE(val, howmuch) ((((NSUInteger)val) << howmuch) | (((NSUInteger)val) >> (MAS_NSUINT_BIT - howmuch))) + +/** + * Given a scalar or struct value, wraps it in NSValue + * Based on EXPObjectify: https://github.com/specta/expecta + */ +static inline id _MASBoxValue(const char *type, ...) { + va_list v; + va_start(v, type); + id obj = nil; + if (strcmp(type, @encode(id)) == 0) { + id actual = va_arg(v, id); + obj = actual; + } else if (strcmp(type, @encode(CGPoint)) == 0) { + CGPoint actual = (CGPoint)va_arg(v, CGPoint); + obj = [NSValue value:&actual withObjCType:type]; + } else if (strcmp(type, @encode(CGSize)) == 0) { + CGSize actual = (CGSize)va_arg(v, CGSize); + obj = [NSValue value:&actual withObjCType:type]; + } else if (strcmp(type, @encode(MASEdgeInsets)) == 0) { + MASEdgeInsets actual = (MASEdgeInsets)va_arg(v, MASEdgeInsets); + obj = [NSValue value:&actual withObjCType:type]; + } else if (strcmp(type, @encode(double)) == 0) { + double actual = (double)va_arg(v, double); + obj = [NSNumber numberWithDouble:actual]; + } else if (strcmp(type, @encode(float)) == 0) { + float actual = (float)va_arg(v, double); + obj = [NSNumber numberWithFloat:actual]; + } else if (strcmp(type, @encode(int)) == 0) { + int actual = (int)va_arg(v, int); + obj = [NSNumber numberWithInt:actual]; + } else if (strcmp(type, @encode(long)) == 0) { + long actual = (long)va_arg(v, long); + obj = [NSNumber numberWithLong:actual]; + } else if (strcmp(type, @encode(long long)) == 0) { + long long actual = (long long)va_arg(v, long long); + obj = [NSNumber numberWithLongLong:actual]; + } else if (strcmp(type, @encode(short)) == 0) { + short actual = (short)va_arg(v, int); + obj = [NSNumber numberWithShort:actual]; + } else if (strcmp(type, @encode(char)) == 0) { + char actual = (char)va_arg(v, int); + obj = [NSNumber numberWithChar:actual]; + } else if (strcmp(type, @encode(bool)) == 0) { + bool actual = (bool)va_arg(v, int); + obj = [NSNumber numberWithBool:actual]; + } else if (strcmp(type, @encode(unsigned char)) == 0) { + unsigned char actual = (unsigned char)va_arg(v, unsigned int); + obj = [NSNumber numberWithUnsignedChar:actual]; + } else if (strcmp(type, @encode(unsigned int)) == 0) { + unsigned int actual = (unsigned int)va_arg(v, unsigned int); + obj = [NSNumber numberWithUnsignedInt:actual]; + } else if (strcmp(type, @encode(unsigned long)) == 0) { + unsigned long actual = (unsigned long)va_arg(v, unsigned long); + obj = [NSNumber numberWithUnsignedLong:actual]; + } else if (strcmp(type, @encode(unsigned long long)) == 0) { + unsigned long long actual = (unsigned long long)va_arg(v, unsigned long long); + obj = [NSNumber numberWithUnsignedLongLong:actual]; + } else if (strcmp(type, @encode(unsigned short)) == 0) { + unsigned short actual = (unsigned short)va_arg(v, unsigned int); + obj = [NSNumber numberWithUnsignedShort:actual]; + } + va_end(v); + return obj; +} + +#define MASBoxValue(value) _MASBoxValue(@encode(__typeof__((value))), (value)) diff --git a/CustomKeyboard/Masonry/Masonry/MASViewAttribute.h b/CustomKeyboard/Masonry/Masonry/MASViewAttribute.h new file mode 100755 index 0000000..601c25d --- /dev/null +++ b/CustomKeyboard/Masonry/Masonry/MASViewAttribute.h @@ -0,0 +1,49 @@ +// +// MASViewAttribute.h +// Masonry +// +// Created by Jonas Budelmann on 21/07/13. +// Copyright (c) 2013 cloudling. All rights reserved. +// + +#import "MASUtilities.h" + +/** + * An immutable tuple which stores the view and the related NSLayoutAttribute. + * Describes part of either the left or right hand side of a constraint equation + */ +@interface MASViewAttribute : NSObject + +/** + * The view which the reciever relates to. Can be nil if item is not a view. + */ +@property (nonatomic, weak, readonly) MAS_VIEW *view; + +/** + * The item which the reciever relates to. + */ +@property (nonatomic, weak, readonly) id item; + +/** + * The attribute which the reciever relates to + */ +@property (nonatomic, assign, readonly) NSLayoutAttribute layoutAttribute; + +/** + * Convenience initializer. + */ +- (id)initWithView:(MAS_VIEW *)view layoutAttribute:(NSLayoutAttribute)layoutAttribute; + +/** + * The designated initializer. + */ +- (id)initWithView:(MAS_VIEW *)view item:(id)item layoutAttribute:(NSLayoutAttribute)layoutAttribute; + +/** + * Determine whether the layoutAttribute is a size attribute + * + * @return YES if layoutAttribute is equal to NSLayoutAttributeWidth or NSLayoutAttributeHeight + */ +- (BOOL)isSizeAttribute; + +@end diff --git a/CustomKeyboard/Masonry/Masonry/MASViewAttribute.m b/CustomKeyboard/Masonry/Masonry/MASViewAttribute.m new file mode 100755 index 0000000..e573e8b --- /dev/null +++ b/CustomKeyboard/Masonry/Masonry/MASViewAttribute.m @@ -0,0 +1,46 @@ +// +// MASViewAttribute.m +// Masonry +// +// Created by Jonas Budelmann on 21/07/13. +// Copyright (c) 2013 cloudling. All rights reserved. +// + +#import "MASViewAttribute.h" + +@implementation MASViewAttribute + +- (id)initWithView:(MAS_VIEW *)view layoutAttribute:(NSLayoutAttribute)layoutAttribute { + self = [self initWithView:view item:view layoutAttribute:layoutAttribute]; + return self; +} + +- (id)initWithView:(MAS_VIEW *)view item:(id)item layoutAttribute:(NSLayoutAttribute)layoutAttribute { + self = [super init]; + if (!self) return nil; + + _view = view; + _item = item; + _layoutAttribute = layoutAttribute; + + return self; +} + +- (BOOL)isSizeAttribute { + return self.layoutAttribute == NSLayoutAttributeWidth + || self.layoutAttribute == NSLayoutAttributeHeight; +} + +- (BOOL)isEqual:(MASViewAttribute *)viewAttribute { + if ([viewAttribute isKindOfClass:self.class]) { + return self.view == viewAttribute.view + && self.layoutAttribute == viewAttribute.layoutAttribute; + } + return [super isEqual:viewAttribute]; +} + +- (NSUInteger)hash { + return MAS_NSUINTROTATE([self.view hash], MAS_NSUINT_BIT / 2) ^ self.layoutAttribute; +} + +@end diff --git a/CustomKeyboard/Masonry/Masonry/MASViewConstraint.h b/CustomKeyboard/Masonry/Masonry/MASViewConstraint.h new file mode 100755 index 0000000..ec390d1 --- /dev/null +++ b/CustomKeyboard/Masonry/Masonry/MASViewConstraint.h @@ -0,0 +1,48 @@ +// +// MASViewConstraint.h +// Masonry +// +// Created by Jonas Budelmann on 20/07/13. +// Copyright (c) 2013 cloudling. All rights reserved. +// + +#import "MASViewAttribute.h" +#import "MASConstraint.h" +#import "MASLayoutConstraint.h" +#import "MASUtilities.h" + +/** + * A single constraint. + * Contains the attributes neccessary for creating a NSLayoutConstraint and adding it to the appropriate view + */ +@interface MASViewConstraint : MASConstraint + +/** + * First item/view and first attribute of the NSLayoutConstraint + */ +@property (nonatomic, strong, readonly) MASViewAttribute *firstViewAttribute; + +/** + * Second item/view and second attribute of the NSLayoutConstraint + */ +@property (nonatomic, strong, readonly) MASViewAttribute *secondViewAttribute; + +/** + * initialises the MASViewConstraint with the first part of the equation + * + * @param firstViewAttribute view.mas_left, view.mas_width etc. + * + * @return a new view constraint + */ +- (id)initWithFirstViewAttribute:(MASViewAttribute *)firstViewAttribute; + +/** + * Returns all MASViewConstraints installed with this view as a first item. + * + * @param view A view to retrieve constraints for. + * + * @return An array of MASViewConstraints. + */ ++ (NSArray *)installedConstraintsForView:(MAS_VIEW *)view; + +@end diff --git a/CustomKeyboard/Masonry/Masonry/MASViewConstraint.m b/CustomKeyboard/Masonry/Masonry/MASViewConstraint.m new file mode 100755 index 0000000..173eec1 --- /dev/null +++ b/CustomKeyboard/Masonry/Masonry/MASViewConstraint.m @@ -0,0 +1,401 @@ +// +// MASViewConstraint.m +// Masonry +// +// Created by Jonas Budelmann on 20/07/13. +// Copyright (c) 2013 cloudling. All rights reserved. +// + +#import "MASViewConstraint.h" +#import "MASConstraint+Private.h" +#import "MASCompositeConstraint.h" +#import "MASLayoutConstraint.h" +#import "View+MASAdditions.h" +#import + +@interface MAS_VIEW (MASConstraints) + +@property (nonatomic, readonly) NSMutableSet *mas_installedConstraints; + +@end + +@implementation MAS_VIEW (MASConstraints) + +static char kInstalledConstraintsKey; + +- (NSMutableSet *)mas_installedConstraints { + NSMutableSet *constraints = objc_getAssociatedObject(self, &kInstalledConstraintsKey); + if (!constraints) { + constraints = [NSMutableSet set]; + objc_setAssociatedObject(self, &kInstalledConstraintsKey, constraints, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + return constraints; +} + +@end + + +@interface MASViewConstraint () + +@property (nonatomic, strong, readwrite) MASViewAttribute *secondViewAttribute; +@property (nonatomic, weak) MAS_VIEW *installedView; +@property (nonatomic, weak) MASLayoutConstraint *layoutConstraint; +@property (nonatomic, assign) NSLayoutRelation layoutRelation; +@property (nonatomic, assign) MASLayoutPriority layoutPriority; +@property (nonatomic, assign) CGFloat layoutMultiplier; +@property (nonatomic, assign) CGFloat layoutConstant; +@property (nonatomic, assign) BOOL hasLayoutRelation; +@property (nonatomic, strong) id mas_key; +@property (nonatomic, assign) BOOL useAnimator; + +@end + +@implementation MASViewConstraint + +- (id)initWithFirstViewAttribute:(MASViewAttribute *)firstViewAttribute { + self = [super init]; + if (!self) return nil; + + _firstViewAttribute = firstViewAttribute; + self.layoutPriority = MASLayoutPriorityRequired; + self.layoutMultiplier = 1; + + return self; +} + +#pragma mark - NSCoping + +- (id)copyWithZone:(NSZone __unused *)zone { + MASViewConstraint *constraint = [[MASViewConstraint alloc] initWithFirstViewAttribute:self.firstViewAttribute]; + constraint.layoutConstant = self.layoutConstant; + constraint.layoutRelation = self.layoutRelation; + constraint.layoutPriority = self.layoutPriority; + constraint.layoutMultiplier = self.layoutMultiplier; + constraint.delegate = self.delegate; + return constraint; +} + +#pragma mark - Public + ++ (NSArray *)installedConstraintsForView:(MAS_VIEW *)view { + return [view.mas_installedConstraints allObjects]; +} + +#pragma mark - Private + +- (void)setLayoutConstant:(CGFloat)layoutConstant { + _layoutConstant = layoutConstant; + +#if TARGET_OS_MAC && !(TARGET_OS_IPHONE || TARGET_OS_TV) + if (self.useAnimator) { + [self.layoutConstraint.animator setConstant:layoutConstant]; + } else { + self.layoutConstraint.constant = layoutConstant; + } +#else + self.layoutConstraint.constant = layoutConstant; +#endif +} + +- (void)setLayoutRelation:(NSLayoutRelation)layoutRelation { + _layoutRelation = layoutRelation; + self.hasLayoutRelation = YES; +} + +- (BOOL)supportsActiveProperty { + return [self.layoutConstraint respondsToSelector:@selector(isActive)]; +} + +- (BOOL)isActive { + BOOL active = YES; + if ([self supportsActiveProperty]) { + active = [self.layoutConstraint isActive]; + } + + return active; +} + +- (BOOL)hasBeenInstalled { + return (self.layoutConstraint != nil) && [self isActive]; +} + +- (void)setSecondViewAttribute:(id)secondViewAttribute { + if ([secondViewAttribute isKindOfClass:NSValue.class]) { + [self setLayoutConstantWithValue:secondViewAttribute]; + } else if ([secondViewAttribute isKindOfClass:MAS_VIEW.class]) { + _secondViewAttribute = [[MASViewAttribute alloc] initWithView:secondViewAttribute layoutAttribute:self.firstViewAttribute.layoutAttribute]; + } else if ([secondViewAttribute isKindOfClass:MASViewAttribute.class]) { + _secondViewAttribute = secondViewAttribute; + } else { + NSAssert(NO, @"attempting to add unsupported attribute: %@", secondViewAttribute); + } +} + +#pragma mark - NSLayoutConstraint multiplier proxies + +- (MASConstraint * (^)(CGFloat))multipliedBy { + return ^id(CGFloat multiplier) { + NSAssert(!self.hasBeenInstalled, + @"Cannot modify constraint multiplier after it has been installed"); + + self.layoutMultiplier = multiplier; + return self; + }; +} + + +- (MASConstraint * (^)(CGFloat))dividedBy { + return ^id(CGFloat divider) { + NSAssert(!self.hasBeenInstalled, + @"Cannot modify constraint multiplier after it has been installed"); + + self.layoutMultiplier = 1.0/divider; + return self; + }; +} + +#pragma mark - MASLayoutPriority proxy + +- (MASConstraint * (^)(MASLayoutPriority))priority { + return ^id(MASLayoutPriority priority) { + NSAssert(!self.hasBeenInstalled, + @"Cannot modify constraint priority after it has been installed"); + + self.layoutPriority = priority; + return self; + }; +} + +#pragma mark - NSLayoutRelation proxy + +- (MASConstraint * (^)(id, NSLayoutRelation))equalToWithRelation { + return ^id(id attribute, NSLayoutRelation relation) { + if ([attribute isKindOfClass:NSArray.class]) { + NSAssert(!self.hasLayoutRelation, @"Redefinition of constraint relation"); + NSMutableArray *children = NSMutableArray.new; + for (id attr in attribute) { + MASViewConstraint *viewConstraint = [self copy]; + viewConstraint.layoutRelation = relation; + viewConstraint.secondViewAttribute = attr; + [children addObject:viewConstraint]; + } + MASCompositeConstraint *compositeConstraint = [[MASCompositeConstraint alloc] initWithChildren:children]; + compositeConstraint.delegate = self.delegate; + [self.delegate constraint:self shouldBeReplacedWithConstraint:compositeConstraint]; + return compositeConstraint; + } else { + NSAssert(!self.hasLayoutRelation || self.layoutRelation == relation && [attribute isKindOfClass:NSValue.class], @"Redefinition of constraint relation"); + self.layoutRelation = relation; + self.secondViewAttribute = attribute; + return self; + } + }; +} + +#pragma mark - Semantic properties + +- (MASConstraint *)with { + return self; +} + +- (MASConstraint *)and { + return self; +} + +#pragma mark - attribute chaining + +- (MASConstraint *)addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute { + NSAssert(!self.hasLayoutRelation, @"Attributes should be chained before defining the constraint relation"); + + return [self.delegate constraint:self addConstraintWithLayoutAttribute:layoutAttribute]; +} + +#pragma mark - Animator proxy + +#if TARGET_OS_MAC && !(TARGET_OS_IPHONE || TARGET_OS_TV) + +- (MASConstraint *)animator { + self.useAnimator = YES; + return self; +} + +#endif + +#pragma mark - debug helpers + +- (MASConstraint * (^)(id))key { + return ^id(id key) { + self.mas_key = key; + return self; + }; +} + +#pragma mark - NSLayoutConstraint constant setters + +- (void)setInsets:(MASEdgeInsets)insets { + NSLayoutAttribute layoutAttribute = self.firstViewAttribute.layoutAttribute; + switch (layoutAttribute) { + case NSLayoutAttributeLeft: + case NSLayoutAttributeLeading: + self.layoutConstant = insets.left; + break; + case NSLayoutAttributeTop: + self.layoutConstant = insets.top; + break; + case NSLayoutAttributeBottom: + self.layoutConstant = -insets.bottom; + break; + case NSLayoutAttributeRight: + case NSLayoutAttributeTrailing: + self.layoutConstant = -insets.right; + break; + default: + break; + } +} + +- (void)setInset:(CGFloat)inset { + [self setInsets:(MASEdgeInsets){.top = inset, .left = inset, .bottom = inset, .right = inset}]; +} + +- (void)setOffset:(CGFloat)offset { + self.layoutConstant = offset; +} + +- (void)setSizeOffset:(CGSize)sizeOffset { + NSLayoutAttribute layoutAttribute = self.firstViewAttribute.layoutAttribute; + switch (layoutAttribute) { + case NSLayoutAttributeWidth: + self.layoutConstant = sizeOffset.width; + break; + case NSLayoutAttributeHeight: + self.layoutConstant = sizeOffset.height; + break; + default: + break; + } +} + +- (void)setCenterOffset:(CGPoint)centerOffset { + NSLayoutAttribute layoutAttribute = self.firstViewAttribute.layoutAttribute; + switch (layoutAttribute) { + case NSLayoutAttributeCenterX: + self.layoutConstant = centerOffset.x; + break; + case NSLayoutAttributeCenterY: + self.layoutConstant = centerOffset.y; + break; + default: + break; + } +} + +#pragma mark - MASConstraint + +- (void)activate { + [self install]; +} + +- (void)deactivate { + [self uninstall]; +} + +- (void)install { + if (self.hasBeenInstalled) { + return; + } + + if ([self supportsActiveProperty] && self.layoutConstraint) { + self.layoutConstraint.active = YES; + [self.firstViewAttribute.view.mas_installedConstraints addObject:self]; + return; + } + + MAS_VIEW *firstLayoutItem = self.firstViewAttribute.item; + NSLayoutAttribute firstLayoutAttribute = self.firstViewAttribute.layoutAttribute; + MAS_VIEW *secondLayoutItem = self.secondViewAttribute.item; + NSLayoutAttribute secondLayoutAttribute = self.secondViewAttribute.layoutAttribute; + + // alignment attributes must have a secondViewAttribute + // therefore we assume that is refering to superview + // eg make.left.equalTo(@10) + if (!self.firstViewAttribute.isSizeAttribute && !self.secondViewAttribute) { + secondLayoutItem = self.firstViewAttribute.view.superview; + secondLayoutAttribute = firstLayoutAttribute; + } + + MASLayoutConstraint *layoutConstraint + = [MASLayoutConstraint constraintWithItem:firstLayoutItem + attribute:firstLayoutAttribute + relatedBy:self.layoutRelation + toItem:secondLayoutItem + attribute:secondLayoutAttribute + multiplier:self.layoutMultiplier + constant:self.layoutConstant]; + + layoutConstraint.priority = self.layoutPriority; + layoutConstraint.mas_key = self.mas_key; + + if (self.secondViewAttribute.view) { + MAS_VIEW *closestCommonSuperview = [self.firstViewAttribute.view mas_closestCommonSuperview:self.secondViewAttribute.view]; + NSAssert(closestCommonSuperview, + @"couldn't find a common superview for %@ and %@", + self.firstViewAttribute.view, self.secondViewAttribute.view); + self.installedView = closestCommonSuperview; + } else if (self.firstViewAttribute.isSizeAttribute) { + self.installedView = self.firstViewAttribute.view; + } else { + self.installedView = self.firstViewAttribute.view.superview; + } + + + MASLayoutConstraint *existingConstraint = nil; + if (self.updateExisting) { + existingConstraint = [self layoutConstraintSimilarTo:layoutConstraint]; + } + if (existingConstraint) { + // just update the constant + existingConstraint.constant = layoutConstraint.constant; + self.layoutConstraint = existingConstraint; + } else { + [self.installedView addConstraint:layoutConstraint]; + self.layoutConstraint = layoutConstraint; + [firstLayoutItem.mas_installedConstraints addObject:self]; + } +} + +- (MASLayoutConstraint *)layoutConstraintSimilarTo:(MASLayoutConstraint *)layoutConstraint { + // check if any constraints are the same apart from the only mutable property constant + + // go through constraints in reverse as we do not want to match auto-resizing or interface builder constraints + // and they are likely to be added first. + for (NSLayoutConstraint *existingConstraint in self.installedView.constraints.reverseObjectEnumerator) { + if (![existingConstraint isKindOfClass:MASLayoutConstraint.class]) continue; + if (existingConstraint.firstItem != layoutConstraint.firstItem) continue; + if (existingConstraint.secondItem != layoutConstraint.secondItem) continue; + if (existingConstraint.firstAttribute != layoutConstraint.firstAttribute) continue; + if (existingConstraint.secondAttribute != layoutConstraint.secondAttribute) continue; + if (existingConstraint.relation != layoutConstraint.relation) continue; + if (existingConstraint.multiplier != layoutConstraint.multiplier) continue; + if (existingConstraint.priority != layoutConstraint.priority) continue; + + return (id)existingConstraint; + } + return nil; +} + +- (void)uninstall { + if ([self supportsActiveProperty]) { + self.layoutConstraint.active = NO; + [self.firstViewAttribute.view.mas_installedConstraints removeObject:self]; + return; + } + + [self.installedView removeConstraint:self.layoutConstraint]; + self.layoutConstraint = nil; + self.installedView = nil; + + [self.firstViewAttribute.view.mas_installedConstraints removeObject:self]; +} + +@end diff --git a/CustomKeyboard/Masonry/Masonry/Masonry.h b/CustomKeyboard/Masonry/Masonry/Masonry.h new file mode 100755 index 0000000..d1bd579 --- /dev/null +++ b/CustomKeyboard/Masonry/Masonry/Masonry.h @@ -0,0 +1,29 @@ +// +// Masonry.h +// Masonry +// +// Created by Jonas Budelmann on 20/07/13. +// Copyright (c) 2013 cloudling. All rights reserved. +// + +#import + +//! Project version number for Masonry. +FOUNDATION_EXPORT double MasonryVersionNumber; + +//! Project version string for Masonry. +FOUNDATION_EXPORT const unsigned char MasonryVersionString[]; + +#import "MASUtilities.h" +#import "View+MASAdditions.h" +#import "View+MASShorthandAdditions.h" +#import "ViewController+MASAdditions.h" +#import "NSArray+MASAdditions.h" +#import "NSArray+MASShorthandAdditions.h" +#import "MASConstraint.h" +#import "MASCompositeConstraint.h" +#import "MASViewAttribute.h" +#import "MASViewConstraint.h" +#import "MASConstraintMaker.h" +#import "MASLayoutConstraint.h" +#import "NSLayoutConstraint+MASDebugAdditions.h" diff --git a/CustomKeyboard/Masonry/Masonry/NSArray+MASAdditions.h b/CustomKeyboard/Masonry/Masonry/NSArray+MASAdditions.h new file mode 100755 index 0000000..587618d --- /dev/null +++ b/CustomKeyboard/Masonry/Masonry/NSArray+MASAdditions.h @@ -0,0 +1,72 @@ +// +// NSArray+MASAdditions.h +// +// +// Created by Daniel Hammond on 11/26/13. +// +// + +#import "MASUtilities.h" +#import "MASConstraintMaker.h" +#import "MASViewAttribute.h" + +typedef NS_ENUM(NSUInteger, MASAxisType) { + MASAxisTypeHorizontal, + MASAxisTypeVertical +}; + +@interface NSArray (MASAdditions) + +/** + * Creates a MASConstraintMaker with each view in the callee. + * Any constraints defined are added to the view or the appropriate superview once the block has finished executing on each view + * + * @param block scope within which you can build up the constraints which you wish to apply to each view. + * + * @return Array of created MASConstraints + */ +- (NSArray *)mas_makeConstraints:(void (NS_NOESCAPE ^)(MASConstraintMaker *make))block; + +/** + * Creates a MASConstraintMaker with each view in the callee. + * Any constraints defined are added to each view or the appropriate superview once the block has finished executing on each view. + * If an existing constraint exists then it will be updated instead. + * + * @param block scope within which you can build up the constraints which you wish to apply to each view. + * + * @return Array of created/updated MASConstraints + */ +- (NSArray *)mas_updateConstraints:(void (NS_NOESCAPE ^)(MASConstraintMaker *make))block; + +/** + * Creates a MASConstraintMaker with each view in the callee. + * Any constraints defined are added to each view or the appropriate superview once the block has finished executing on each view. + * All constraints previously installed for the views will be removed. + * + * @param block scope within which you can build up the constraints which you wish to apply to each view. + * + * @return Array of created/updated MASConstraints + */ +- (NSArray *)mas_remakeConstraints:(void (NS_NOESCAPE ^)(MASConstraintMaker *make))block; + +/** + * distribute with fixed spacing + * + * @param axisType which axis to distribute items along + * @param fixedSpacing the spacing between each item + * @param leadSpacing the spacing before the first item and the container + * @param tailSpacing the spacing after the last item and the container + */ +- (void)mas_distributeViewsAlongAxis:(MASAxisType)axisType withFixedSpacing:(CGFloat)fixedSpacing leadSpacing:(CGFloat)leadSpacing tailSpacing:(CGFloat)tailSpacing; + +/** + * distribute with fixed item size + * + * @param axisType which axis to distribute items along + * @param fixedItemLength the fixed length of each item + * @param leadSpacing the spacing before the first item and the container + * @param tailSpacing the spacing after the last item and the container + */ +- (void)mas_distributeViewsAlongAxis:(MASAxisType)axisType withFixedItemLength:(CGFloat)fixedItemLength leadSpacing:(CGFloat)leadSpacing tailSpacing:(CGFloat)tailSpacing; + +@end diff --git a/CustomKeyboard/Masonry/Masonry/NSArray+MASAdditions.m b/CustomKeyboard/Masonry/Masonry/NSArray+MASAdditions.m new file mode 100755 index 0000000..831d8cd --- /dev/null +++ b/CustomKeyboard/Masonry/Masonry/NSArray+MASAdditions.m @@ -0,0 +1,162 @@ +// +// NSArray+MASAdditions.m +// +// +// Created by Daniel Hammond on 11/26/13. +// +// + +#import "NSArray+MASAdditions.h" +#import "View+MASAdditions.h" + +@implementation NSArray (MASAdditions) + +- (NSArray *)mas_makeConstraints:(void(^)(MASConstraintMaker *make))block { + NSMutableArray *constraints = [NSMutableArray array]; + for (MAS_VIEW *view in self) { + NSAssert([view isKindOfClass:[MAS_VIEW class]], @"All objects in the array must be views"); + [constraints addObjectsFromArray:[view mas_makeConstraints:block]]; + } + return constraints; +} + +- (NSArray *)mas_updateConstraints:(void(^)(MASConstraintMaker *make))block { + NSMutableArray *constraints = [NSMutableArray array]; + for (MAS_VIEW *view in self) { + NSAssert([view isKindOfClass:[MAS_VIEW class]], @"All objects in the array must be views"); + [constraints addObjectsFromArray:[view mas_updateConstraints:block]]; + } + return constraints; +} + +- (NSArray *)mas_remakeConstraints:(void(^)(MASConstraintMaker *make))block { + NSMutableArray *constraints = [NSMutableArray array]; + for (MAS_VIEW *view in self) { + NSAssert([view isKindOfClass:[MAS_VIEW class]], @"All objects in the array must be views"); + [constraints addObjectsFromArray:[view mas_remakeConstraints:block]]; + } + return constraints; +} + +- (void)mas_distributeViewsAlongAxis:(MASAxisType)axisType withFixedSpacing:(CGFloat)fixedSpacing leadSpacing:(CGFloat)leadSpacing tailSpacing:(CGFloat)tailSpacing { + if (self.count < 2) { + NSAssert(self.count>1,@"views to distribute need to bigger than one"); + return; + } + + MAS_VIEW *tempSuperView = [self mas_commonSuperviewOfViews]; + if (axisType == MASAxisTypeHorizontal) { + MAS_VIEW *prev; + for (int i = 0; i < self.count; i++) { + MAS_VIEW *v = self[i]; + [v mas_makeConstraints:^(MASConstraintMaker *make) { + if (prev) { + make.width.equalTo(prev); + make.left.equalTo(prev.mas_right).offset(fixedSpacing); + if (i == self.count - 1) {//last one + make.right.equalTo(tempSuperView).offset(-tailSpacing); + } + } + else {//first one + make.left.equalTo(tempSuperView).offset(leadSpacing); + } + + }]; + prev = v; + } + } + else { + MAS_VIEW *prev; + for (int i = 0; i < self.count; i++) { + MAS_VIEW *v = self[i]; + [v mas_makeConstraints:^(MASConstraintMaker *make) { + if (prev) { + make.height.equalTo(prev); + make.top.equalTo(prev.mas_bottom).offset(fixedSpacing); + if (i == self.count - 1) {//last one + make.bottom.equalTo(tempSuperView).offset(-tailSpacing); + } + } + else {//first one + make.top.equalTo(tempSuperView).offset(leadSpacing); + } + + }]; + prev = v; + } + } +} + +- (void)mas_distributeViewsAlongAxis:(MASAxisType)axisType withFixedItemLength:(CGFloat)fixedItemLength leadSpacing:(CGFloat)leadSpacing tailSpacing:(CGFloat)tailSpacing { + if (self.count < 2) { + NSAssert(self.count>1,@"views to distribute need to bigger than one"); + return; + } + + MAS_VIEW *tempSuperView = [self mas_commonSuperviewOfViews]; + if (axisType == MASAxisTypeHorizontal) { + MAS_VIEW *prev; + for (int i = 0; i < self.count; i++) { + MAS_VIEW *v = self[i]; + [v mas_makeConstraints:^(MASConstraintMaker *make) { + make.width.equalTo(@(fixedItemLength)); + if (prev) { + if (i == self.count - 1) {//last one + make.right.equalTo(tempSuperView).offset(-tailSpacing); + } + else { + CGFloat offset = (1-(i/((CGFloat)self.count-1)))*(fixedItemLength+leadSpacing)-i*tailSpacing/(((CGFloat)self.count-1)); + make.right.equalTo(tempSuperView).multipliedBy(i/((CGFloat)self.count-1)).with.offset(offset); + } + } + else {//first one + make.left.equalTo(tempSuperView).offset(leadSpacing); + } + }]; + prev = v; + } + } + else { + MAS_VIEW *prev; + for (int i = 0; i < self.count; i++) { + MAS_VIEW *v = self[i]; + [v mas_makeConstraints:^(MASConstraintMaker *make) { + make.height.equalTo(@(fixedItemLength)); + if (prev) { + if (i == self.count - 1) {//last one + make.bottom.equalTo(tempSuperView).offset(-tailSpacing); + } + else { + CGFloat offset = (1-(i/((CGFloat)self.count-1)))*(fixedItemLength+leadSpacing)-i*tailSpacing/(((CGFloat)self.count-1)); + make.bottom.equalTo(tempSuperView).multipliedBy(i/((CGFloat)self.count-1)).with.offset(offset); + } + } + else {//first one + make.top.equalTo(tempSuperView).offset(leadSpacing); + } + }]; + prev = v; + } + } +} + +- (MAS_VIEW *)mas_commonSuperviewOfViews +{ + MAS_VIEW *commonSuperview = nil; + MAS_VIEW *previousView = nil; + for (id object in self) { + if ([object isKindOfClass:[MAS_VIEW class]]) { + MAS_VIEW *view = (MAS_VIEW *)object; + if (previousView) { + commonSuperview = [view mas_closestCommonSuperview:commonSuperview]; + } else { + commonSuperview = view; + } + previousView = view; + } + } + NSAssert(commonSuperview, @"Can't constrain views that do not share a common superview. Make sure that all the views in this array have been added into the same view hierarchy."); + return commonSuperview; +} + +@end diff --git a/CustomKeyboard/Masonry/Masonry/NSArray+MASShorthandAdditions.h b/CustomKeyboard/Masonry/Masonry/NSArray+MASShorthandAdditions.h new file mode 100755 index 0000000..8b47369 --- /dev/null +++ b/CustomKeyboard/Masonry/Masonry/NSArray+MASShorthandAdditions.h @@ -0,0 +1,41 @@ +// +// NSArray+MASShorthandAdditions.h +// Masonry +// +// Created by Jonas Budelmann on 22/07/13. +// Copyright (c) 2013 Jonas Budelmann. All rights reserved. +// + +#import "NSArray+MASAdditions.h" + +#ifdef MAS_SHORTHAND + +/** + * Shorthand array additions without the 'mas_' prefixes, + * only enabled if MAS_SHORTHAND is defined + */ +@interface NSArray (MASShorthandAdditions) + +- (NSArray *)makeConstraints:(void(^)(MASConstraintMaker *make))block; +- (NSArray *)updateConstraints:(void(^)(MASConstraintMaker *make))block; +- (NSArray *)remakeConstraints:(void(^)(MASConstraintMaker *make))block; + +@end + +@implementation NSArray (MASShorthandAdditions) + +- (NSArray *)makeConstraints:(void(^)(MASConstraintMaker *))block { + return [self mas_makeConstraints:block]; +} + +- (NSArray *)updateConstraints:(void(^)(MASConstraintMaker *))block { + return [self mas_updateConstraints:block]; +} + +- (NSArray *)remakeConstraints:(void(^)(MASConstraintMaker *))block { + return [self mas_remakeConstraints:block]; +} + +@end + +#endif diff --git a/CustomKeyboard/Masonry/Masonry/NSLayoutConstraint+MASDebugAdditions.h b/CustomKeyboard/Masonry/Masonry/NSLayoutConstraint+MASDebugAdditions.h new file mode 100755 index 0000000..1279b4f --- /dev/null +++ b/CustomKeyboard/Masonry/Masonry/NSLayoutConstraint+MASDebugAdditions.h @@ -0,0 +1,16 @@ +// +// NSLayoutConstraint+MASDebugAdditions.h +// Masonry +// +// Created by Jonas Budelmann on 3/08/13. +// Copyright (c) 2013 Jonas Budelmann. All rights reserved. +// + +#import "MASUtilities.h" + +/** + * makes debug and log output of NSLayoutConstraints more readable + */ +@interface NSLayoutConstraint (MASDebugAdditions) + +@end diff --git a/CustomKeyboard/Masonry/Masonry/NSLayoutConstraint+MASDebugAdditions.m b/CustomKeyboard/Masonry/Masonry/NSLayoutConstraint+MASDebugAdditions.m new file mode 100755 index 0000000..ab539a2 --- /dev/null +++ b/CustomKeyboard/Masonry/Masonry/NSLayoutConstraint+MASDebugAdditions.m @@ -0,0 +1,146 @@ +// +// NSLayoutConstraint+MASDebugAdditions.m +// Masonry +// +// Created by Jonas Budelmann on 3/08/13. +// Copyright (c) 2013 Jonas Budelmann. All rights reserved. +// + +#import "NSLayoutConstraint+MASDebugAdditions.h" +#import "MASConstraint.h" +#import "MASLayoutConstraint.h" + +@implementation NSLayoutConstraint (MASDebugAdditions) + +#pragma mark - description maps + ++ (NSDictionary *)layoutRelationDescriptionsByValue { + static dispatch_once_t once; + static NSDictionary *descriptionMap; + dispatch_once(&once, ^{ + descriptionMap = @{ + @(NSLayoutRelationEqual) : @"==", + @(NSLayoutRelationGreaterThanOrEqual) : @">=", + @(NSLayoutRelationLessThanOrEqual) : @"<=", + }; + }); + return descriptionMap; +} + ++ (NSDictionary *)layoutAttributeDescriptionsByValue { + static dispatch_once_t once; + static NSDictionary *descriptionMap; + dispatch_once(&once, ^{ + descriptionMap = @{ + @(NSLayoutAttributeTop) : @"top", + @(NSLayoutAttributeLeft) : @"left", + @(NSLayoutAttributeBottom) : @"bottom", + @(NSLayoutAttributeRight) : @"right", + @(NSLayoutAttributeLeading) : @"leading", + @(NSLayoutAttributeTrailing) : @"trailing", + @(NSLayoutAttributeWidth) : @"width", + @(NSLayoutAttributeHeight) : @"height", + @(NSLayoutAttributeCenterX) : @"centerX", + @(NSLayoutAttributeCenterY) : @"centerY", + @(NSLayoutAttributeBaseline) : @"baseline", + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + @(NSLayoutAttributeFirstBaseline) : @"firstBaseline", + @(NSLayoutAttributeLastBaseline) : @"lastBaseline", +#endif + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) + @(NSLayoutAttributeLeftMargin) : @"leftMargin", + @(NSLayoutAttributeRightMargin) : @"rightMargin", + @(NSLayoutAttributeTopMargin) : @"topMargin", + @(NSLayoutAttributeBottomMargin) : @"bottomMargin", + @(NSLayoutAttributeLeadingMargin) : @"leadingMargin", + @(NSLayoutAttributeTrailingMargin) : @"trailingMargin", + @(NSLayoutAttributeCenterXWithinMargins) : @"centerXWithinMargins", + @(NSLayoutAttributeCenterYWithinMargins) : @"centerYWithinMargins", +#endif + + }; + + }); + return descriptionMap; +} + + ++ (NSDictionary *)layoutPriorityDescriptionsByValue { + static dispatch_once_t once; + static NSDictionary *descriptionMap; + dispatch_once(&once, ^{ +#if TARGET_OS_IPHONE || TARGET_OS_TV + descriptionMap = @{ + @(MASLayoutPriorityDefaultHigh) : @"high", + @(MASLayoutPriorityDefaultLow) : @"low", + @(MASLayoutPriorityDefaultMedium) : @"medium", + @(MASLayoutPriorityRequired) : @"required", + @(MASLayoutPriorityFittingSizeLevel) : @"fitting size", + }; +#elif TARGET_OS_MAC + descriptionMap = @{ + @(MASLayoutPriorityDefaultHigh) : @"high", + @(MASLayoutPriorityDragThatCanResizeWindow) : @"drag can resize window", + @(MASLayoutPriorityDefaultMedium) : @"medium", + @(MASLayoutPriorityWindowSizeStayPut) : @"window size stay put", + @(MASLayoutPriorityDragThatCannotResizeWindow) : @"drag cannot resize window", + @(MASLayoutPriorityDefaultLow) : @"low", + @(MASLayoutPriorityFittingSizeCompression) : @"fitting size", + @(MASLayoutPriorityRequired) : @"required", + }; +#endif + }); + return descriptionMap; +} + +#pragma mark - description override + ++ (NSString *)descriptionForObject:(id)obj { + if ([obj respondsToSelector:@selector(mas_key)] && [obj mas_key]) { + return [NSString stringWithFormat:@"%@:%@", [obj class], [obj mas_key]]; + } + return [NSString stringWithFormat:@"%@:%p", [obj class], obj]; +} + +- (NSString *)description { + NSMutableString *description = [[NSMutableString alloc] initWithString:@"<"]; + + [description appendString:[self.class descriptionForObject:self]]; + + [description appendFormat:@" %@", [self.class descriptionForObject:self.firstItem]]; + if (self.firstAttribute != NSLayoutAttributeNotAnAttribute) { + [description appendFormat:@".%@", self.class.layoutAttributeDescriptionsByValue[@(self.firstAttribute)]]; + } + + [description appendFormat:@" %@", self.class.layoutRelationDescriptionsByValue[@(self.relation)]]; + + if (self.secondItem) { + [description appendFormat:@" %@", [self.class descriptionForObject:self.secondItem]]; + } + if (self.secondAttribute != NSLayoutAttributeNotAnAttribute) { + [description appendFormat:@".%@", self.class.layoutAttributeDescriptionsByValue[@(self.secondAttribute)]]; + } + + if (self.multiplier != 1) { + [description appendFormat:@" * %g", self.multiplier]; + } + + if (self.secondAttribute == NSLayoutAttributeNotAnAttribute) { + [description appendFormat:@" %g", self.constant]; + } else { + if (self.constant) { + [description appendFormat:@" %@ %g", (self.constant < 0 ? @"-" : @"+"), ABS(self.constant)]; + } + } + + if (self.priority != MASLayoutPriorityRequired) { + [description appendFormat:@" ^%@", self.class.layoutPriorityDescriptionsByValue[@(self.priority)] ?: [NSNumber numberWithDouble:self.priority]]; + } + + [description appendString:@">"]; + return description; +} + +@end diff --git a/CustomKeyboard/Masonry/Masonry/View+MASAdditions.h b/CustomKeyboard/Masonry/Masonry/View+MASAdditions.h new file mode 100755 index 0000000..f7343d2 --- /dev/null +++ b/CustomKeyboard/Masonry/Masonry/View+MASAdditions.h @@ -0,0 +1,111 @@ +// +// UIView+MASAdditions.h +// Masonry +// +// Created by Jonas Budelmann on 20/07/13. +// Copyright (c) 2013 cloudling. All rights reserved. +// + +#import "MASUtilities.h" +#import "MASConstraintMaker.h" +#import "MASViewAttribute.h" + +/** + * Provides constraint maker block + * and convience methods for creating MASViewAttribute which are view + NSLayoutAttribute pairs + */ +@interface MAS_VIEW (MASAdditions) + +/** + * following properties return a new MASViewAttribute with current view and appropriate NSLayoutAttribute + */ +@property (nonatomic, strong, readonly) MASViewAttribute *mas_left; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_top; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_right; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_bottom; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_leading; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_trailing; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_width; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_height; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_centerX; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_centerY; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_baseline; +@property (nonatomic, strong, readonly) MASViewAttribute *(^mas_attribute)(NSLayoutAttribute attr); + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + +@property (nonatomic, strong, readonly) MASViewAttribute *mas_firstBaseline; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_lastBaseline; + +#endif + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) + +@property (nonatomic, strong, readonly) MASViewAttribute *mas_leftMargin; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_rightMargin; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_topMargin; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_bottomMargin; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_leadingMargin; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_trailingMargin; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_centerXWithinMargins; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_centerYWithinMargins; + +#endif + +#if (__IPHONE_OS_VERSION_MAX_ALLOWED >= 110000) || (__TV_OS_VERSION_MAX_ALLOWED >= 110000) + +@property (nonatomic, strong, readonly) MASViewAttribute *mas_safeAreaLayoutGuide API_AVAILABLE(ios(11.0),tvos(11.0)); +@property (nonatomic, strong, readonly) MASViewAttribute *mas_safeAreaLayoutGuideTop API_AVAILABLE(ios(11.0),tvos(11.0)); +@property (nonatomic, strong, readonly) MASViewAttribute *mas_safeAreaLayoutGuideBottom API_AVAILABLE(ios(11.0),tvos(11.0)); +@property (nonatomic, strong, readonly) MASViewAttribute *mas_safeAreaLayoutGuideLeft API_AVAILABLE(ios(11.0),tvos(11.0)); +@property (nonatomic, strong, readonly) MASViewAttribute *mas_safeAreaLayoutGuideRight API_AVAILABLE(ios(11.0),tvos(11.0)); + +#endif + +/** + * a key to associate with this view + */ +@property (nonatomic, strong) id mas_key; + +/** + * Finds the closest common superview between this view and another view + * + * @param view other view + * + * @return returns nil if common superview could not be found + */ +- (instancetype)mas_closestCommonSuperview:(MAS_VIEW *)view; + +/** + * Creates a MASConstraintMaker with the callee view. + * Any constraints defined are added to the view or the appropriate superview once the block has finished executing + * + * @param block scope within which you can build up the constraints which you wish to apply to the view. + * + * @return Array of created MASConstraints + */ +- (NSArray *)mas_makeConstraints:(void(NS_NOESCAPE ^)(MASConstraintMaker *make))block; + +/** + * Creates a MASConstraintMaker with the callee view. + * Any constraints defined are added to the view or the appropriate superview once the block has finished executing. + * If an existing constraint exists then it will be updated instead. + * + * @param block scope within which you can build up the constraints which you wish to apply to the view. + * + * @return Array of created/updated MASConstraints + */ +- (NSArray *)mas_updateConstraints:(void(NS_NOESCAPE ^)(MASConstraintMaker *make))block; + +/** + * Creates a MASConstraintMaker with the callee view. + * Any constraints defined are added to the view or the appropriate superview once the block has finished executing. + * All constraints previously installed for the view will be removed. + * + * @param block scope within which you can build up the constraints which you wish to apply to the view. + * + * @return Array of created/updated MASConstraints + */ +- (NSArray *)mas_remakeConstraints:(void(NS_NOESCAPE ^)(MASConstraintMaker *make))block; + +@end diff --git a/CustomKeyboard/Masonry/Masonry/View+MASAdditions.m b/CustomKeyboard/Masonry/Masonry/View+MASAdditions.m new file mode 100755 index 0000000..4fa07b4 --- /dev/null +++ b/CustomKeyboard/Masonry/Masonry/View+MASAdditions.m @@ -0,0 +1,186 @@ +// +// UIView+MASAdditions.m +// Masonry +// +// Created by Jonas Budelmann on 20/07/13. +// Copyright (c) 2013 cloudling. All rights reserved. +// + +#import "View+MASAdditions.h" +#import + +@implementation MAS_VIEW (MASAdditions) + +- (NSArray *)mas_makeConstraints:(void(^)(MASConstraintMaker *))block { + self.translatesAutoresizingMaskIntoConstraints = NO; + MASConstraintMaker *constraintMaker = [[MASConstraintMaker alloc] initWithView:self]; + block(constraintMaker); + return [constraintMaker install]; +} + +- (NSArray *)mas_updateConstraints:(void(^)(MASConstraintMaker *))block { + self.translatesAutoresizingMaskIntoConstraints = NO; + MASConstraintMaker *constraintMaker = [[MASConstraintMaker alloc] initWithView:self]; + constraintMaker.updateExisting = YES; + block(constraintMaker); + return [constraintMaker install]; +} + +- (NSArray *)mas_remakeConstraints:(void(^)(MASConstraintMaker *make))block { + self.translatesAutoresizingMaskIntoConstraints = NO; + MASConstraintMaker *constraintMaker = [[MASConstraintMaker alloc] initWithView:self]; + constraintMaker.removeExisting = YES; + block(constraintMaker); + return [constraintMaker install]; +} + +#pragma mark - NSLayoutAttribute properties + +- (MASViewAttribute *)mas_left { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeLeft]; +} + +- (MASViewAttribute *)mas_top { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeTop]; +} + +- (MASViewAttribute *)mas_right { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeRight]; +} + +- (MASViewAttribute *)mas_bottom { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeBottom]; +} + +- (MASViewAttribute *)mas_leading { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeLeading]; +} + +- (MASViewAttribute *)mas_trailing { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeTrailing]; +} + +- (MASViewAttribute *)mas_width { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeWidth]; +} + +- (MASViewAttribute *)mas_height { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeHeight]; +} + +- (MASViewAttribute *)mas_centerX { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeCenterX]; +} + +- (MASViewAttribute *)mas_centerY { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeCenterY]; +} + +- (MASViewAttribute *)mas_baseline { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeBaseline]; +} + +- (MASViewAttribute *(^)(NSLayoutAttribute))mas_attribute +{ + return ^(NSLayoutAttribute attr) { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:attr]; + }; +} + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + +- (MASViewAttribute *)mas_firstBaseline { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeFirstBaseline]; +} +- (MASViewAttribute *)mas_lastBaseline { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeLastBaseline]; +} + +#endif + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) + +- (MASViewAttribute *)mas_leftMargin { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeLeftMargin]; +} + +- (MASViewAttribute *)mas_rightMargin { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeRightMargin]; +} + +- (MASViewAttribute *)mas_topMargin { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeTopMargin]; +} + +- (MASViewAttribute *)mas_bottomMargin { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeBottomMargin]; +} + +- (MASViewAttribute *)mas_leadingMargin { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeLeadingMargin]; +} + +- (MASViewAttribute *)mas_trailingMargin { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeTrailingMargin]; +} + +- (MASViewAttribute *)mas_centerXWithinMargins { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeCenterXWithinMargins]; +} + +- (MASViewAttribute *)mas_centerYWithinMargins { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeCenterYWithinMargins]; +} + +#endif + +#if (__IPHONE_OS_VERSION_MAX_ALLOWED >= 110000) || (__TV_OS_VERSION_MAX_ALLOWED >= 110000) + +- (MASViewAttribute *)mas_safeAreaLayoutGuide { + return [[MASViewAttribute alloc] initWithView:self item:self.safeAreaLayoutGuide layoutAttribute:NSLayoutAttributeBottom]; +} +- (MASViewAttribute *)mas_safeAreaLayoutGuideTop { + return [[MASViewAttribute alloc] initWithView:self item:self.safeAreaLayoutGuide layoutAttribute:NSLayoutAttributeTop]; +} +- (MASViewAttribute *)mas_safeAreaLayoutGuideBottom { + return [[MASViewAttribute alloc] initWithView:self item:self.safeAreaLayoutGuide layoutAttribute:NSLayoutAttributeBottom]; +} +- (MASViewAttribute *)mas_safeAreaLayoutGuideLeft { + return [[MASViewAttribute alloc] initWithView:self item:self.safeAreaLayoutGuide layoutAttribute:NSLayoutAttributeLeft]; +} +- (MASViewAttribute *)mas_safeAreaLayoutGuideRight { + return [[MASViewAttribute alloc] initWithView:self item:self.safeAreaLayoutGuide layoutAttribute:NSLayoutAttributeRight]; +} + +#endif + +#pragma mark - associated properties + +- (id)mas_key { + return objc_getAssociatedObject(self, @selector(mas_key)); +} + +- (void)setMas_key:(id)key { + objc_setAssociatedObject(self, @selector(mas_key), key, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#pragma mark - heirachy + +- (instancetype)mas_closestCommonSuperview:(MAS_VIEW *)view { + MAS_VIEW *closestCommonSuperview = nil; + + MAS_VIEW *secondViewSuperview = view; + while (!closestCommonSuperview && secondViewSuperview) { + MAS_VIEW *firstViewSuperview = self; + while (!closestCommonSuperview && firstViewSuperview) { + if (secondViewSuperview == firstViewSuperview) { + closestCommonSuperview = secondViewSuperview; + } + firstViewSuperview = firstViewSuperview.superview; + } + secondViewSuperview = secondViewSuperview.superview; + } + return closestCommonSuperview; +} + +@end diff --git a/CustomKeyboard/Masonry/Masonry/View+MASShorthandAdditions.h b/CustomKeyboard/Masonry/Masonry/View+MASShorthandAdditions.h new file mode 100755 index 0000000..1c19a94 --- /dev/null +++ b/CustomKeyboard/Masonry/Masonry/View+MASShorthandAdditions.h @@ -0,0 +1,133 @@ +// +// UIView+MASShorthandAdditions.h +// Masonry +// +// Created by Jonas Budelmann on 22/07/13. +// Copyright (c) 2013 Jonas Budelmann. All rights reserved. +// + +#import "View+MASAdditions.h" + +#ifdef MAS_SHORTHAND + +/** + * Shorthand view additions without the 'mas_' prefixes, + * only enabled if MAS_SHORTHAND is defined + */ +@interface MAS_VIEW (MASShorthandAdditions) + +@property (nonatomic, strong, readonly) MASViewAttribute *left; +@property (nonatomic, strong, readonly) MASViewAttribute *top; +@property (nonatomic, strong, readonly) MASViewAttribute *right; +@property (nonatomic, strong, readonly) MASViewAttribute *bottom; +@property (nonatomic, strong, readonly) MASViewAttribute *leading; +@property (nonatomic, strong, readonly) MASViewAttribute *trailing; +@property (nonatomic, strong, readonly) MASViewAttribute *width; +@property (nonatomic, strong, readonly) MASViewAttribute *height; +@property (nonatomic, strong, readonly) MASViewAttribute *centerX; +@property (nonatomic, strong, readonly) MASViewAttribute *centerY; +@property (nonatomic, strong, readonly) MASViewAttribute *baseline; +@property (nonatomic, strong, readonly) MASViewAttribute *(^attribute)(NSLayoutAttribute attr); + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + +@property (nonatomic, strong, readonly) MASViewAttribute *firstBaseline; +@property (nonatomic, strong, readonly) MASViewAttribute *lastBaseline; + +#endif + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) + +@property (nonatomic, strong, readonly) MASViewAttribute *leftMargin; +@property (nonatomic, strong, readonly) MASViewAttribute *rightMargin; +@property (nonatomic, strong, readonly) MASViewAttribute *topMargin; +@property (nonatomic, strong, readonly) MASViewAttribute *bottomMargin; +@property (nonatomic, strong, readonly) MASViewAttribute *leadingMargin; +@property (nonatomic, strong, readonly) MASViewAttribute *trailingMargin; +@property (nonatomic, strong, readonly) MASViewAttribute *centerXWithinMargins; +@property (nonatomic, strong, readonly) MASViewAttribute *centerYWithinMargins; + +#endif + +#if (__IPHONE_OS_VERSION_MAX_ALLOWED >= 110000) || (__TV_OS_VERSION_MAX_ALLOWED >= 110000) + +@property (nonatomic, strong, readonly) MASViewAttribute *safeAreaLayoutGuideTop API_AVAILABLE(ios(11.0),tvos(11.0)); +@property (nonatomic, strong, readonly) MASViewAttribute *safeAreaLayoutGuideBottom API_AVAILABLE(ios(11.0),tvos(11.0)); +@property (nonatomic, strong, readonly) MASViewAttribute *safeAreaLayoutGuideLeft API_AVAILABLE(ios(11.0),tvos(11.0)); +@property (nonatomic, strong, readonly) MASViewAttribute *safeAreaLayoutGuideRight API_AVAILABLE(ios(11.0),tvos(11.0)); + +#endif + +- (NSArray *)makeConstraints:(void(^)(MASConstraintMaker *make))block; +- (NSArray *)updateConstraints:(void(^)(MASConstraintMaker *make))block; +- (NSArray *)remakeConstraints:(void(^)(MASConstraintMaker *make))block; + +@end + +#define MAS_ATTR_FORWARD(attr) \ +- (MASViewAttribute *)attr { \ + return [self mas_##attr]; \ +} + +@implementation MAS_VIEW (MASShorthandAdditions) + +MAS_ATTR_FORWARD(top); +MAS_ATTR_FORWARD(left); +MAS_ATTR_FORWARD(bottom); +MAS_ATTR_FORWARD(right); +MAS_ATTR_FORWARD(leading); +MAS_ATTR_FORWARD(trailing); +MAS_ATTR_FORWARD(width); +MAS_ATTR_FORWARD(height); +MAS_ATTR_FORWARD(centerX); +MAS_ATTR_FORWARD(centerY); +MAS_ATTR_FORWARD(baseline); + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + +MAS_ATTR_FORWARD(firstBaseline); +MAS_ATTR_FORWARD(lastBaseline); + +#endif + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) + +MAS_ATTR_FORWARD(leftMargin); +MAS_ATTR_FORWARD(rightMargin); +MAS_ATTR_FORWARD(topMargin); +MAS_ATTR_FORWARD(bottomMargin); +MAS_ATTR_FORWARD(leadingMargin); +MAS_ATTR_FORWARD(trailingMargin); +MAS_ATTR_FORWARD(centerXWithinMargins); +MAS_ATTR_FORWARD(centerYWithinMargins); + +#endif + +#if (__IPHONE_OS_VERSION_MAX_ALLOWED >= 110000) || (__TV_OS_VERSION_MAX_ALLOWED >= 110000) + +MAS_ATTR_FORWARD(safeAreaLayoutGuideTop); +MAS_ATTR_FORWARD(safeAreaLayoutGuideBottom); +MAS_ATTR_FORWARD(safeAreaLayoutGuideLeft); +MAS_ATTR_FORWARD(safeAreaLayoutGuideRight); + +#endif + +- (MASViewAttribute *(^)(NSLayoutAttribute))attribute { + return [self mas_attribute]; +} + +- (NSArray *)makeConstraints:(void(NS_NOESCAPE ^)(MASConstraintMaker *))block { + return [self mas_makeConstraints:block]; +} + +- (NSArray *)updateConstraints:(void(NS_NOESCAPE ^)(MASConstraintMaker *))block { + return [self mas_updateConstraints:block]; +} + +- (NSArray *)remakeConstraints:(void(NS_NOESCAPE ^)(MASConstraintMaker *))block { + return [self mas_remakeConstraints:block]; +} + +@end + +#endif diff --git a/CustomKeyboard/Masonry/Masonry/ViewController+MASAdditions.h b/CustomKeyboard/Masonry/Masonry/ViewController+MASAdditions.h new file mode 100755 index 0000000..79fd1fa --- /dev/null +++ b/CustomKeyboard/Masonry/Masonry/ViewController+MASAdditions.h @@ -0,0 +1,30 @@ +// +// UIViewController+MASAdditions.h +// Masonry +// +// Created by Craig Siemens on 2015-06-23. +// +// + +#import "MASUtilities.h" +#import "MASConstraintMaker.h" +#import "MASViewAttribute.h" + +#ifdef MAS_VIEW_CONTROLLER + +@interface MAS_VIEW_CONTROLLER (MASAdditions) + +/** + * following properties return a new MASViewAttribute with appropriate UILayoutGuide and NSLayoutAttribute + */ +@property (nonatomic, strong, readonly) MASViewAttribute *mas_topLayoutGuide; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_bottomLayoutGuide; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_topLayoutGuideTop; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_topLayoutGuideBottom; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_bottomLayoutGuideTop; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_bottomLayoutGuideBottom; + + +@end + +#endif diff --git a/CustomKeyboard/Masonry/Masonry/ViewController+MASAdditions.m b/CustomKeyboard/Masonry/Masonry/ViewController+MASAdditions.m new file mode 100755 index 0000000..2f5139f --- /dev/null +++ b/CustomKeyboard/Masonry/Masonry/ViewController+MASAdditions.m @@ -0,0 +1,39 @@ +// +// UIViewController+MASAdditions.m +// Masonry +// +// Created by Craig Siemens on 2015-06-23. +// +// + +#import "ViewController+MASAdditions.h" + +#ifdef MAS_VIEW_CONTROLLER + +@implementation MAS_VIEW_CONTROLLER (MASAdditions) + +- (MASViewAttribute *)mas_topLayoutGuide { + return [[MASViewAttribute alloc] initWithView:self.view item:self.topLayoutGuide layoutAttribute:NSLayoutAttributeBottom]; +} +- (MASViewAttribute *)mas_topLayoutGuideTop { + return [[MASViewAttribute alloc] initWithView:self.view item:self.topLayoutGuide layoutAttribute:NSLayoutAttributeTop]; +} +- (MASViewAttribute *)mas_topLayoutGuideBottom { + return [[MASViewAttribute alloc] initWithView:self.view item:self.topLayoutGuide layoutAttribute:NSLayoutAttributeBottom]; +} + +- (MASViewAttribute *)mas_bottomLayoutGuide { + return [[MASViewAttribute alloc] initWithView:self.view item:self.bottomLayoutGuide layoutAttribute:NSLayoutAttributeTop]; +} +- (MASViewAttribute *)mas_bottomLayoutGuideTop { + return [[MASViewAttribute alloc] initWithView:self.view item:self.bottomLayoutGuide layoutAttribute:NSLayoutAttributeTop]; +} +- (MASViewAttribute *)mas_bottomLayoutGuideBottom { + return [[MASViewAttribute alloc] initWithView:self.view item:self.bottomLayoutGuide layoutAttribute:NSLayoutAttributeBottom]; +} + + + +@end + +#endif diff --git a/CustomKeyboard/Masonry/README.md b/CustomKeyboard/Masonry/README.md new file mode 100755 index 0000000..d428657 --- /dev/null +++ b/CustomKeyboard/Masonry/README.md @@ -0,0 +1,415 @@ +# Masonry [![Build Status](https://travis-ci.org/SnapKit/Masonry.svg?branch=master)](https://travis-ci.org/SnapKit/Masonry) [![Coverage Status](https://img.shields.io/coveralls/SnapKit/Masonry.svg?style=flat-square)](https://coveralls.io/r/SnapKit/Masonry) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) ![Pod Version](https://img.shields.io/cocoapods/v/Masonry.svg?style=flat) + +**Masonry is still actively maintained, we are committed to fixing bugs and merging good quality PRs from the wider community. However if you're using Swift in your project, we recommend using [SnapKit](https://github.com/SnapKit/SnapKit) as it provides better type safety with a simpler API.** + +Masonry is a light-weight layout framework which wraps AutoLayout with a nicer syntax. Masonry has its own layout DSL which provides a chainable way of describing your NSLayoutConstraints which results in layout code that is more concise and readable. +Masonry supports iOS and Mac OS X. + +For examples take a look at the **Masonry iOS Examples** project in the Masonry workspace. You will need to run `pod install` after downloading. + +## What's wrong with NSLayoutConstraints? + +Under the hood Auto Layout is a powerful and flexible way of organising and laying out your views. However creating constraints from code is verbose and not very descriptive. +Imagine a simple example in which you want to have a view fill its superview but inset by 10 pixels on every side +```obj-c +UIView *superview = self.view; + +UIView *view1 = [[UIView alloc] init]; +view1.translatesAutoresizingMaskIntoConstraints = NO; +view1.backgroundColor = [UIColor greenColor]; +[superview addSubview:view1]; + +UIEdgeInsets padding = UIEdgeInsetsMake(10, 10, 10, 10); + +[superview addConstraints:@[ + + //view1 constraints + [NSLayoutConstraint constraintWithItem:view1 + attribute:NSLayoutAttributeTop + relatedBy:NSLayoutRelationEqual + toItem:superview + attribute:NSLayoutAttributeTop + multiplier:1.0 + constant:padding.top], + + [NSLayoutConstraint constraintWithItem:view1 + attribute:NSLayoutAttributeLeft + relatedBy:NSLayoutRelationEqual + toItem:superview + attribute:NSLayoutAttributeLeft + multiplier:1.0 + constant:padding.left], + + [NSLayoutConstraint constraintWithItem:view1 + attribute:NSLayoutAttributeBottom + relatedBy:NSLayoutRelationEqual + toItem:superview + attribute:NSLayoutAttributeBottom + multiplier:1.0 + constant:-padding.bottom], + + [NSLayoutConstraint constraintWithItem:view1 + attribute:NSLayoutAttributeRight + relatedBy:NSLayoutRelationEqual + toItem:superview + attribute:NSLayoutAttributeRight + multiplier:1 + constant:-padding.right], + + ]]; +``` +Even with such a simple example the code needed is quite verbose and quickly becomes unreadable when you have more than 2 or 3 views. +Another option is to use Visual Format Language (VFL), which is a bit less long winded. +However the ASCII type syntax has its own pitfalls and its also a bit harder to animate as `NSLayoutConstraint constraintsWithVisualFormat:` returns an array. + +## Prepare to meet your Maker! + +Heres the same constraints created using MASConstraintMaker + +```obj-c +UIEdgeInsets padding = UIEdgeInsetsMake(10, 10, 10, 10); + +[view1 mas_makeConstraints:^(MASConstraintMaker *make) { + make.top.equalTo(superview.mas_top).with.offset(padding.top); //with is an optional semantic filler + make.left.equalTo(superview.mas_left).with.offset(padding.left); + make.bottom.equalTo(superview.mas_bottom).with.offset(-padding.bottom); + make.right.equalTo(superview.mas_right).with.offset(-padding.right); +}]; +``` +Or even shorter + +```obj-c +[view1 mas_makeConstraints:^(MASConstraintMaker *make) { + make.edges.equalTo(superview).with.insets(padding); +}]; +``` + +Also note in the first example we had to add the constraints to the superview `[superview addConstraints:...`. +Masonry however will automagically add constraints to the appropriate view. + +Masonry will also call `view1.translatesAutoresizingMaskIntoConstraints = NO;` for you. + +## Not all things are created equal + +> `.equalTo` equivalent to **NSLayoutRelationEqual** + +> `.lessThanOrEqualTo` equivalent to **NSLayoutRelationLessThanOrEqual** + +> `.greaterThanOrEqualTo` equivalent to **NSLayoutRelationGreaterThanOrEqual** + +These three equality constraints accept one argument which can be any of the following: + +#### 1. MASViewAttribute + +```obj-c +make.centerX.lessThanOrEqualTo(view2.mas_left); +``` + +MASViewAttribute | NSLayoutAttribute +------------------------- | -------------------------- +view.mas_left | NSLayoutAttributeLeft +view.mas_right | NSLayoutAttributeRight +view.mas_top | NSLayoutAttributeTop +view.mas_bottom | NSLayoutAttributeBottom +view.mas_leading | NSLayoutAttributeLeading +view.mas_trailing | NSLayoutAttributeTrailing +view.mas_width | NSLayoutAttributeWidth +view.mas_height | NSLayoutAttributeHeight +view.mas_centerX | NSLayoutAttributeCenterX +view.mas_centerY | NSLayoutAttributeCenterY +view.mas_baseline | NSLayoutAttributeBaseline + +#### 2. UIView/NSView + +if you want view.left to be greater than or equal to label.left : +```obj-c +//these two constraints are exactly the same +make.left.greaterThanOrEqualTo(label); +make.left.greaterThanOrEqualTo(label.mas_left); +``` + +#### 3. NSNumber + +Auto Layout allows width and height to be set to constant values. +if you want to set view to have a minimum and maximum width you could pass a number to the equality blocks: +```obj-c +//width >= 200 && width <= 400 +make.width.greaterThanOrEqualTo(@200); +make.width.lessThanOrEqualTo(@400) +``` + +However Auto Layout does not allow alignment attributes such as left, right, centerY etc to be set to constant values. +So if you pass a NSNumber for these attributes Masonry will turn these into constraints relative to the view’s superview ie: +```obj-c +//creates view.left = view.superview.left + 10 +make.left.lessThanOrEqualTo(@10) +``` + +Instead of using NSNumber, you can use primitives and structs to build your constraints, like so: +```obj-c +make.top.mas_equalTo(42); +make.height.mas_equalTo(20); +make.size.mas_equalTo(CGSizeMake(50, 100)); +make.edges.mas_equalTo(UIEdgeInsetsMake(10, 0, 10, 0)); +make.left.mas_equalTo(view).mas_offset(UIEdgeInsetsMake(10, 0, 10, 0)); +``` + +By default, macros which support [autoboxing](https://en.wikipedia.org/wiki/Autoboxing#Autoboxing) are prefixed with `mas_`. Unprefixed versions are available by defining `MAS_SHORTHAND_GLOBALS` before importing Masonry. + +#### 4. NSArray + +An array of a mixture of any of the previous types +```obj-c +make.height.equalTo(@[view1.mas_height, view2.mas_height]); +make.height.equalTo(@[view1, view2]); +make.left.equalTo(@[view1, @100, view3.right]); +```` + +## Learn to prioritize + +> `.priority` allows you to specify an exact priority + +> `.priorityHigh` equivalent to **UILayoutPriorityDefaultHigh** + +> `.priorityMedium` is half way between high and low + +> `.priorityLow` equivalent to **UILayoutPriorityDefaultLow** + +Priorities are can be tacked on to the end of a constraint chain like so: +```obj-c +make.left.greaterThanOrEqualTo(label.mas_left).with.priorityLow(); + +make.top.equalTo(label.mas_top).with.priority(600); +``` + +## Composition, composition, composition + +Masonry also gives you a few convenience methods which create multiple constraints at the same time. These are called MASCompositeConstraints + +#### edges + +```obj-c +// make top, left, bottom, right equal view2 +make.edges.equalTo(view2); + +// make top = superview.top + 5, left = superview.left + 10, +// bottom = superview.bottom - 15, right = superview.right - 20 +make.edges.equalTo(superview).insets(UIEdgeInsetsMake(5, 10, 15, 20)) +``` + +#### size + +```obj-c +// make width and height greater than or equal to titleLabel +make.size.greaterThanOrEqualTo(titleLabel) + +// make width = superview.width + 100, height = superview.height - 50 +make.size.equalTo(superview).sizeOffset(CGSizeMake(100, -50)) +``` + +#### center +```obj-c +// make centerX and centerY = button1 +make.center.equalTo(button1) + +// make centerX = superview.centerX - 5, centerY = superview.centerY + 10 +make.center.equalTo(superview).centerOffset(CGPointMake(-5, 10)) +``` + +You can chain view attributes for increased readability: + +```obj-c +// All edges but the top should equal those of the superview +make.left.right.and.bottom.equalTo(superview); +make.top.equalTo(otherView); +``` + +## Hold on for dear life + +Sometimes you need modify existing constraints in order to animate or remove/replace constraints. +In Masonry there are a few different approaches to updating constraints. + +#### 1. References +You can hold on to a reference of a particular constraint by assigning the result of a constraint make expression to a local variable or a class property. +You could also reference multiple constraints by storing them away in an array. + +```obj-c +// in public/private interface +@property (nonatomic, strong) MASConstraint *topConstraint; + +... + +// when making constraints +[view1 mas_makeConstraints:^(MASConstraintMaker *make) { + self.topConstraint = make.top.equalTo(superview.mas_top).with.offset(padding.top); + make.left.equalTo(superview.mas_left).with.offset(padding.left); +}]; + +... +// then later you can call +[self.topConstraint uninstall]; +``` + +#### 2. mas_updateConstraints +Alternatively if you are only updating the constant value of the constraint you can use the convience method `mas_updateConstraints` instead of `mas_makeConstraints` + +```obj-c +// this is Apple's recommended place for adding/updating constraints +// this method can get called multiple times in response to setNeedsUpdateConstraints +// which can be called by UIKit internally or in your code if you need to trigger an update to your constraints +- (void)updateConstraints { + [self.growingButton mas_updateConstraints:^(MASConstraintMaker *make) { + make.center.equalTo(self); + make.width.equalTo(@(self.buttonSize.width)).priorityLow(); + make.height.equalTo(@(self.buttonSize.height)).priorityLow(); + make.width.lessThanOrEqualTo(self); + make.height.lessThanOrEqualTo(self); + }]; + + //according to apple super should be called at end of method + [super updateConstraints]; +} +``` + +### 3. mas_remakeConstraints +`mas_updateConstraints` is useful for updating a set of constraints, but doing anything beyond updating constant values can get exhausting. That's where `mas_remakeConstraints` comes in. + +`mas_remakeConstraints` is similar to `mas_updateConstraints`, but instead of updating constant values, it will remove all of its constraints before installing them again. This lets you provide different constraints without having to keep around references to ones which you want to remove. + +```obj-c +- (void)changeButtonPosition { + [self.button mas_remakeConstraints:^(MASConstraintMaker *make) { + make.size.equalTo(self.buttonSize); + + if (topLeft) { + make.top.and.left.offset(10); + } else { + make.bottom.and.right.offset(-10); + } + }]; +} +``` + +You can find more detailed examples of all three approaches in the **Masonry iOS Examples** project. + +## When the ^&*!@ hits the fan! + +Laying out your views doesn't always goto plan. So when things literally go pear shaped, you don't want to be looking at console output like this: + +```obj-c +Unable to simultaneously satisfy constraints.....blah blah blah.... +( + "=5000)]>", + "", + "", + "" +) + +Will attempt to recover by breaking constraint +=5000)]> +``` + +Masonry adds a category to NSLayoutConstraint which overrides the default implementation of `- (NSString *)description`. +Now you can give meaningful names to views and constraints, and also easily pick out the constraints created by Masonry. + +which means your console output can now look like this: + +```obj-c +Unable to simultaneously satisfy constraints......blah blah blah.... +( + "", + "= 5000>", + "", + "" +) + +Will attempt to recover by breaking constraint += 5000> +``` + +For an example of how to set this up take a look at the **Masonry iOS Examples** project in the Masonry workspace. + +## Where should I create my constraints? + +```objc +@implementation DIYCustomView + +- (id)init { + self = [super init]; + if (!self) return nil; + + // --- Create your views here --- + self.button = [[UIButton alloc] init]; + + return self; +} + +// tell UIKit that you are using AutoLayout ++ (BOOL)requiresConstraintBasedLayout { + return YES; +} + +// this is Apple's recommended place for adding/updating constraints +- (void)updateConstraints { + + // --- remake/update constraints here + [self.button remakeConstraints:^(MASConstraintMaker *make) { + make.width.equalTo(@(self.buttonSize.width)); + make.height.equalTo(@(self.buttonSize.height)); + }]; + + //according to apple super should be called at end of method + [super updateConstraints]; +} + +- (void)didTapButton:(UIButton *)button { + // --- Do your changes ie change variables that affect your layout etc --- + self.buttonSize = CGSize(200, 200); + + // tell constraints they need updating + [self setNeedsUpdateConstraints]; +} + +@end +``` + +## Installation +Use the [orsome](http://www.youtube.com/watch?v=YaIZF8uUTtk) [CocoaPods](http://github.com/CocoaPods/CocoaPods). + +In your Podfile +>`pod 'Masonry'` + +If you want to use masonry without all those pesky 'mas_' prefixes. Add #define MAS_SHORTHAND to your prefix.pch before importing Masonry +>`#define MAS_SHORTHAND` + +Get busy Masoning +>`#import "Masonry.h"` + +## Code Snippets + +Copy the included code snippets to ``~/Library/Developer/Xcode/UserData/CodeSnippets`` to write your masonry blocks at lightning speed! + +`mas_make` -> ` [<#view#> mas_makeConstraints:^(MASConstraintMaker *make) { + <#code#> + }];` + +`mas_update` -> ` [<#view#> mas_updateConstraints:^(MASConstraintMaker *make) { + <#code#> + }];` + +`mas_remake` -> ` [<#view#> mas_remakeConstraints:^(MASConstraintMaker *make) { + <#code#> + }];` + +## Features +* Not limited to subset of Auto Layout. Anything NSLayoutConstraint can do, Masonry can do too! +* Great debug support, give your views and constraints meaningful names. +* Constraints read like sentences. +* No crazy macro magic. Masonry won't pollute the global namespace with macros. +* Not string or dictionary based and hence you get compile time checking. + +## TODO +* Eye candy +* Mac example project +* More tests and examples + diff --git a/CustomKeyboard/PrefixHeader.pch b/CustomKeyboard/PrefixHeader.pch index e416482..b761eff 100644 --- a/CustomKeyboard/PrefixHeader.pch +++ b/CustomKeyboard/PrefixHeader.pch @@ -15,4 +15,7 @@ #define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.width #define imageNamed(s) [UIImage imageNamed:s] +#import "Masonry.h" + + #endif /* PrefixHeader_pch */ diff --git a/Podfile b/Podfile new file mode 100644 index 0000000..1bcc590 --- /dev/null +++ b/Podfile @@ -0,0 +1,24 @@ +# Uncomment the next line to define a global platform for your project +source 'https://github.com/CocoaPods/Specs.git' +platform :ios, '13.0' + +target 'CustomKeyboard' do + # Comment the next line if you don't want to use dynamic frameworks + use_frameworks! + + # Pods for CustomKeyboard + +end + +target 'keyBoard' do + # Comment the next line if you don't want to use dynamic frameworks + use_frameworks! + + pod 'AFNetworking','4.0.1' + pod 'Bugly','2.6.1' + pod 'Masonry', '1.1.0' + pod 'MJExtension', '3.4.2' + pod 'MJRefresh', '3.7.9' + pod 'SDWebImage', '5.21.1' + +end diff --git a/Podfile.lock b/Podfile.lock new file mode 100644 index 0000000..ff55f71 --- /dev/null +++ b/Podfile.lock @@ -0,0 +1,52 @@ +PODS: + - AFNetworking (4.0.1): + - AFNetworking/NSURLSession (= 4.0.1) + - AFNetworking/Reachability (= 4.0.1) + - AFNetworking/Security (= 4.0.1) + - AFNetworking/Serialization (= 4.0.1) + - AFNetworking/UIKit (= 4.0.1) + - AFNetworking/NSURLSession (4.0.1): + - AFNetworking/Reachability + - AFNetworking/Security + - AFNetworking/Serialization + - AFNetworking/Reachability (4.0.1) + - AFNetworking/Security (4.0.1) + - AFNetworking/Serialization (4.0.1) + - AFNetworking/UIKit (4.0.1): + - AFNetworking/NSURLSession + - Bugly (2.6.1) + - Masonry (1.1.0) + - MJExtension (3.4.2) + - MJRefresh (3.7.9) + - SDWebImage (5.21.1): + - SDWebImage/Core (= 5.21.1) + - SDWebImage/Core (5.21.1) + +DEPENDENCIES: + - AFNetworking (= 4.0.1) + - Bugly (= 2.6.1) + - Masonry (= 1.1.0) + - MJExtension (= 3.4.2) + - MJRefresh (= 3.7.9) + - SDWebImage (= 5.21.1) + +SPEC REPOS: + https://github.com/CocoaPods/Specs.git: + - AFNetworking + - Bugly + - Masonry + - MJExtension + - MJRefresh + - SDWebImage + +SPEC CHECKSUMS: + AFNetworking: 3bd23d814e976cd148d7d44c3ab78017b744cd58 + Bugly: 217ac2ce5f0f2626d43dbaa4f70764c953a26a31 + Masonry: 678fab65091a9290e40e2832a55e7ab731aad201 + MJExtension: e97d164cb411aa9795cf576093a1fa208b4a8dd8 + MJRefresh: ff9e531227924c84ce459338414550a05d2aea78 + SDWebImage: f29024626962457f3470184232766516dee8dfea + +PODFILE CHECKSUM: b3c72fe500149c35040cdd73c1d91fe05777bc5f + +COCOAPODS: 1.16.2 diff --git a/Pods/AFNetworking/AFNetworking/AFCompatibilityMacros.h b/Pods/AFNetworking/AFNetworking/AFCompatibilityMacros.h new file mode 100644 index 0000000..1f0ab26 --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFCompatibilityMacros.h @@ -0,0 +1,49 @@ +// AFCompatibilityMacros.h +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#ifndef AFCompatibilityMacros_h +#define AFCompatibilityMacros_h + +#ifdef API_AVAILABLE + #define AF_API_AVAILABLE(...) API_AVAILABLE(__VA_ARGS__) +#else + #define AF_API_AVAILABLE(...) +#endif // API_AVAILABLE + +#ifdef API_UNAVAILABLE + #define AF_API_UNAVAILABLE(...) API_UNAVAILABLE(__VA_ARGS__) +#else + #define AF_API_UNAVAILABLE(...) +#endif // API_UNAVAILABLE + +#if __has_warning("-Wunguarded-availability-new") + #define AF_CAN_USE_AT_AVAILABLE 1 +#else + #define AF_CAN_USE_AT_AVAILABLE 0 +#endif + +#if ((__IPHONE_OS_VERSION_MAX_ALLOWED && __IPHONE_OS_VERSION_MAX_ALLOWED < 100000) || (__MAC_OS_VERSION_MAX_ALLOWED && __MAC_OS_VERSION_MAX_ALLOWED < 101200) ||(__WATCH_OS_MAX_VERSION_ALLOWED && __WATCH_OS_MAX_VERSION_ALLOWED < 30000) ||(__TV_OS_MAX_VERSION_ALLOWED && __TV_OS_MAX_VERSION_ALLOWED < 100000)) + #define AF_CAN_INCLUDE_SESSION_TASK_METRICS 0 +#else + #define AF_CAN_INCLUDE_SESSION_TASK_METRICS 1 +#endif + +#endif /* AFCompatibilityMacros_h */ diff --git a/Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.h b/Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.h new file mode 100644 index 0000000..943fc22 --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.h @@ -0,0 +1,285 @@ +// AFHTTPSessionManager.h +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import +#if !TARGET_OS_WATCH +#import +#endif +#import + +#import "AFURLSessionManager.h" + +/** + `AFHTTPSessionManager` is a subclass of `AFURLSessionManager` with convenience methods for making HTTP requests. When a `baseURL` is provided, requests made with the `GET` / `POST` / et al. convenience methods can be made with relative paths. + + ## Subclassing Notes + + Developers targeting iOS 7 or Mac OS X 10.9 or later that deal extensively with a web service are encouraged to subclass `AFHTTPSessionManager`, providing a class method that returns a shared singleton object on which authentication and other configuration can be shared across the application. + + ## Methods to Override + + To change the behavior of all data task operation construction, which is also used in the `GET` / `POST` / et al. convenience methods, override `dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:`. + + ## Serialization + + Requests created by an HTTP client will contain default headers and encode parameters according to the `requestSerializer` property, which is an object conforming to ``. + + Responses received from the server are automatically validated and serialized by the `responseSerializers` property, which is an object conforming to `` + + ## URL Construction Using Relative Paths + + For HTTP convenience methods, the request serializer constructs URLs from the path relative to the `-baseURL`, using `NSURL +URLWithString:relativeToURL:`, when provided. If `baseURL` is `nil`, `path` needs to resolve to a valid `NSURL` object using `NSURL +URLWithString:`. + + Below are a few examples of how `baseURL` and relative paths interact: + + NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"]; + [NSURL URLWithString:@"foo" relativeToURL:baseURL]; // http://example.com/v1/foo + [NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL]; // http://example.com/v1/foo?bar=baz + [NSURL URLWithString:@"/foo" relativeToURL:baseURL]; // http://example.com/foo + [NSURL URLWithString:@"foo/" relativeToURL:baseURL]; // http://example.com/v1/foo + [NSURL URLWithString:@"/foo/" relativeToURL:baseURL]; // http://example.com/foo/ + [NSURL URLWithString:@"http://example2.com/" relativeToURL:baseURL]; // http://example2.com/ + + Also important to note is that a trailing slash will be added to any `baseURL` without one. This would otherwise cause unexpected behavior when constructing URLs using paths without a leading slash. + + @warning Managers for background sessions must be owned for the duration of their use. This can be accomplished by creating an application-wide or shared singleton instance. + */ + +NS_ASSUME_NONNULL_BEGIN + +@interface AFHTTPSessionManager : AFURLSessionManager + +/** + 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 * 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 * responseSerializer; + +///------------------------------- +/// @name Managing Security Policy +///------------------------------- + +/** + The security policy used by created session to evaluate server trust for secure connections. `AFURLSessionManager` uses the `defaultPolicy` unless otherwise specified. A security policy configured with `AFSSLPinningModePublicKey` or `AFSSLPinningModeCertificate` can only be applied on a session manager initialized with a secure base URL (i.e. https). Applying a security policy with pinning enabled on an insecure session manager throws an `Invalid Security Policy` exception. + */ +@property (nonatomic, strong) AFSecurityPolicy *securityPolicy; + +///--------------------- +/// @name Initialization +///--------------------- + +/** + Creates and returns an `AFHTTPSessionManager` object. + */ ++ (instancetype)manager; + +/** + Initializes an `AFHTTPSessionManager` object with the specified base URL. + + @param url The base URL for the HTTP client. + + @return The newly-initialized HTTP client + */ +- (instancetype)initWithBaseURL:(nullable NSURL *)url; + +/** + Initializes an `AFHTTPSessionManager` object with the specified base URL. + + This is the designated initializer. + + @param url The base URL for the HTTP client. + @param configuration The configuration used to create the managed session. + + @return The newly-initialized HTTP client + */ +- (instancetype)initWithBaseURL:(nullable NSURL *)url + sessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER; + +///--------------------------- +/// @name Making HTTP Requests +///--------------------------- + +/** + Creates and runs an `NSURLSessionDataTask` with a `GET` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param headers The headers appended to the default headers for this request. + @param downloadProgress A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler: + */ +- (nullable NSURLSessionDataTask *)GET:(NSString *)URLString + parameters:(nullable id)parameters + headers:(nullable NSDictionary *)headers + progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgress + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; + +/** + Creates and runs an `NSURLSessionDataTask` with a `HEAD` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param headers The headers appended to the default headers for this request. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes a single arguments: the data task. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:completionHandler: + */ +- (nullable NSURLSessionDataTask *)HEAD:(NSString *)URLString + parameters:(nullable id)parameters + headers:(nullable NSDictionary *)headers + success:(nullable void (^)(NSURLSessionDataTask *task))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; + +/** + Creates and runs an `NSURLSessionDataTask` with a `POST` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param headers The headers appended to the default headers for this request. + @param uploadProgress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler: + */ +- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(nullable id)parameters + headers:(nullable NSDictionary *)headers + progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; + +/** + Creates and runs an `NSURLSessionDataTask` with a multipart `POST` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param headers The headers appended to the default headers for this request. + @param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol. + @param uploadProgress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler: + */ +- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(nullable id)parameters + headers:(nullable NSDictionary *)headers + constructingBodyWithBlock:(nullable void (^)(id formData))block + progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; + +/** + Creates and runs an `NSURLSessionDataTask` with a `PUT` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param headers The headers appended to the default headers for this request. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:completionHandler: + */ +- (nullable NSURLSessionDataTask *)PUT:(NSString *)URLString + parameters:(nullable id)parameters + headers:(nullable NSDictionary *)headers + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; + +/** + Creates and runs an `NSURLSessionDataTask` with a `PATCH` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param headers The headers appended to the default headers for this request. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:completionHandler: + */ +- (nullable NSURLSessionDataTask *)PATCH:(NSString *)URLString + parameters:(nullable id)parameters + headers:(nullable NSDictionary *)headers + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; + +/** + Creates and runs an `NSURLSessionDataTask` with a `DELETE` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param headers The headers appended to the default headers for this request. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:completionHandler: + */ +- (nullable NSURLSessionDataTask *)DELETE:(NSString *)URLString + parameters:(nullable id)parameters + headers:(nullable NSDictionary *)headers + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; + +/** + Creates an `NSURLSessionDataTask` with a custom `HTTPMethod` request. + + @param method The HTTPMethod string used to create the request. + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param headers The headers appended to the default headers for this request. + @param uploadProgress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. + @param downloadProgress A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler: + */ +- (nullable NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method + URLString:(NSString *)URLString + parameters:(nullable id)parameters + headers:(nullable NSDictionary *)headers + uploadProgress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress + downloadProgress:(nullable void (^)(NSProgress *downloadProgress))downloadProgress + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.m b/Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.m new file mode 100644 index 0000000..b4ab591 --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.m @@ -0,0 +1,357 @@ +// AFHTTPSessionManager.m +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFHTTPSessionManager.h" + +#import "AFURLRequestSerialization.h" +#import "AFURLResponseSerialization.h" + +#import +#import +#import + +#import +#import +#import +#import +#import + +#if TARGET_OS_IOS || TARGET_OS_TV +#import +#elif TARGET_OS_WATCH +#import +#endif + +@interface AFHTTPSessionManager () +@property (readwrite, nonatomic, strong) NSURL *baseURL; +@end + +@implementation AFHTTPSessionManager +@dynamic responseSerializer; + ++ (instancetype)manager { + return [[[self class] alloc] initWithBaseURL:nil]; +} + +- (instancetype)init { + return [self initWithBaseURL:nil]; +} + +- (instancetype)initWithBaseURL:(NSURL *)url { + return [self initWithBaseURL:url sessionConfiguration:nil]; +} + +- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration { + return [self initWithBaseURL:nil sessionConfiguration:configuration]; +} + +- (instancetype)initWithBaseURL:(NSURL *)url + sessionConfiguration:(NSURLSessionConfiguration *)configuration +{ + self = [super initWithSessionConfiguration:configuration]; + if (!self) { + return nil; + } + + // Ensure terminal slash for baseURL path, so that NSURL +URLWithString:relativeToURL: works as expected + if ([[url path] length] > 0 && ![[url absoluteString] hasSuffix:@"/"]) { + url = [url URLByAppendingPathComponent:@""]; + } + + self.baseURL = url; + + self.requestSerializer = [AFHTTPRequestSerializer serializer]; + self.responseSerializer = [AFJSONResponseSerializer serializer]; + + return self; +} + +#pragma mark - + +- (void)setRequestSerializer:(AFHTTPRequestSerializer *)requestSerializer { + NSParameterAssert(requestSerializer); + + _requestSerializer = requestSerializer; +} + +- (void)setResponseSerializer:(AFHTTPResponseSerializer *)responseSerializer { + NSParameterAssert(responseSerializer); + + [super setResponseSerializer:responseSerializer]; +} + +@dynamic securityPolicy; + +- (void)setSecurityPolicy:(AFSecurityPolicy *)securityPolicy { + if (securityPolicy.SSLPinningMode != AFSSLPinningModeNone && ![self.baseURL.scheme isEqualToString:@"https"]) { + NSString *pinningMode = @"Unknown Pinning Mode"; + switch (securityPolicy.SSLPinningMode) { + case AFSSLPinningModeNone: pinningMode = @"AFSSLPinningModeNone"; break; + case AFSSLPinningModeCertificate: pinningMode = @"AFSSLPinningModeCertificate"; break; + case AFSSLPinningModePublicKey: pinningMode = @"AFSSLPinningModePublicKey"; break; + } + NSString *reason = [NSString stringWithFormat:@"A security policy configured with `%@` can only be applied on a manager with a secure base URL (i.e. https)", pinningMode]; + @throw [NSException exceptionWithName:@"Invalid Security Policy" reason:reason userInfo:nil]; + } + + [super setSecurityPolicy:securityPolicy]; +} + +#pragma mark - + +- (NSURLSessionDataTask *)GET:(NSString *)URLString + parameters:(nullable id)parameters + headers:(nullable NSDictionary *)headers + progress:(nullable void (^)(NSProgress * _Nonnull))downloadProgress + success:(nullable void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure +{ + + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"GET" + URLString:URLString + parameters:parameters + headers:headers + uploadProgress:nil + downloadProgress:downloadProgress + success:success + failure:failure]; + + [dataTask resume]; + + return dataTask; +} + +- (NSURLSessionDataTask *)HEAD:(NSString *)URLString + parameters:(nullable id)parameters + headers:(nullable NSDictionary *)headers + success:(nullable void (^)(NSURLSessionDataTask * _Nonnull))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure +{ + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"HEAD" URLString:URLString parameters:parameters headers:headers uploadProgress:nil downloadProgress:nil success:^(NSURLSessionDataTask *task, __unused id responseObject) { + if (success) { + success(task); + } + } failure:failure]; + + [dataTask resume]; + + return dataTask; +} + +- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(nullable id)parameters + headers:(nullable NSDictionary *)headers + progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure +{ + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"POST" URLString:URLString parameters:parameters headers:headers uploadProgress:uploadProgress downloadProgress:nil success:success failure:failure]; + + [dataTask resume]; + + return dataTask; +} + +- (NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(nullable id)parameters + headers:(nullable NSDictionary *)headers + constructingBodyWithBlock:(nullable void (^)(id _Nonnull))block + progress:(nullable void (^)(NSProgress * _Nonnull))uploadProgress + success:(nullable void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure +{ + NSError *serializationError = nil; + NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError]; + for (NSString *headerField in headers.keyEnumerator) { + [request setValue:headers[headerField] forHTTPHeaderField:headerField]; + } + if (serializationError) { + if (failure) { + dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{ + failure(nil, serializationError); + }); + } + + return nil; + } + + __block NSURLSessionDataTask *task = [self uploadTaskWithStreamedRequest:request progress:uploadProgress completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) { + if (error) { + if (failure) { + failure(task, error); + } + } else { + if (success) { + success(task, responseObject); + } + } + }]; + + [task resume]; + + return task; +} + +- (NSURLSessionDataTask *)PUT:(NSString *)URLString + parameters:(nullable id)parameters + headers:(nullable NSDictionary *)headers + success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask *task, NSError *error))failure +{ + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PUT" URLString:URLString parameters:parameters headers:headers uploadProgress:nil downloadProgress:nil success:success failure:failure]; + + [dataTask resume]; + + return dataTask; +} + +- (NSURLSessionDataTask *)PATCH:(NSString *)URLString + parameters:(nullable id)parameters + headers:(nullable NSDictionary *)headers + success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask *task, NSError *error))failure +{ + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PATCH" URLString:URLString parameters:parameters headers:headers uploadProgress:nil downloadProgress:nil success:success failure:failure]; + + [dataTask resume]; + + return dataTask; +} + +- (NSURLSessionDataTask *)DELETE:(NSString *)URLString + parameters:(nullable id)parameters + headers:(nullable NSDictionary *)headers + success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask *task, NSError *error))failure +{ + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"DELETE" URLString:URLString parameters:parameters headers:headers uploadProgress:nil downloadProgress:nil success:success failure:failure]; + + [dataTask resume]; + + return dataTask; +} + + +- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method + URLString:(NSString *)URLString + parameters:(nullable id)parameters + headers:(nullable NSDictionary *)headers + uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress + downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure +{ + NSError *serializationError = nil; + NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError]; + for (NSString *headerField in headers.keyEnumerator) { + [request setValue:headers[headerField] forHTTPHeaderField:headerField]; + } + if (serializationError) { + if (failure) { + dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{ + failure(nil, serializationError); + }); + } + + return nil; + } + + __block NSURLSessionDataTask *dataTask = nil; + dataTask = [self dataTaskWithRequest:request + uploadProgress:uploadProgress + downloadProgress:downloadProgress + completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) { + if (error) { + if (failure) { + failure(dataTask, error); + } + } else { + if (success) { + success(dataTask, responseObject); + } + } + }]; + + return dataTask; +} + +#pragma mark - NSObject + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@: %p, baseURL: %@, session: %@, operationQueue: %@>", NSStringFromClass([self class]), self, [self.baseURL absoluteString], self.session, self.operationQueue]; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)decoder { + NSURL *baseURL = [decoder decodeObjectOfClass:[NSURL class] forKey:NSStringFromSelector(@selector(baseURL))]; + NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"]; + if (!configuration) { + NSString *configurationIdentifier = [decoder decodeObjectOfClass:[NSString class] forKey:@"identifier"]; + if (configurationIdentifier) { + configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:configurationIdentifier]; + } + } + + self = [self initWithBaseURL:baseURL sessionConfiguration:configuration]; + if (!self) { + return nil; + } + + self.requestSerializer = [decoder decodeObjectOfClass:[AFHTTPRequestSerializer class] forKey:NSStringFromSelector(@selector(requestSerializer))]; + self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))]; + AFSecurityPolicy *decodedPolicy = [decoder decodeObjectOfClass:[AFSecurityPolicy class] forKey:NSStringFromSelector(@selector(securityPolicy))]; + if (decodedPolicy) { + self.securityPolicy = decodedPolicy; + } + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeObject:self.baseURL forKey:NSStringFromSelector(@selector(baseURL))]; + if ([self.session.configuration conformsToProtocol:@protocol(NSCoding)]) { + [coder encodeObject:self.session.configuration forKey:@"sessionConfiguration"]; + } else { + [coder encodeObject:self.session.configuration.identifier forKey:@"identifier"]; + } + [coder encodeObject:self.requestSerializer forKey:NSStringFromSelector(@selector(requestSerializer))]; + [coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))]; + [coder encodeObject:self.securityPolicy forKey:NSStringFromSelector(@selector(securityPolicy))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFHTTPSessionManager *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL sessionConfiguration:self.session.configuration]; + + HTTPClient.requestSerializer = [self.requestSerializer copyWithZone:zone]; + HTTPClient.responseSerializer = [self.responseSerializer copyWithZone:zone]; + HTTPClient.securityPolicy = [self.securityPolicy copyWithZone:zone]; + return HTTPClient; +} + +@end diff --git a/Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.h b/Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.h new file mode 100644 index 0000000..21982a0 --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.h @@ -0,0 +1,216 @@ +// AFNetworkReachabilityManager.h +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +#if !TARGET_OS_WATCH +#import + +typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) { + AFNetworkReachabilityStatusUnknown = -1, + AFNetworkReachabilityStatusNotReachable = 0, + AFNetworkReachabilityStatusReachableViaWWAN = 1, + AFNetworkReachabilityStatusReachableViaWiFi = 2, +}; + +NS_ASSUME_NONNULL_BEGIN + +/** + `AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces. + + Reachability can be used to determine background information about why a network operation failed, or to trigger a network operation retrying when a connection is established. It should not be used to prevent a user from initiating a network request, as it's possible that an initial request may be required to establish reachability. + + See Apple's Reachability Sample Code ( https://developer.apple.com/library/ios/samplecode/reachability/ ) + + @warning Instances of `AFNetworkReachabilityManager` must be started with `-startMonitoring` before reachability status can be determined. + */ +@interface AFNetworkReachabilityManager : NSObject + +/** + The current network reachability status. + */ +@property (readonly, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus; + +/** + Whether or not the network is currently reachable. + */ +@property (readonly, nonatomic, assign, getter = isReachable) BOOL reachable; + +/** + Whether or not the network is currently reachable via WWAN. + */ +@property (readonly, nonatomic, assign, getter = isReachableViaWWAN) BOOL reachableViaWWAN; + +/** + Whether or not the network is currently reachable via WiFi. + */ +@property (readonly, nonatomic, assign, getter = isReachableViaWiFi) BOOL reachableViaWiFi; + +///--------------------- +/// @name Initialization +///--------------------- + +/** + Returns the shared network reachability manager. + */ ++ (instancetype)sharedManager; + +/** + Creates and returns a network reachability manager with the default socket address. + + @return An initialized network reachability manager, actively monitoring the default socket address. + */ ++ (instancetype)manager; + +/** + Creates and returns a network reachability manager for the specified domain. + + @param domain The domain used to evaluate network reachability. + + @return An initialized network reachability manager, actively monitoring the specified domain. + */ ++ (instancetype)managerForDomain:(NSString *)domain; + +/** + Creates and returns a network reachability manager for the socket address. + + @param address The socket address (`sockaddr_in6`) used to evaluate network reachability. + + @return An initialized network reachability manager, actively monitoring the specified socket address. + */ ++ (instancetype)managerForAddress:(const void *)address; + +/** + Initializes an instance of a network reachability manager from the specified reachability object. + + @param reachability The reachability object to monitor. + + @return An initialized network reachability manager, actively monitoring the specified reachability. + */ +- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability NS_DESIGNATED_INITIALIZER; + +/** + * Unavailable initializer + */ ++ (instancetype)new NS_UNAVAILABLE; + +/** + * Unavailable initializer + */ +- (instancetype)init NS_UNAVAILABLE; + +///-------------------------------------------------- +/// @name Starting & Stopping Reachability Monitoring +///-------------------------------------------------- + +/** + Starts monitoring for changes in network reachability status. + */ +- (void)startMonitoring; + +/** + Stops monitoring for changes in network reachability status. + */ +- (void)stopMonitoring; + +///------------------------------------------------- +/// @name Getting Localized Reachability Description +///------------------------------------------------- + +/** + Returns a localized string representation of the current network reachability status. + */ +- (NSString *)localizedNetworkReachabilityStatusString; + +///--------------------------------------------------- +/// @name Setting Network Reachability Change Callback +///--------------------------------------------------- + +/** + Sets a callback to be executed when the network availability of the `baseURL` host changes. + + @param block A block object to be executed when the network availability of the `baseURL` host changes.. This block has no return value and takes a single argument which represents the various reachability states from the device to the `baseURL`. + */ +- (void)setReachabilityStatusChangeBlock:(nullable void (^)(AFNetworkReachabilityStatus status))block; + +@end + +///---------------- +/// @name Constants +///---------------- + +/** + ## Network Reachability + + The following constants are provided by `AFNetworkReachabilityManager` as possible network reachability statuses. + + enum { + AFNetworkReachabilityStatusUnknown, + AFNetworkReachabilityStatusNotReachable, + AFNetworkReachabilityStatusReachableViaWWAN, + AFNetworkReachabilityStatusReachableViaWiFi, + } + + `AFNetworkReachabilityStatusUnknown` + The `baseURL` host reachability is not known. + + `AFNetworkReachabilityStatusNotReachable` + The `baseURL` host cannot be reached. + + `AFNetworkReachabilityStatusReachableViaWWAN` + The `baseURL` host can be reached via a cellular connection, such as EDGE or GPRS. + + `AFNetworkReachabilityStatusReachableViaWiFi` + The `baseURL` host can be reached via a Wi-Fi connection. + + ### Keys for Notification UserInfo Dictionary + + Strings that are used as keys in a `userInfo` dictionary in a network reachability status change notification. + + `AFNetworkingReachabilityNotificationStatusItem` + A key in the userInfo dictionary in a `AFNetworkingReachabilityDidChangeNotification` notification. + The corresponding value is an `NSNumber` object representing the `AFNetworkReachabilityStatus` value for the current reachability status. + */ + +///-------------------- +/// @name Notifications +///-------------------- + +/** + Posted when network reachability changes. + This notification assigns no notification object. The `userInfo` dictionary contains an `NSNumber` object under the `AFNetworkingReachabilityNotificationStatusItem` key, representing the `AFNetworkReachabilityStatus` value for the current network reachability. + + @warning In order for network reachability to be monitored, include the `SystemConfiguration` framework in the active target's "Link Binary With Library" build phase, and add `#import ` to the header prefix of the project (`Prefix.pch`). + */ +FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityDidChangeNotification; +FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityNotificationStatusItem; + +///-------------------- +/// @name Functions +///-------------------- + +/** + Returns a localized string representation of an `AFNetworkReachabilityStatus` value. + */ +FOUNDATION_EXPORT NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status); + +NS_ASSUME_NONNULL_END +#endif diff --git a/Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.m b/Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.m new file mode 100644 index 0000000..0322bf9 --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.m @@ -0,0 +1,269 @@ +// AFNetworkReachabilityManager.m +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFNetworkReachabilityManager.h" +#if !TARGET_OS_WATCH + +#import +#import +#import +#import +#import + +NSString * const AFNetworkingReachabilityDidChangeNotification = @"com.alamofire.networking.reachability.change"; +NSString * const AFNetworkingReachabilityNotificationStatusItem = @"AFNetworkingReachabilityNotificationStatusItem"; + +typedef void (^AFNetworkReachabilityStatusBlock)(AFNetworkReachabilityStatus status); +typedef AFNetworkReachabilityManager * (^AFNetworkReachabilityStatusCallback)(AFNetworkReachabilityStatus status); + +NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status) { + switch (status) { + case AFNetworkReachabilityStatusNotReachable: + return NSLocalizedStringFromTable(@"Not Reachable", @"AFNetworking", nil); + case AFNetworkReachabilityStatusReachableViaWWAN: + return NSLocalizedStringFromTable(@"Reachable via WWAN", @"AFNetworking", nil); + case AFNetworkReachabilityStatusReachableViaWiFi: + return NSLocalizedStringFromTable(@"Reachable via WiFi", @"AFNetworking", nil); + case AFNetworkReachabilityStatusUnknown: + default: + return NSLocalizedStringFromTable(@"Unknown", @"AFNetworking", nil); + } +} + +static AFNetworkReachabilityStatus AFNetworkReachabilityStatusForFlags(SCNetworkReachabilityFlags flags) { + BOOL isReachable = ((flags & kSCNetworkReachabilityFlagsReachable) != 0); + BOOL needsConnection = ((flags & kSCNetworkReachabilityFlagsConnectionRequired) != 0); + BOOL canConnectionAutomatically = (((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) || ((flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0)); + BOOL canConnectWithoutUserInteraction = (canConnectionAutomatically && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0); + BOOL isNetworkReachable = (isReachable && (!needsConnection || canConnectWithoutUserInteraction)); + + AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusUnknown; + if (isNetworkReachable == NO) { + status = AFNetworkReachabilityStatusNotReachable; + } +#if TARGET_OS_IPHONE + else if ((flags & kSCNetworkReachabilityFlagsIsWWAN) != 0) { + status = AFNetworkReachabilityStatusReachableViaWWAN; + } +#endif + else { + status = AFNetworkReachabilityStatusReachableViaWiFi; + } + + return status; +} + +/** + * Queue a status change notification for the main thread. + * + * This is done to ensure that the notifications are received in the same order + * as they are sent. If notifications are sent directly, it is possible that + * a queued notification (for an earlier status condition) is processed after + * the later update, resulting in the listener being left in the wrong state. + */ +static void AFPostReachabilityStatusChange(SCNetworkReachabilityFlags flags, AFNetworkReachabilityStatusCallback block) { + AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags); + dispatch_async(dispatch_get_main_queue(), ^{ + AFNetworkReachabilityManager *manager = nil; + if (block) { + manager = block(status); + } + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; + NSDictionary *userInfo = @{ AFNetworkingReachabilityNotificationStatusItem: @(status) }; + [notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:manager userInfo:userInfo]; + }); +} + +static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkReachabilityFlags flags, void *info) { + AFPostReachabilityStatusChange(flags, (__bridge AFNetworkReachabilityStatusCallback)info); +} + + +static const void * AFNetworkReachabilityRetainCallback(const void *info) { + return Block_copy(info); +} + +static void AFNetworkReachabilityReleaseCallback(const void *info) { + if (info) { + Block_release(info); + } +} + +@interface AFNetworkReachabilityManager () +@property (readonly, nonatomic, assign) SCNetworkReachabilityRef networkReachability; +@property (readwrite, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus; +@property (readwrite, nonatomic, copy) AFNetworkReachabilityStatusBlock networkReachabilityStatusBlock; +@end + +@implementation AFNetworkReachabilityManager + ++ (instancetype)sharedManager { + static AFNetworkReachabilityManager *_sharedManager = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + _sharedManager = [self manager]; + }); + + return _sharedManager; +} + ++ (instancetype)managerForDomain:(NSString *)domain { + SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [domain UTF8String]); + + AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability]; + + CFRelease(reachability); + + return manager; +} + ++ (instancetype)managerForAddress:(const void *)address { + SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)address); + AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability]; + + CFRelease(reachability); + + return manager; +} + ++ (instancetype)manager +{ +#if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 90000) || (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + struct sockaddr_in6 address; + bzero(&address, sizeof(address)); + address.sin6_len = sizeof(address); + address.sin6_family = AF_INET6; +#else + struct sockaddr_in address; + bzero(&address, sizeof(address)); + address.sin_len = sizeof(address); + address.sin_family = AF_INET; +#endif + return [self managerForAddress:&address]; +} + +- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability { + self = [super init]; + if (!self) { + return nil; + } + + _networkReachability = CFRetain(reachability); + self.networkReachabilityStatus = AFNetworkReachabilityStatusUnknown; + + return self; +} + +- (instancetype)init +{ + @throw [NSException exceptionWithName:NSGenericException + reason:@"`-init` unavailable. Use `-initWithReachability:` instead" + userInfo:nil]; + return nil; +} + +- (void)dealloc { + [self stopMonitoring]; + + if (_networkReachability != NULL) { + CFRelease(_networkReachability); + } +} + +#pragma mark - + +- (BOOL)isReachable { + return [self isReachableViaWWAN] || [self isReachableViaWiFi]; +} + +- (BOOL)isReachableViaWWAN { + return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN; +} + +- (BOOL)isReachableViaWiFi { + return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi; +} + +#pragma mark - + +- (void)startMonitoring { + [self stopMonitoring]; + + if (!self.networkReachability) { + return; + } + + __weak __typeof(self)weakSelf = self; + AFNetworkReachabilityStatusCallback callback = ^(AFNetworkReachabilityStatus status) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + + strongSelf.networkReachabilityStatus = status; + if (strongSelf.networkReachabilityStatusBlock) { + strongSelf.networkReachabilityStatusBlock(status); + } + + return strongSelf; + }; + + SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL}; + SCNetworkReachabilitySetCallback(self.networkReachability, AFNetworkReachabilityCallback, &context); + SCNetworkReachabilityScheduleWithRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes); + + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),^{ + SCNetworkReachabilityFlags flags; + if (SCNetworkReachabilityGetFlags(self.networkReachability, &flags)) { + AFPostReachabilityStatusChange(flags, callback); + } + }); +} + +- (void)stopMonitoring { + if (!self.networkReachability) { + return; + } + + SCNetworkReachabilityUnscheduleFromRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes); +} + +#pragma mark - + +- (NSString *)localizedNetworkReachabilityStatusString { + return AFStringFromNetworkReachabilityStatus(self.networkReachabilityStatus); +} + +#pragma mark - + +- (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block { + self.networkReachabilityStatusBlock = block; +} + +#pragma mark - NSKeyValueObserving + ++ (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key { + if ([key isEqualToString:@"reachable"] || [key isEqualToString:@"reachableViaWWAN"] || [key isEqualToString:@"reachableViaWiFi"]) { + return [NSSet setWithObject:@"networkReachabilityStatus"]; + } + + return [super keyPathsForValuesAffectingValueForKey:key]; +} + +@end +#endif diff --git a/Pods/AFNetworking/AFNetworking/AFNetworking.h b/Pods/AFNetworking/AFNetworking/AFNetworking.h new file mode 100644 index 0000000..e2fb2f4 --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFNetworking.h @@ -0,0 +1,41 @@ +// AFNetworking.h +// +// Copyright (c) 2013 AFNetworking (http://afnetworking.com/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import +#import +#import + +#ifndef _AFNETWORKING_ + #define _AFNETWORKING_ + + #import "AFURLRequestSerialization.h" + #import "AFURLResponseSerialization.h" + #import "AFSecurityPolicy.h" + +#if !TARGET_OS_WATCH + #import "AFNetworkReachabilityManager.h" +#endif + + #import "AFURLSessionManager.h" + #import "AFHTTPSessionManager.h" + +#endif /* _AFNETWORKING_ */ diff --git a/Pods/AFNetworking/AFNetworking/AFSecurityPolicy.h b/Pods/AFNetworking/AFNetworking/AFSecurityPolicy.h new file mode 100644 index 0000000..9b966a5 --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFSecurityPolicy.h @@ -0,0 +1,161 @@ +// AFSecurityPolicy.h +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import +#import + +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. + + Note that if pinning is enabled, `evaluateServerTrust:forDomain:` will return true if any pinned certificate matches. + + @see policyWithPinningMode:withPinnedCertificates: + */ +@property (nonatomic, strong, nullable) NSSet *pinnedCertificates; + +/** + Whether or not to trust servers with an invalid or expired SSL certificates. Defaults to `NO`. + */ +@property (nonatomic, assign) BOOL allowInvalidCertificates; + +/** + Whether or not to validate the domain name in the certificate's CN field. Defaults to `YES`. + */ +@property (nonatomic, assign) BOOL validatesDomainName; + +///----------------------------------------- +/// @name Getting Certificates from the Bundle +///----------------------------------------- + +/** + Returns any certificates included in the bundle. If you are using AFNetworking as an embedded framework, you must use this method to find the certificates you have included in your app bundle, and use them when creating your security policy by calling `policyWithPinningMode:withPinnedCertificates`. + + @return The certificates included in the given bundle. + */ ++ (NSSet *)certificatesInBundle:(NSBundle *)bundle; + +///----------------------------------------- +/// @name Getting Specific Security Policies +///----------------------------------------- + +/** + Returns the shared default security policy, which does not allow invalid certificates, validates domain name, and does not validate against pinned certificates or public keys. + + @return The default security policy. + */ ++ (instancetype)defaultPolicy; + +///--------------------- +/// @name Initialization +///--------------------- + +/** + Creates and returns a security policy with the specified pinning mode. + + Certificates with the `.cer` extension found in the main bundle will be pinned. If you want more control over which certificates are pinned, please use `policyWithPinningMode:withPinnedCertificates:` instead. + + @param pinningMode The SSL pinning mode. + + @return A new security policy. + + @see -policyWithPinningMode:withPinnedCertificates: + */ ++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode; + +/** + Creates and returns a security policy with the specified pinning mode. + + @param pinningMode The SSL pinning mode. + @param pinnedCertificates The certificates to pin against. + + @return A new security policy. + + @see +certificatesInBundle: + @see -pinnedCertificates +*/ ++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet *)pinnedCertificates; + +///------------------------------ +/// @name Evaluating Server Trust +///------------------------------ + +/** + Whether or not the specified server trust should be accepted, based on the security policy. + + This method should be used when responding to an authentication challenge from a server. + + @param serverTrust The X.509 certificate trust of the server. + @param domain The domain of serverTrust. If `nil`, the domain will not be validated. + + @return Whether or not to trust the server. + */ +- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust + forDomain:(nullable NSString *)domain; + +@end + +NS_ASSUME_NONNULL_END + +///---------------- +/// @name Constants +///---------------- + +/** + ## SSL Pinning Modes + + The following constants are provided by `AFSSLPinningMode` as possible SSL pinning modes. + + enum { + AFSSLPinningModeNone, + AFSSLPinningModePublicKey, + AFSSLPinningModeCertificate, + } + + `AFSSLPinningModeNone` + Do not used pinned certificates to validate servers. + + `AFSSLPinningModePublicKey` + Validate host certificates against public keys of pinned certificates. + + `AFSSLPinningModeCertificate` + Validate host certificates against pinned certificates. +*/ diff --git a/Pods/AFNetworking/AFNetworking/AFSecurityPolicy.m b/Pods/AFNetworking/AFNetworking/AFSecurityPolicy.m new file mode 100644 index 0000000..da199aa --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFSecurityPolicy.m @@ -0,0 +1,341 @@ +// AFSecurityPolicy.m +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFSecurityPolicy.h" + +#import + +#if !TARGET_OS_IOS && !TARGET_OS_WATCH && !TARGET_OS_TV +static NSData * AFSecKeyGetData(SecKeyRef key) { + CFDataRef data = NULL; + + __Require_noErr_Quiet(SecItemExport(key, kSecFormatUnknown, kSecItemPemArmour, NULL, &data), _out); + + return (__bridge_transfer NSData *)data; + +_out: + if (data) { + CFRelease(data); + } + + return nil; +} +#endif + +static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) { +#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV + return [(__bridge id)key1 isEqual:(__bridge id)key2]; +#else + return [AFSecKeyGetData(key1) isEqual:AFSecKeyGetData(key2)]; +#endif +} + +static id AFPublicKeyForCertificate(NSData *certificate) { + id allowedPublicKey = nil; + SecCertificateRef allowedCertificate; + SecPolicyRef policy = nil; + SecTrustRef allowedTrust = nil; + SecTrustResultType result; + + allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificate); + __Require_Quiet(allowedCertificate != NULL, _out); + + policy = SecPolicyCreateBasicX509(); + __Require_noErr_Quiet(SecTrustCreateWithCertificates(allowedCertificate, policy, &allowedTrust), _out); +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + __Require_noErr_Quiet(SecTrustEvaluate(allowedTrust, &result), _out); +#pragma clang diagnostic pop + + allowedPublicKey = (__bridge_transfer id)SecTrustCopyPublicKey(allowedTrust); + +_out: + if (allowedTrust) { + CFRelease(allowedTrust); + } + + if (policy) { + CFRelease(policy); + } + + if (allowedCertificate) { + CFRelease(allowedCertificate); + } + + return allowedPublicKey; +} + +static BOOL AFServerTrustIsValid(SecTrustRef serverTrust) { + BOOL isValid = NO; + SecTrustResultType result; +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + __Require_noErr_Quiet(SecTrustEvaluate(serverTrust, &result), _out); +#pragma clang diagnostic pop + + isValid = (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed); + +_out: + return isValid; +} + +static NSArray * AFCertificateTrustChainForServerTrust(SecTrustRef serverTrust) { + CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust); + NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount]; + + for (CFIndex i = 0; i < certificateCount; i++) { + SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i); + [trustChain addObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)]; + } + + return [NSArray arrayWithArray:trustChain]; +} + +static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) { + SecPolicyRef policy = SecPolicyCreateBasicX509(); + CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust); + NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount]; + for (CFIndex i = 0; i < certificateCount; i++) { + SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i); + + SecCertificateRef someCertificates[] = {certificate}; + CFArrayRef certificates = CFArrayCreate(NULL, (const void **)someCertificates, 1, NULL); + + SecTrustRef trust; + __Require_noErr_Quiet(SecTrustCreateWithCertificates(certificates, policy, &trust), _out); + SecTrustResultType result; +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + __Require_noErr_Quiet(SecTrustEvaluate(trust, &result), _out); +#pragma clang diagnostic pop + [trustChain addObject:(__bridge_transfer id)SecTrustCopyPublicKey(trust)]; + + _out: + if (trust) { + CFRelease(trust); + } + + if (certificates) { + CFRelease(certificates); + } + + continue; + } + CFRelease(policy); + + return [NSArray arrayWithArray:trustChain]; +} + +#pragma mark - + +@interface AFSecurityPolicy() +@property (readwrite, nonatomic, assign) AFSSLPinningMode SSLPinningMode; +@property (readwrite, nonatomic, strong) NSSet *pinnedPublicKeys; +@end + +@implementation AFSecurityPolicy + ++ (NSSet *)certificatesInBundle:(NSBundle *)bundle { + NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."]; + + NSMutableSet *certificates = [NSMutableSet setWithCapacity:[paths count]]; + for (NSString *path in paths) { + NSData *certificateData = [NSData dataWithContentsOfFile:path]; + [certificates addObject:certificateData]; + } + + return [NSSet setWithSet:certificates]; +} + ++ (instancetype)defaultPolicy { + AFSecurityPolicy *securityPolicy = [[self alloc] init]; + securityPolicy.SSLPinningMode = AFSSLPinningModeNone; + + return securityPolicy; +} + ++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode { + NSSet *defaultPinnedCertificates = [self certificatesInBundle:[NSBundle mainBundle]]; + return [self policyWithPinningMode:pinningMode withPinnedCertificates:defaultPinnedCertificates]; +} + ++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet *)pinnedCertificates { + AFSecurityPolicy *securityPolicy = [[self alloc] init]; + securityPolicy.SSLPinningMode = pinningMode; + + [securityPolicy setPinnedCertificates:pinnedCertificates]; + + return securityPolicy; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.validatesDomainName = YES; + + return self; +} + +- (void)setPinnedCertificates:(NSSet *)pinnedCertificates { + _pinnedCertificates = pinnedCertificates; + + if (self.pinnedCertificates) { + NSMutableSet *mutablePinnedPublicKeys = [NSMutableSet setWithCapacity:[self.pinnedCertificates count]]; + for (NSData *certificate in self.pinnedCertificates) { + id publicKey = AFPublicKeyForCertificate(certificate); + if (!publicKey) { + continue; + } + [mutablePinnedPublicKeys addObject:publicKey]; + } + self.pinnedPublicKeys = [NSSet setWithSet:mutablePinnedPublicKeys]; + } else { + self.pinnedPublicKeys = nil; + } +} + +#pragma mark - + +- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust + forDomain:(NSString *)domain +{ + if (domain && self.allowInvalidCertificates && self.validatesDomainName && (self.SSLPinningMode == AFSSLPinningModeNone || [self.pinnedCertificates count] == 0)) { + // https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/NetworkingTopics/Articles/OverridingSSLChainValidationCorrectly.html + // According to the docs, you should only trust your provided certs for evaluation. + // Pinned certificates are added to the trust. Without pinned certificates, + // there is nothing to evaluate against. + // + // From Apple Docs: + // "Do not implicitly trust self-signed certificates as anchors (kSecTrustOptionImplicitAnchors). + // Instead, add your own (self-signed) CA certificate to the list of trusted anchors." + NSLog(@"In order to validate a domain name for self signed certificates, you MUST use pinning."); + return NO; + } + + NSMutableArray *policies = [NSMutableArray array]; + if (self.validatesDomainName) { + [policies addObject:(__bridge_transfer id)SecPolicyCreateSSL(true, (__bridge CFStringRef)domain)]; + } else { + [policies addObject:(__bridge_transfer id)SecPolicyCreateBasicX509()]; + } + + SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)policies); + + if (self.SSLPinningMode == AFSSLPinningModeNone) { + return self.allowInvalidCertificates || AFServerTrustIsValid(serverTrust); + } else if (!self.allowInvalidCertificates && !AFServerTrustIsValid(serverTrust)) { + return NO; + } + + switch (self.SSLPinningMode) { + case AFSSLPinningModeCertificate: { + NSMutableArray *pinnedCertificates = [NSMutableArray array]; + for (NSData *certificateData in self.pinnedCertificates) { + [pinnedCertificates addObject:(__bridge_transfer id)SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificateData)]; + } + SecTrustSetAnchorCertificates(serverTrust, (__bridge CFArrayRef)pinnedCertificates); + + if (!AFServerTrustIsValid(serverTrust)) { + return NO; + } + + // obtain the chain after being validated, which *should* contain the pinned certificate in the last position (if it's the Root CA) + NSArray *serverCertificates = AFCertificateTrustChainForServerTrust(serverTrust); + + for (NSData *trustChainCertificate in [serverCertificates reverseObjectEnumerator]) { + if ([self.pinnedCertificates containsObject:trustChainCertificate]) { + return YES; + } + } + + return NO; + } + case AFSSLPinningModePublicKey: { + NSUInteger trustedPublicKeyCount = 0; + NSArray *publicKeys = AFPublicKeyTrustChainForServerTrust(serverTrust); + + for (id trustChainPublicKey in publicKeys) { + for (id pinnedPublicKey in self.pinnedPublicKeys) { + if (AFSecKeyIsEqualToKey((__bridge SecKeyRef)trustChainPublicKey, (__bridge SecKeyRef)pinnedPublicKey)) { + trustedPublicKeyCount += 1; + } + } + } + return trustedPublicKeyCount > 0; + } + + default: + return NO; + } + + return NO; +} + +#pragma mark - NSKeyValueObserving + ++ (NSSet *)keyPathsForValuesAffectingPinnedPublicKeys { + return [NSSet setWithObject:@"pinnedCertificates"]; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)decoder { + + self = [self init]; + if (!self) { + return nil; + } + + self.SSLPinningMode = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(SSLPinningMode))] unsignedIntegerValue]; + self.allowInvalidCertificates = [decoder decodeBoolForKey:NSStringFromSelector(@selector(allowInvalidCertificates))]; + self.validatesDomainName = [decoder decodeBoolForKey:NSStringFromSelector(@selector(validatesDomainName))]; + self.pinnedCertificates = [decoder decodeObjectOfClass:[NSSet class] forKey:NSStringFromSelector(@selector(pinnedCertificates))]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [coder encodeObject:[NSNumber numberWithUnsignedInteger:self.SSLPinningMode] forKey:NSStringFromSelector(@selector(SSLPinningMode))]; + [coder encodeBool:self.allowInvalidCertificates forKey:NSStringFromSelector(@selector(allowInvalidCertificates))]; + [coder encodeBool:self.validatesDomainName forKey:NSStringFromSelector(@selector(validatesDomainName))]; + [coder encodeObject:self.pinnedCertificates forKey:NSStringFromSelector(@selector(pinnedCertificates))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFSecurityPolicy *securityPolicy = [[[self class] allocWithZone:zone] init]; + securityPolicy.SSLPinningMode = self.SSLPinningMode; + securityPolicy.allowInvalidCertificates = self.allowInvalidCertificates; + securityPolicy.validatesDomainName = self.validatesDomainName; + securityPolicy.pinnedCertificates = [self.pinnedCertificates copyWithZone:zone]; + + return securityPolicy; +} + +@end diff --git a/Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.h b/Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.h new file mode 100644 index 0000000..b17e871 --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.h @@ -0,0 +1,479 @@ +// AFURLRequestSerialization.h +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import +#import + +#if TARGET_OS_IOS || TARGET_OS_TV +#import +#elif TARGET_OS_WATCH +#import +#endif + +NS_ASSUME_NONNULL_BEGIN + +/** + Returns a percent-escaped string following RFC 3986 for a query string key or value. + RFC 3986 states that the following characters are "reserved" characters. + - General Delimiters: ":", "#", "[", "]", "@", "?", "/" + - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" + + In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow + query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" + should be percent-escaped in the query string. + + @param string The string to be percent-escaped. + + @return The percent-escaped string. + */ +FOUNDATION_EXPORT NSString * AFPercentEscapedStringFromString(NSString *string); + +/** + A helper method to generate encoded url query parameters for appending to the end of a URL. + + @param parameters A dictionary of key/values to be encoded. + + @return A url encoded query string + */ +FOUNDATION_EXPORT NSString * AFQueryStringFromParameters(NSDictionary *parameters); + +/** + The `AFURLRequestSerialization` protocol is adopted by an object that encodes parameters for a specified HTTP requests. Request serializers may encode parameters as query strings, HTTP bodies, setting the appropriate HTTP header fields as necessary. + + For example, a JSON request serializer may set the HTTP body of the request to a JSON representation, and set the `Content-Type` HTTP header field value to `application/json`. + */ +@protocol AFURLRequestSerialization + +/** + Returns a request with the specified parameters encoded into a copy of the original request. + + @param request The original request. + @param parameters The parameters to be encoded. + @param error The error that occurred while attempting to encode the request parameters. + + @return A serialized request. + */ +- (nullable NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request + withParameters:(nullable id)parameters + error:(NSError * _Nullable __autoreleasing *)error NS_SWIFT_NOTHROW; + +@end + +#pragma mark - + +/** + + */ +typedef NS_ENUM(NSUInteger, AFHTTPRequestQueryStringSerializationStyle) { + AFHTTPRequestQueryStringDefaultStyle = 0, +}; + +@protocol AFMultipartFormData; + +/** + `AFHTTPRequestSerializer` conforms to the `AFURLRequestSerialization` & `AFURLResponseSerialization` protocols, offering a concrete base implementation of query string / URL form-encoded parameter serialization and default request headers, as well as response status code and content type validation. + + Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPRequestSerializer` in order to ensure consistent default behavior. + */ +@interface AFHTTPRequestSerializer : NSObject + +/** + 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; + +/** + 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 * _Nullable (^)(NSURLRequest *request, id parameters, NSError * __autoreleasing *error))block; + +///------------------------------- +/// @name Creating Request Objects +///------------------------------- + +/** + Creates an `NSMutableURLRequest` object with the specified HTTP method and URL string. + + If the HTTP method is `GET`, `HEAD`, or `DELETE`, the parameters will be used to construct a url-encoded query string that is appended to the request's URL. Otherwise, the parameters will be encoded according to the value of the `parameterEncoding` property, and set as the request body. + + @param method The HTTP method for the request, such as `GET`, `POST`, `PUT`, or `DELETE`. This parameter must not be `nil`. + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be either set as a query string for `GET` requests, or the request HTTP body. + @param error The error that occurred while constructing the request. + + @return An `NSMutableURLRequest` object. + */ +- (nullable NSMutableURLRequest *)requestWithMethod:(NSString *)method + URLString:(NSString *)URLString + parameters:(nullable id)parameters + error:(NSError * _Nullable __autoreleasing *)error; + +/** + Creates an `NSMutableURLRequest` object with the specified HTTP method and URLString, and constructs a `multipart/form-data` HTTP body, using the specified parameters and multipart form data block. See http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.2 + + Multipart form requests are automatically streamed, reading files directly from disk along with in-memory data in a single HTTP body. The resulting `NSMutableURLRequest` object has an `HTTPBodyStream` property, so refrain from setting `HTTPBodyStream` or `HTTPBody` on this request object, as it will clear out the multipart form body stream. + + @param method The HTTP method for the request. This parameter must not be `GET` or `HEAD`, or `nil`. + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded and set in the request HTTP body. + @param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol. + @param error The error that occurred while constructing the request. + + @return An `NSMutableURLRequest` object + */ +- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method + URLString:(NSString *)URLString + parameters:(nullable NSDictionary *)parameters + constructingBodyWithBlock:(nullable void (^)(id formData))block + error:(NSError * _Nullable __autoreleasing *)error; + +/** + Creates an `NSMutableURLRequest` by removing the `HTTPBodyStream` from a request, and asynchronously writing its contents into the specified file, invoking the completion handler when finished. + + @param request The multipart form request. The `HTTPBodyStream` property of `request` must not be `nil`. + @param fileURL The file URL to write multipart form contents to. + @param handler A handler block to execute. + + @discussion There is a bug in `NSURLSessionTask` that causes requests to not send a `Content-Length` header when streaming contents from an HTTP body, which is notably problematic when interacting with the Amazon S3 webservice. As a workaround, this method takes a request constructed with `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:error:`, or any other request with an `HTTPBodyStream`, writes the contents to the specified file and returns a copy of the original request with the `HTTPBodyStream` property set to `nil`. From here, the file can either be passed to `AFURLSessionManager -uploadTaskWithRequest:fromFile:progress:completionHandler:`, or have its contents read into an `NSData` that's assigned to the `HTTPBody` property of the request. + + @see https://github.com/AFNetworking/AFNetworking/issues/1398 + */ +- (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request + writingStreamContentsToFile:(NSURL *)fileURL + completionHandler:(nullable void (^)(NSError * _Nullable error))handler; + +@end + +#pragma mark - + +/** + The `AFMultipartFormData` protocol defines the methods supported by the parameter in the block argument of `AFHTTPRequestSerializer -multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:`. + */ +@protocol AFMultipartFormData + +/** + Appends the HTTP header `Content-Disposition: file; filename=#{generated filename}; name=#{name}"` and `Content-Type: #{generated mimeType}`, followed by the encoded file data and the multipart form boundary. + + The filename and MIME type for this data in the form will be automatically generated, using the last path component of the `fileURL` and system associated MIME type for the `fileURL` extension, respectively. + + @param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`. + @param name The name to be associated with the specified data. This parameter must not be `nil`. + @param error If an error occurs, upon return contains an `NSError` object that describes the problem. + + @return `YES` if the file data was successfully appended, otherwise `NO`. + */ +- (BOOL)appendPartWithFileURL:(NSURL *)fileURL + name:(NSString *)name + error:(NSError * _Nullable __autoreleasing *)error; + +/** + Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary. + + @param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`. + @param name The name to be associated with the specified data. This parameter must not be `nil`. + @param fileName The file name to be used in the `Content-Disposition` header. This parameter must not be `nil`. + @param mimeType The declared MIME type of the file data. This parameter must not be `nil`. + @param error If an error occurs, upon return contains an `NSError` object that describes the problem. + + @return `YES` if the file data was successfully appended otherwise `NO`. + */ +- (BOOL)appendPartWithFileURL:(NSURL *)fileURL + name:(NSString *)name + fileName:(NSString *)fileName + mimeType:(NSString *)mimeType + error:(NSError * _Nullable __autoreleasing *)error; + +/** + Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the data from the input stream and the multipart form boundary. + + @param inputStream The input stream to be appended to the form data + @param name The name to be associated with the specified input stream. This parameter must not be `nil`. + @param fileName The filename to be associated with the specified input stream. This parameter must not be `nil`. + @param length The length of the specified input stream in bytes. + @param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`. + */ +- (void)appendPartWithInputStream:(nullable NSInputStream *)inputStream + name:(NSString *)name + fileName:(NSString *)fileName + length:(int64_t)length + mimeType:(NSString *)mimeType; + +/** + Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary. + + @param data The data to be encoded and appended to the form data. + @param name The name to be associated with the specified data. This parameter must not be `nil`. + @param fileName The filename to be associated with the specified data. This parameter must not be `nil`. + @param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`. + */ +- (void)appendPartWithFileData:(NSData *)data + name:(NSString *)name + fileName:(NSString *)fileName + mimeType:(NSString *)mimeType; + +/** + Appends the HTTP headers `Content-Disposition: form-data; name=#{name}"`, followed by the encoded data and the multipart form boundary. + + @param data The data to be encoded and appended to the form data. + @param name The name to be associated with the specified data. This parameter must not be `nil`. + */ + +- (void)appendPartWithFormData:(NSData *)data + name:(NSString *)name; + + +/** + Appends HTTP headers, followed by the encoded data and the multipart form boundary. + + @param headers The HTTP headers to be appended to the form data. + @param body The data to be encoded and appended to the form data. This parameter must not be `nil`. + */ +- (void)appendPartWithHeaders:(nullable NSDictionary *)headers + body:(NSData *)body; + +/** + Throttles request bandwidth by limiting the packet size and adding a delay for each chunk read from the upload stream. + + When uploading over a 3G or EDGE connection, requests may fail with "request body stream exhausted". Setting a maximum packet size and delay according to the recommended values (`kAFUploadStream3GSuggestedPacketSize` and `kAFUploadStream3GSuggestedDelay`) lowers the risk of the input stream exceeding its allocated bandwidth. Unfortunately, there is no definite way to distinguish between a 3G, EDGE, or LTE connection over `NSURLConnection`. As such, it is not recommended that you throttle bandwidth based solely on network reachability. Instead, you should consider checking for the "request body stream exhausted" in a failure block, and then retrying the request with throttled bandwidth. + + @param numberOfBytes Maximum packet size, in number of bytes. The default packet size for an input stream is 16kb. + @param delay Duration of delay each time a packet is read. By default, no delay is set. + */ +- (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes + delay:(NSTimeInterval)delay; + +@end + +#pragma mark - + +/** + `AFJSONRequestSerializer` is a subclass of `AFHTTPRequestSerializer` that encodes parameters as JSON using `NSJSONSerialization`, setting the `Content-Type` of the encoded request to `application/json`. + */ +@interface AFJSONRequestSerializer : AFHTTPRequestSerializer + +/** + Options for writing the request JSON data from Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONWritingOptions". `0` by default. + */ +@property (nonatomic, assign) NSJSONWritingOptions writingOptions; + +/** + Creates and returns a JSON serializer with specified reading and writing options. + + @param writingOptions The specified JSON writing options. + */ ++ (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions; + +@end + +#pragma mark - + +/** + `AFPropertyListRequestSerializer` is a subclass of `AFHTTPRequestSerializer` that encodes parameters as JSON using `NSPropertyListSerializer`, setting the `Content-Type` of the encoded request to `application/x-plist`. + */ +@interface AFPropertyListRequestSerializer : AFHTTPRequestSerializer + +/** + The property list format. Possible values are described in "NSPropertyListFormat". + */ +@property (nonatomic, assign) NSPropertyListFormat format; + +/** + @warning The `writeOptions` property is currently unused. + */ +@property (nonatomic, assign) NSPropertyListWriteOptions writeOptions; + +/** + Creates and returns a property list serializer with a specified format, read options, and write options. + + @param format The property list format. + @param writeOptions The property list write options. + + @warning The `writeOptions` property is currently unused. + */ ++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format + writeOptions:(NSPropertyListWriteOptions)writeOptions; + +@end + +#pragma mark - + +///---------------- +/// @name Constants +///---------------- + +/** + ## Error Domains + + The following error domain is predefined. + + - `NSString * const AFURLRequestSerializationErrorDomain` + + ### Constants + + `AFURLRequestSerializationErrorDomain` + AFURLRequestSerializer errors. Error codes for `AFURLRequestSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`. + */ +FOUNDATION_EXPORT NSString * const AFURLRequestSerializationErrorDomain; + +/** + ## User info dictionary keys + + These keys may exist in the user info dictionary, in addition to those defined for NSError. + + - `NSString * const AFNetworkingOperationFailingURLRequestErrorKey` + + ### Constants + + `AFNetworkingOperationFailingURLRequestErrorKey` + The corresponding value is an `NSURLRequest` containing the request of the operation associated with an error. This key is only present in the `AFURLRequestSerializationErrorDomain`. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLRequestErrorKey; + +/** + ## Throttling Bandwidth for HTTP Request Input Streams + + @see -throttleBandwidthWithPacketSize:delay: + + ### Constants + + `kAFUploadStream3GSuggestedPacketSize` + Maximum packet size, in number of bytes. Equal to 16kb. + + `kAFUploadStream3GSuggestedDelay` + Duration of delay each time a packet is read. Equal to 0.2 seconds. + */ +FOUNDATION_EXPORT NSUInteger const kAFUploadStream3GSuggestedPacketSize; +FOUNDATION_EXPORT NSTimeInterval const kAFUploadStream3GSuggestedDelay; + +NS_ASSUME_NONNULL_END diff --git a/Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.m b/Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.m new file mode 100644 index 0000000..f60b6f9 --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.m @@ -0,0 +1,1399 @@ +// AFURLRequestSerialization.m +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFURLRequestSerialization.h" + +#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV +#import +#else +#import +#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); + +/** + 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. + */ +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]]; + + // FIXME: https://github.com/AFNetworking/AFNetworking/pull/3028 + // return [string stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet]; + + static NSUInteger const batchSize = 50; + + NSUInteger index = 0; + NSMutableString *escaped = @"".mutableCopy; + + while (index < string.length) { + NSUInteger length = MIN(string.length - index, batchSize); + NSRange range = NSMakeRange(index, length); + + // To avoid breaking up character sequences such as 👴🏻👮🏽 + range = [string rangeOfComposedCharacterSequencesForRange:range]; + + NSString *substring = [string substringWithRange:range]; + NSString *encoded = [substring stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet]; + [escaped appendString:encoded]; + + index += range.length; + } + + return escaped; +} + +#pragma mark - + +@interface AFQueryStringPair : NSObject +@property (readwrite, nonatomic, strong) id field; +@property (readwrite, nonatomic, strong) id value; + +- (instancetype)initWithField:(id)field value:(id)value; + +- (NSString *)URLEncodedStringValue; +@end + +@implementation AFQueryStringPair + +- (instancetype)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 - + +FOUNDATION_EXPORT NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary); +FOUNDATION_EXPORT NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value); + +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 +- (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, strong) dispatch_queue_t requestHeaderModificationQueue; +@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]; + self.requestHeaderModificationQueue = dispatch_queue_create("requestHeaderModificationQueue", DISPATCH_QUEUE_CONCURRENT); + + // 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"]; + + // User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43 + NSString *userAgent = nil; +#if TARGET_OS_IOS + 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_TV + userAgent = [NSString stringWithFormat:@"%@/%@ (%@; tvOS %@; 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 + 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 + 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 { + NSDictionary __block *value; + dispatch_sync(self.requestHeaderModificationQueue, ^{ + value = [NSDictionary dictionaryWithDictionary:self.mutableHTTPRequestHeaders]; + }); + return value; +} + +- (void)setValue:(NSString *)value +forHTTPHeaderField:(NSString *)field +{ + dispatch_barrier_sync(self.requestHeaderModificationQueue, ^{ + [self.mutableHTTPRequestHeaders setValue:value forKey:field]; + }); +} + +- (NSString *)valueForHTTPHeaderField:(NSString *)field { + NSString __block *value; + dispatch_sync(self.requestHeaderModificationQueue, ^{ + value = [self.mutableHTTPRequestHeaders valueForKey:field]; + }); + return value; +} + +- (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username + password:(NSString *)password +{ + NSData *basicAuthCredentials = [[NSString stringWithFormat:@"%@:%@", username, password] dataUsingEncoding:NSUTF8StringEncoding]; + NSString *base64AuthCredentials = [basicAuthCredentials base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)0]; + [self setValue:[NSString stringWithFormat:@"Basic %@", base64AuthCredentials] forHTTPHeaderField:@"Authorization"]; +} + +- (void)clearAuthorizationHeader { + dispatch_barrier_sync(self.requestHeaderModificationQueue, ^{ + [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 + 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 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]; + } + }]; + + NSString *query = nil; + if (parameters) { + 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]]) { + if (query && query.length > 0) { + mutableRequest.URL = [NSURL URLWithString:[[mutableRequest.URL absoluteString] stringByAppendingFormat:mutableRequest.URL.query ? @"&%@" : @"?%@", query]]; + } + } else { + // #2864: an empty string is a valid x-www-form-urlencoded payload + if (!query) { + query = @""; + } + 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; +} + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [self init]; + if (!self) { + return nil; + } + + self.mutableHTTPRequestHeaders = [[decoder decodeObjectOfClass:[NSDictionary class] forKey:NSStringFromSelector(@selector(mutableHTTPRequestHeaders))] mutableCopy]; + self.queryStringSerializationStyle = (AFHTTPRequestQueryStringSerializationStyle)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))] unsignedIntegerValue]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + dispatch_sync(self.requestHeaderModificationQueue, ^{ + [coder encodeObject:self.mutableHTTPRequestHeaders forKey:NSStringFromSelector(@selector(mutableHTTPRequestHeaders))]; + }); + [coder encodeObject:@(self.queryStringSerializationStyle) forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFHTTPRequestSerializer *serializer = [[[self class] allocWithZone:zone] init]; + dispatch_sync(self.requestHeaderModificationQueue, ^{ + 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) { + 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; + } +} + +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 +@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; + +- (instancetype)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 + +- (instancetype)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; +} + +- (void)setRequest:(NSMutableURLRequest *)request +{ + _request = [request mutableCopy]; +} + +- (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 () +@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 +#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; + +- (instancetype)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; + + while ((NSUInteger)totalNumberOfBytesRead < MIN(length, self.numberOfBytesInPacket)) { + if (!self.currentHTTPBodyPart || ![self.currentHTTPBodyPart hasBytesAvailable]) { + if (!(self.currentHTTPBodyPart = [self.HTTPBodyPartEnumerator nextObject])) { + break; + } + } else { + NSUInteger maxLength = MIN(length, self.numberOfBytesInPacket) - (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]; + } + } + } + } + + 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 + +- (instancetype)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 () { + AFHTTPBodyPartReadPhase _phase; + NSInputStream *_inputStream; + unsigned long long _phaseReadOffset; +} + +- (BOOL)transitionToNextPhase; +- (NSInteger)readData:(NSData *)data + intoBuffer:(uint8_t *)buffer + maxLength:(NSUInteger)length; +@end + +@implementation AFHTTPBodyPart + +- (instancetype)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; + } + + 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; + } +} + +- (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 +{ + NSRange range = NSMakeRange((NSUInteger)_phaseReadOffset, MIN([data length] - ((NSUInteger)_phaseReadOffset), length)); + [data getBytes:buffer range:range]; + + _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; + } + + 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; + + return YES; +} + +#pragma mark - NSCopying + +- (instancetype)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"]; + } + + if (![NSJSONSerialization isValidJSONObject:parameters]) { + if (error) { + NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"The `parameters` argument is not valid JSON.", @"AFNetworking", nil)}; + *error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo]; + } + return nil; + } + + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error]; + + if (!jsonData) { + return nil; + } + + [mutableRequest setHTTPBody:jsonData]; + } + + return mutableRequest; +} + +#pragma mark - NSSecureCoding + +- (instancetype)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 encodeObject:@(self.writingOptions) forKey:NSStringFromSelector(@selector(writingOptions))]; +} + +#pragma mark - NSCopying + +- (instancetype)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"]; + } + + NSData *plistData = [NSPropertyListSerialization dataWithPropertyList:parameters format:self.format options:self.writeOptions error:error]; + + if (!plistData) { + return nil; + } + + [mutableRequest setHTTPBody:plistData]; + } + + return mutableRequest; +} + +#pragma mark - NSSecureCoding + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + + self.format = (NSPropertyListFormat)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue]; + self.writeOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(writeOptions))] unsignedIntegerValue]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeObject:@(self.format) forKey:NSStringFromSelector(@selector(format))]; + [coder encodeObject:@(self.writeOptions) forKey:NSStringFromSelector(@selector(writeOptions))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFPropertyListRequestSerializer *serializer = [super copyWithZone:zone]; + serializer.format = self.format; + serializer.writeOptions = self.writeOptions; + + return serializer; +} + +@end diff --git a/Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.h b/Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.h new file mode 100644 index 0000000..56a4d28 --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.h @@ -0,0 +1,313 @@ +// AFURLResponseSerialization.h +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + Recursively removes `NSNull` values from a JSON object. +*/ +FOUNDATION_EXPORT id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingOptions readingOptions); + +/** + The `AFURLResponseSerialization` protocol is adopted by an object that decodes data into a more useful object representation, according to details in the server response. Response serializers may additionally perform validation on the incoming response and data. + + For example, a JSON response serializer may check for an acceptable status code (`2XX` range) and content type (`application/json`), decoding a valid JSON response into an object. + */ +@protocol AFURLResponseSerialization + +/** + The response object decoded from the data associated with a specified response. + + @param response The response to be processed. + @param data The response data to be decoded. + @param error The error that occurred while attempting to decode the response data. + + @return The object decoded from the specified response data. + */ +- (nullable id)responseObjectForResponse:(nullable NSURLResponse *)response + data:(nullable NSData *)data + error:(NSError * _Nullable __autoreleasing *)error NS_SWIFT_NOTHROW; + +@end + +#pragma mark - + +/** + `AFHTTPResponseSerializer` conforms to the `AFURLRequestSerialization` & `AFURLResponseSerialization` protocols, offering a concrete base implementation of query string / URL form-encoded parameter serialization and default request headers, as well as response status code and content type validation. + + Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPResponseSerializer` in order to ensure consistent default behavior. + */ +@interface AFHTTPResponseSerializer : NSObject + +- (instancetype)init; + +/** + Creates and returns a serializer with default configuration. + */ ++ (instancetype)serializer; + +///----------------------------------------- +/// @name Configuring Response Serialization +///----------------------------------------- + +/** + The acceptable HTTP status codes for responses. When non-`nil`, responses with status codes not contained by the set will result in an error during validation. + + See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html + */ +@property (nonatomic, copy, nullable) NSIndexSet *acceptableStatusCodes; + +/** + The acceptable MIME types for responses. When non-`nil`, responses with a `Content-Type` with MIME types that do not intersect with the set will result in an error during validation. + */ +@property (nonatomic, copy, nullable) NSSet *acceptableContentTypes; + +/** + Validates the specified response and data. + + In its base implementation, this method checks for an acceptable status code and content type. Subclasses may wish to add other domain-specific checks. + + @param response The response to be validated. + @param data The data associated with the response. + @param error The error that occurred while attempting to validate the response. + + @return `YES` if the response is valid, otherwise `NO`. + */ +- (BOOL)validateResponse:(nullable NSHTTPURLResponse *)response + data:(nullable NSData *)data + error:(NSError * _Nullable __autoreleasing *)error; + +@end + +#pragma mark - + + +/** + `AFJSONResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes JSON responses. + + By default, `AFJSONResponseSerializer` accepts the following MIME types, which includes the official standard, `application/json`, as well as other commonly-used types: + + - `application/json` + - `text/json` + - `text/javascript` + + In RFC 7159 - Section 8.1, it states that JSON text is required to be encoded in UTF-8, UTF-16, or UTF-32, and the default encoding is UTF-8. NSJSONSerialization provides support for all the encodings listed in the specification, and recommends UTF-8 for efficiency. Using an unsupported encoding will result in serialization error. See the `NSJSONSerialization` documentation for more details. + */ +@interface AFJSONResponseSerializer : AFHTTPResponseSerializer + +- (instancetype)init; + +/** + Options for reading the response JSON data and creating the Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default. + */ +@property (nonatomic, assign) NSJSONReadingOptions readingOptions; + +/** + Whether to remove keys with `NSNull` values from response JSON. Defaults to `NO`. + */ +@property (nonatomic, assign) BOOL removesKeysWithNullValues; + +/** + Creates and returns a JSON serializer with specified reading and writing options. + + @param readingOptions The specified JSON reading options. + */ ++ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions; + +@end + +#pragma mark - + +/** + `AFXMLParserResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLParser` objects. + + By default, `AFXMLParserResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types: + + - `application/xml` + - `text/xml` + */ +@interface AFXMLParserResponseSerializer : AFHTTPResponseSerializer + +@end + +#pragma mark - + +#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED + +/** + `AFXMLDocumentResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects. + + By default, `AFXMLDocumentResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types: + + - `application/xml` + - `text/xml` + */ +@interface AFXMLDocumentResponseSerializer : AFHTTPResponseSerializer + +- (instancetype)init; + +/** + Input and output options specifically intended for `NSXMLDocument` objects. For possible values, see the `NSXMLDocument` documentation section "Input and Output Options". `0` by default. + */ +@property (nonatomic, assign) NSUInteger options; + +/** + Creates and returns an XML document serializer with the specified options. + + @param mask The XML document options. + */ ++ (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask; + +@end + +#endif + +#pragma mark - + +/** + `AFPropertyListResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects. + + By default, `AFPropertyListResponseSerializer` accepts the following MIME types: + + - `application/x-plist` + */ +@interface AFPropertyListResponseSerializer : AFHTTPResponseSerializer + +- (instancetype)init; + +/** + The property list format. Possible values are described in "NSPropertyListFormat". + */ +@property (nonatomic, assign) NSPropertyListFormat format; + +/** + The property list reading options. Possible values are described in "NSPropertyListMutabilityOptions." + */ +@property (nonatomic, assign) NSPropertyListReadOptions readOptions; + +/** + Creates and returns a property list serializer with a specified format, read options, and write options. + + @param format The property list format. + @param readOptions The property list reading options. + */ ++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format + readOptions:(NSPropertyListReadOptions)readOptions; + +@end + +#pragma mark - + +/** + `AFImageResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes image responses. + + By default, `AFImageResponseSerializer` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage: + + - `image/tiff` + - `image/jpeg` + - `image/gif` + - `image/png` + - `image/ico` + - `image/x-icon` + - `image/bmp` + - `image/x-bmp` + - `image/x-xbitmap` + - `image/x-win-bitmap` + */ +@interface AFImageResponseSerializer : AFHTTPResponseSerializer + +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH +/** + The scale factor used when interpreting the image data to construct `responseImage`. Specifying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the size property. This is set to the value of scale of the main screen by default, which automatically scales images for retina displays, for instance. + */ +@property (nonatomic, assign) CGFloat imageScale; + +/** + Whether to automatically inflate response image data for compressed formats (such as PNG or JPEG). Enabling this can significantly improve drawing performance on iOS when used with `setCompletionBlockWithSuccess:failure:`, as it allows a bitmap representation to be constructed in the background rather than on the main thread. `YES` by default. + */ +@property (nonatomic, assign) BOOL automaticallyInflatesResponseImage; +#endif + +@end + +#pragma mark - + +/** + `AFCompoundSerializer` is a subclass of `AFHTTPResponseSerializer` that delegates the response serialization to the first `AFHTTPResponseSerializer` object that returns an object for `responseObjectForResponse:data:error:`, falling back on the default behavior of `AFHTTPResponseSerializer`. This is useful for supporting multiple potential types and structures of server responses with a single serializer. + */ +@interface AFCompoundResponseSerializer : AFHTTPResponseSerializer + +/** + The component response serializers. + */ +@property (readonly, nonatomic, copy) NSArray > *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`. + */ +FOUNDATION_EXPORT NSString * const AFURLResponseSerializationErrorDomain; + +/** + ## User info dictionary keys + + These keys may exist in the user info dictionary, in addition to those defined for NSError. + + - `NSString * const AFNetworkingOperationFailingURLResponseErrorKey` + - `NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey` + + ### Constants + + `AFNetworkingOperationFailingURLResponseErrorKey` + The corresponding value is an `NSURLResponse` containing the response of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`. + + `AFNetworkingOperationFailingURLResponseDataErrorKey` + The corresponding value is an `NSData` containing the original data of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseErrorKey; + +FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey; + +NS_ASSUME_NONNULL_END diff --git a/Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.m b/Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.m new file mode 100755 index 0000000..2715a1b --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.m @@ -0,0 +1,836 @@ +// AFURLResponseSerialization.m +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFURLResponseSerialization.h" + +#import + +#if TARGET_OS_IOS +#import +#elif TARGET_OS_WATCH +#import +#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) +#import +#endif + +NSString * const AFURLResponseSerializationErrorDomain = @"com.alamofire.error.serialization.response"; +NSString * const AFNetworkingOperationFailingURLResponseErrorKey = @"com.alamofire.serialization.response.error.response"; +NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey = @"com.alamofire.serialization.response.error.data"; + +static NSError * AFErrorWithUnderlyingError(NSError *error, NSError *underlyingError) { + if (!error) { + return underlyingError; + } + + if (!underlyingError || error.userInfo[NSUnderlyingErrorKey]) { + return error; + } + + NSMutableDictionary *mutableUserInfo = [error.userInfo mutableCopy]; + mutableUserInfo[NSUnderlyingErrorKey] = underlyingError; + + return [[NSError alloc] initWithDomain:error.domain code:error.code userInfo:mutableUserInfo]; +} + +static BOOL AFErrorOrUnderlyingErrorHasCodeInDomain(NSError *error, NSInteger code, NSString *domain) { + if ([error.domain isEqualToString:domain] && error.code == code) { + return YES; + } else if (error.userInfo[NSUnderlyingErrorKey]) { + return AFErrorOrUnderlyingErrorHasCodeInDomain(error.userInfo[NSUnderlyingErrorKey], code, domain); + } + + return NO; +} + +id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingOptions readingOptions) { + if ([JSONObject isKindOfClass:[NSArray class]]) { + NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:[(NSArray *)JSONObject count]]; + for (id value in (NSArray *)JSONObject) { + if (![value isEqual:[NSNull null]]) { + [mutableArray addObject:AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions)]; + } + } + + return (readingOptions & NSJSONReadingMutableContainers) ? mutableArray : [NSArray arrayWithArray:mutableArray]; + } else if ([JSONObject isKindOfClass:[NSDictionary class]]) { + NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary:JSONObject]; + for (id key in [(NSDictionary *)JSONObject allKeys]) { + id value = (NSDictionary *)JSONObject[key]; + if (!value || [value isEqual:[NSNull null]]) { + [mutableDictionary removeObjectForKey:key]; + } else if ([value isKindOfClass:[NSArray class]] || [value isKindOfClass:[NSDictionary class]]) { + mutableDictionary[key] = AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions); + } + } + + return (readingOptions & NSJSONReadingMutableContainers) ? mutableDictionary : [NSDictionary dictionaryWithDictionary:mutableDictionary]; + } + + return JSONObject; +} + +@implementation AFHTTPResponseSerializer + ++ (instancetype)serializer { + return [[self alloc] init]; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)]; + self.acceptableContentTypes = nil; + + return self; +} + +#pragma mark - + +- (BOOL)validateResponse:(NSHTTPURLResponse *)response + data:(NSData *)data + error:(NSError * __autoreleasing *)error +{ + BOOL responseIsValid = YES; + NSError *validationError = nil; + + if ([response isKindOfClass:[NSHTTPURLResponse class]]) { + if (self.acceptableContentTypes && ![self.acceptableContentTypes containsObject:[response MIMEType]] && + !([response MIMEType] == nil && [data length] == 0)) { + + if ([data length] > 0 && [response URL]) { + NSMutableDictionary *mutableUserInfo = [@{ + NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: unacceptable content-type: %@", @"AFNetworking", nil), [response MIMEType]], + NSURLErrorFailingURLErrorKey:[response URL], + AFNetworkingOperationFailingURLResponseErrorKey: response, + } mutableCopy]; + if (data) { + mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data; + } + + validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:mutableUserInfo], validationError); + } + + responseIsValid = NO; + } + + if (self.acceptableStatusCodes && ![self.acceptableStatusCodes containsIndex:(NSUInteger)response.statusCode] && [response URL]) { + NSMutableDictionary *mutableUserInfo = [@{ + NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: %@ (%ld)", @"AFNetworking", nil), [NSHTTPURLResponse localizedStringForStatusCode:response.statusCode], (long)response.statusCode], + NSURLErrorFailingURLErrorKey:[response URL], + AFNetworkingOperationFailingURLResponseErrorKey: response, + } mutableCopy]; + + if (data) { + mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data; + } + + validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorBadServerResponse userInfo:mutableUserInfo], validationError); + + responseIsValid = NO; + } + } + + if (error && !responseIsValid) { + *error = validationError; + } + + return responseIsValid; +} + +#pragma mark - AFURLResponseSerialization + +- (id)responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + [self validateResponse:(NSHTTPURLResponse *)response data:data error:error]; + + return data; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [self init]; + if (!self) { + return nil; + } + + self.acceptableStatusCodes = [decoder decodeObjectOfClass:[NSIndexSet class] forKey:NSStringFromSelector(@selector(acceptableStatusCodes))]; + self.acceptableContentTypes = [decoder decodeObjectOfClass:[NSSet class] forKey:NSStringFromSelector(@selector(acceptableContentTypes))]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [coder encodeObject:self.acceptableStatusCodes forKey:NSStringFromSelector(@selector(acceptableStatusCodes))]; + [coder encodeObject:self.acceptableContentTypes forKey:NSStringFromSelector(@selector(acceptableContentTypes))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFHTTPResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; + serializer.acceptableStatusCodes = [self.acceptableStatusCodes copyWithZone:zone]; + serializer.acceptableContentTypes = [self.acceptableContentTypes copyWithZone:zone]; + + return serializer; +} + +@end + +#pragma mark - + +@implementation AFJSONResponseSerializer + ++ (instancetype)serializer { + return [self serializerWithReadingOptions:(NSJSONReadingOptions)0]; +} + ++ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions { + AFJSONResponseSerializer *serializer = [[self alloc] init]; + serializer.readingOptions = readingOptions; + + return serializer; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil]; + + return self; +} + +#pragma mark - AFURLResponseSerialization + +- (id)responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { + return nil; + } + } + + // Workaround for behavior of Rails to return a single space for `head :ok` (a workaround for a bug in Safari), which is not interpreted as valid input by NSJSONSerialization. + // See https://github.com/rails/rails/issues/1742 + BOOL isSpace = [data isEqualToData:[NSData dataWithBytes:" " length:1]]; + + if (data.length == 0 || isSpace) { + return nil; + } + + NSError *serializationError = nil; + + id responseObject = [NSJSONSerialization JSONObjectWithData:data options:self.readingOptions error:&serializationError]; + + if (!responseObject) + { + if (error) { + *error = AFErrorWithUnderlyingError(serializationError, *error); + } + return nil; + } + + if (self.removesKeysWithNullValues) { + return AFJSONObjectByRemovingKeysWithNullValues(responseObject, self.readingOptions); + } + + return responseObject; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + + self.readingOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readingOptions))] unsignedIntegerValue]; + self.removesKeysWithNullValues = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(removesKeysWithNullValues))] boolValue]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeObject:@(self.readingOptions) forKey:NSStringFromSelector(@selector(readingOptions))]; + [coder encodeObject:@(self.removesKeysWithNullValues) forKey:NSStringFromSelector(@selector(removesKeysWithNullValues))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFJSONResponseSerializer *serializer = [super copyWithZone:zone]; + serializer.readingOptions = self.readingOptions; + serializer.removesKeysWithNullValues = self.removesKeysWithNullValues; + + return serializer; +} + +@end + +#pragma mark - + +@implementation AFXMLParserResponseSerializer + ++ (instancetype)serializer { + AFXMLParserResponseSerializer *serializer = [[self alloc] init]; + + return serializer; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil]; + + return self; +} + +#pragma mark - AFURLResponseSerialization + +- (id)responseObjectForResponse:(NSHTTPURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { + return nil; + } + } + + return [[NSXMLParser alloc] initWithData:data]; +} + +@end + +#pragma mark - + +#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED + +@implementation AFXMLDocumentResponseSerializer + ++ (instancetype)serializer { + return [self serializerWithXMLDocumentOptions:0]; +} + ++ (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask { + AFXMLDocumentResponseSerializer *serializer = [[self alloc] init]; + serializer.options = mask; + + return serializer; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil]; + + return self; +} + +#pragma mark - AFURLResponseSerialization + +- (id)responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { + return nil; + } + } + + NSError *serializationError = nil; + NSXMLDocument *document = [[NSXMLDocument alloc] initWithData:data options:self.options error:&serializationError]; + + if (!document) + { + if (error) { + *error = AFErrorWithUnderlyingError(serializationError, *error); + } + return nil; + } + + return document; +} + +#pragma mark - NSSecureCoding + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + + self.options = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(options))] unsignedIntegerValue]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeObject:@(self.options) forKey:NSStringFromSelector(@selector(options))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFXMLDocumentResponseSerializer *serializer = [super copyWithZone:zone]; + serializer.options = self.options; + + return serializer; +} + +@end + +#endif + +#pragma mark - + +@implementation AFPropertyListResponseSerializer + ++ (instancetype)serializer { + return [self serializerWithFormat:NSPropertyListXMLFormat_v1_0 readOptions:0]; +} + ++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format + readOptions:(NSPropertyListReadOptions)readOptions +{ + AFPropertyListResponseSerializer *serializer = [[self alloc] init]; + serializer.format = format; + serializer.readOptions = readOptions; + + return serializer; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/x-plist", nil]; + + return self; +} + +#pragma mark - AFURLResponseSerialization + +- (id)responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { + return nil; + } + } + + if (!data) { + return nil; + } + + NSError *serializationError = nil; + + id responseObject = [NSPropertyListSerialization propertyListWithData:data options:self.readOptions format:NULL error:&serializationError]; + + if (!responseObject) + { + if (error) { + *error = AFErrorWithUnderlyingError(serializationError, *error); + } + return nil; + } + + return responseObject; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + + self.format = (NSPropertyListFormat)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue]; + self.readOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readOptions))] unsignedIntegerValue]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeObject:@(self.format) forKey:NSStringFromSelector(@selector(format))]; + [coder encodeObject:@(self.readOptions) forKey:NSStringFromSelector(@selector(readOptions))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFPropertyListResponseSerializer *serializer = [super copyWithZone:zone]; + serializer.format = self.format; + serializer.readOptions = self.readOptions; + + return serializer; +} + +@end + +#pragma mark - + +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH +#import +#import + +@interface UIImage (AFNetworkingSafeImageLoading) ++ (UIImage *)af_safeImageWithData:(NSData *)data; +@end + +static NSLock* imageLock = nil; + +@implementation UIImage (AFNetworkingSafeImageLoading) + ++ (UIImage *)af_safeImageWithData:(NSData *)data { + UIImage* image = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + imageLock = [[NSLock alloc] init]; + }); + + [imageLock lock]; + image = [UIImage imageWithData:data]; + [imageLock unlock]; + return image; +} + +@end + +static UIImage * AFImageWithDataAtScale(NSData *data, CGFloat scale) { + UIImage *image = [UIImage af_safeImageWithData:data]; + if (image.images) { + return image; + } + + return [[UIImage alloc] initWithCGImage:[image CGImage] scale:scale orientation:image.imageOrientation]; +} + +static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *response, NSData *data, CGFloat scale) { + if (!data || [data length] == 0) { + return nil; + } + + CGImageRef imageRef = NULL; + CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data); + + if ([response.MIMEType isEqualToString:@"image/png"]) { + imageRef = CGImageCreateWithPNGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault); + } else if ([response.MIMEType isEqualToString:@"image/jpeg"]) { + imageRef = CGImageCreateWithJPEGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault); + + if (imageRef) { + CGColorSpaceRef imageColorSpace = CGImageGetColorSpace(imageRef); + CGColorSpaceModel imageColorSpaceModel = CGColorSpaceGetModel(imageColorSpace); + + // CGImageCreateWithJPEGDataProvider does not properly handle CMKY, so fall back to AFImageWithDataAtScale + if (imageColorSpaceModel == kCGColorSpaceModelCMYK) { + CGImageRelease(imageRef); + imageRef = NULL; + } + } + } + + CGDataProviderRelease(dataProvider); + + UIImage *image = AFImageWithDataAtScale(data, scale); + if (!imageRef) { + if (image.images || !image) { + return image; + } + + imageRef = CGImageCreateCopy([image CGImage]); + if (!imageRef) { + return nil; + } + } + + size_t width = CGImageGetWidth(imageRef); + size_t height = CGImageGetHeight(imageRef); + size_t bitsPerComponent = CGImageGetBitsPerComponent(imageRef); + + if (width * height > 1024 * 1024 || bitsPerComponent > 8) { + CGImageRelease(imageRef); + + return image; + } + + // CGImageGetBytesPerRow() calculates incorrectly in iOS 5.0, so defer to CGBitmapContextCreate + size_t bytesPerRow = 0; + CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); + CGColorSpaceModel colorSpaceModel = CGColorSpaceGetModel(colorSpace); + CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef); + + if (colorSpaceModel == kCGColorSpaceModelRGB) { + uint32_t alpha = (bitmapInfo & kCGBitmapAlphaInfoMask); +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wassign-enum" + if (alpha == kCGImageAlphaNone) { + bitmapInfo &= ~kCGBitmapAlphaInfoMask; + bitmapInfo |= kCGImageAlphaNoneSkipFirst; + } else if (!(alpha == kCGImageAlphaNoneSkipFirst || alpha == kCGImageAlphaNoneSkipLast)) { + bitmapInfo &= ~kCGBitmapAlphaInfoMask; + bitmapInfo |= kCGImageAlphaPremultipliedFirst; + } +#pragma clang diagnostic pop + } + + CGContextRef context = CGBitmapContextCreate(NULL, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo); + + CGColorSpaceRelease(colorSpace); + + if (!context) { + CGImageRelease(imageRef); + + return image; + } + + CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, width, height), imageRef); + CGImageRef inflatedImageRef = CGBitmapContextCreateImage(context); + + CGContextRelease(context); + + UIImage *inflatedImage = [[UIImage alloc] initWithCGImage:inflatedImageRef scale:scale orientation:image.imageOrientation]; + + CGImageRelease(inflatedImageRef); + CGImageRelease(imageRef); + + return inflatedImage; +} +#endif + + +@implementation AFImageResponseSerializer + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon", @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap", nil]; + +#if TARGET_OS_IOS || TARGET_OS_TV + self.imageScale = [[UIScreen mainScreen] scale]; + self.automaticallyInflatesResponseImage = YES; +#elif TARGET_OS_WATCH + self.imageScale = [[WKInterfaceDevice currentDevice] screenScale]; + self.automaticallyInflatesResponseImage = YES; +#endif + + return self; +} + +#pragma mark - AFURLResponseSerializer + +- (id)responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { + return nil; + } + } + +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH + if (self.automaticallyInflatesResponseImage) { + return AFInflatedImageFromResponseWithDataAtScale((NSHTTPURLResponse *)response, data, self.imageScale); + } else { + return AFImageWithDataAtScale(data, self.imageScale); + } +#else + // Ensure that the image is set to it's correct pixel width and height + NSBitmapImageRep *bitimage = [[NSBitmapImageRep alloc] initWithData:data]; + NSImage *image = [[NSImage alloc] initWithSize:NSMakeSize([bitimage pixelsWide], [bitimage pixelsHigh])]; + [image addRepresentation:bitimage]; + + return image; +#endif + + return nil; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH + NSNumber *imageScale = [decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(imageScale))]; +#if CGFLOAT_IS_DOUBLE + self.imageScale = [imageScale doubleValue]; +#else + self.imageScale = [imageScale floatValue]; +#endif + + self.automaticallyInflatesResponseImage = [decoder decodeBoolForKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))]; +#endif + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH + [coder encodeObject:@(self.imageScale) forKey:NSStringFromSelector(@selector(imageScale))]; + [coder encodeBool:self.automaticallyInflatesResponseImage forKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))]; +#endif +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFImageResponseSerializer *serializer = [super copyWithZone:zone]; + +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH + serializer.imageScale = self.imageScale; + serializer.automaticallyInflatesResponseImage = self.automaticallyInflatesResponseImage; +#endif + + return serializer; +} + +@end + +#pragma mark - + +@interface AFCompoundResponseSerializer () +@property (readwrite, nonatomic, copy) NSArray *responseSerializers; +@end + +@implementation AFCompoundResponseSerializer + ++ (instancetype)compoundSerializerWithResponseSerializers:(NSArray *)responseSerializers { + AFCompoundResponseSerializer *serializer = [[self alloc] init]; + serializer.responseSerializers = responseSerializers; + + return serializer; +} + +#pragma mark - AFURLResponseSerialization + +- (id)responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + for (id serializer in self.responseSerializers) { + if (![serializer isKindOfClass:[AFHTTPResponseSerializer class]]) { + continue; + } + + NSError *serializerError = nil; + id responseObject = [serializer responseObjectForResponse:response data:data error:&serializerError]; + if (responseObject) { + if (error) { + *error = AFErrorWithUnderlyingError(serializerError, *error); + } + + return responseObject; + } + } + + return [super responseObjectForResponse:response data:data error:error]; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + + NSSet *classes = [NSSet setWithArray:@[[NSArray class], [AFHTTPResponseSerializer class]]]; + self.responseSerializers = [decoder decodeObjectOfClasses:classes forKey:NSStringFromSelector(@selector(responseSerializers))]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeObject:self.responseSerializers forKey:NSStringFromSelector(@selector(responseSerializers))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFCompoundResponseSerializer *serializer = [super copyWithZone:zone]; + serializer.responseSerializers = self.responseSerializers; + + return serializer; +} + +@end diff --git a/Pods/AFNetworking/AFNetworking/AFURLSessionManager.h b/Pods/AFNetworking/AFNetworking/AFURLSessionManager.h new file mode 100644 index 0000000..88700c3 --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFURLSessionManager.h @@ -0,0 +1,516 @@ +// AFURLSessionManager.h +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + + +#import + +#import "AFURLResponseSerialization.h" +#import "AFURLRequestSerialization.h" +#import "AFSecurityPolicy.h" +#import "AFCompatibilityMacros.h" +#if !TARGET_OS_WATCH +#import "AFNetworkReachabilityManager.h" +#endif + +/** + `AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to ``, ``, ``, and ``. + + ## Subclassing Notes + + This is the base class for `AFHTTPSessionManager`, which adds functionality specific to making HTTP requests. If you are looking to extend `AFURLSessionManager` specifically for HTTP, consider subclassing `AFHTTPSessionManager` instead. + + ## NSURLSession & NSURLSessionTask Delegate Methods + + `AFURLSessionManager` implements the following delegate methods: + + ### `NSURLSessionDelegate` + + - `URLSession:didBecomeInvalidWithError:` + - `URLSession:didReceiveChallenge:completionHandler:` + - `URLSessionDidFinishEventsForBackgroundURLSession:` + + ### `NSURLSessionTaskDelegate` + + - `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:` + - `URLSession:task:didReceiveChallenge:completionHandler:` + - `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:` + - `URLSession:task:needNewBodyStream:` + - `URLSession:task:didCompleteWithError:` + + ### `NSURLSessionDataDelegate` + + - `URLSession:dataTask:didReceiveResponse:completionHandler:` + - `URLSession:dataTask:didBecomeDownloadTask:` + - `URLSession:dataTask:didReceiveData:` + - `URLSession:dataTask:willCacheResponse:completionHandler:` + + ### `NSURLSessionDownloadDelegate` + + - `URLSession:downloadTask:didFinishDownloadingToURL:` + - `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:` + - `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:` + + If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first. + + ## Network Reachability Monitoring + + Network reachability status and change monitoring is available through the `reachabilityManager` property. Applications may choose to monitor network reachability conditions in order to prevent or suspend any outbound requests. See `AFNetworkReachabilityManager` for more details. + + ## NSCoding Caveats + + - Encoded managers do not include any block properties. Be sure to set delegate callback blocks when using `-initWithCoder:` or `NSKeyedUnarchiver`. + + ## NSCopying Caveats + + - `-copy` and `-copyWithZone:` return a new manager with a new `NSURLSession` created from the configuration of the original. + - Operation copies do not include any delegate callback blocks, as they often strongly captures a reference to `self`, which would otherwise have the unintuitive side-effect of pointing to the _original_ session manager when copied. + + @warning Managers for background sessions must be owned for the duration of their use. This can be accomplished by creating an application-wide or shared singleton instance. + */ + +NS_ASSUME_NONNULL_BEGIN + +@interface AFURLSessionManager : NSObject + +/** + 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 responseSerializer; + +///------------------------------- +/// @name Managing Security Policy +///------------------------------- + +/** + The security policy used by created session to evaluate server trust for secure connections. `AFURLSessionManager` uses the `defaultPolicy` unless otherwise specified. + */ +@property (nonatomic, strong) AFSecurityPolicy *securityPolicy; + +#if !TARGET_OS_WATCH +///-------------------------------------- +/// @name Monitoring Network Reachability +///-------------------------------------- + +/** + The network reachability manager. `AFURLSessionManager` uses the `sharedManager` by default. + */ +@property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager; +#endif + +///---------------------------- +/// @name Getting Session Tasks +///---------------------------- + +/** + The data, upload, and download tasks currently run by the managed session. + */ +@property (readonly, nonatomic, strong) NSArray *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. + */ +@property (nonatomic, strong, nullable) dispatch_queue_t completionQueue; + +/** + The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used. + */ +@property (nonatomic, strong, nullable) dispatch_group_t completionGroup; + +///--------------------- +/// @name Initialization +///--------------------- + +/** + Creates and returns a manager for a session created with the specified configuration. This is the designated initializer. + + @param configuration The configuration used to create the managed session. + + @return A manager for a newly-created session. + */ +- (instancetype)initWithSessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER; + +/** + Invalidates the managed session, optionally canceling pending tasks and optionally resets given session. + + @param cancelPendingTasks Whether or not to cancel pending tasks. + @param resetSession Whether or not to reset the session of the manager. + */ +- (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks resetSession:(BOOL)resetSession; + +///------------------------- +/// @name Running Data Tasks +///------------------------- + +/** + Creates an `NSURLSessionDataTask` with the specified request. + + @param request The HTTP request for the request. + @param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. + @param downloadProgressBlock A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue. + @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. + */ +- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request + uploadProgress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock + downloadProgress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; + +///--------------------------- +/// @name Running Upload Tasks +///--------------------------- + +/** + Creates an `NSURLSessionUploadTask` with the specified request for a local file. + + @param request The HTTP request for the request. + @param fileURL A URL to the local file to be uploaded. + @param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. + @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. + + @see `attemptsToRecreateUploadTasksForBackgroundSessions` + */ +- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request + fromFile:(NSURL *)fileURL + progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; + +/** + Creates an `NSURLSessionUploadTask` with the specified request for an HTTP body. + + @param request The HTTP request for the request. + @param bodyData A data object containing the HTTP body to be uploaded. + @param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. + @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. + */ +- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request + fromData:(nullable NSData *)bodyData + progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; + +/** + Creates an `NSURLSessionUploadTask` with the specified streaming request. + + @param request The HTTP request for the request. + @param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. + @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. + */ +- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request + progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; + +///----------------------------- +/// @name Running Download Tasks +///----------------------------- + +/** + Creates an `NSURLSessionDownloadTask` with the specified request. + + @param request The HTTP request for the request. + @param downloadProgressBlock A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue. + @param destination A block object to be executed in order to determine the destination of the downloaded file. This block takes two arguments, the target path & the server response, and returns the desired file URL of the resulting download. The temporary file used during the download will be automatically deleted after being moved to the returned URL. + @param completionHandler A block to be executed when a task finishes. This block has no return value and takes three arguments: the server response, the path of the downloaded file, and the error describing the network or parsing error that occurred, if any. + + @warning If using a background `NSURLSessionConfiguration` on iOS, these blocks will be lost when the app is terminated. Background sessions may prefer to use `-setDownloadTaskDidFinishDownloadingBlock:` to specify the URL for saving the downloaded file, rather than the destination block of this method. + */ +- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request + progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock + destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination + completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * _Nullable filePath, NSError * _Nullable error))completionHandler; + +/** + Creates an `NSURLSessionDownloadTask` with the specified resume data. + + @param resumeData The data used to resume downloading. + @param downloadProgressBlock A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue. + @param destination A block object to be executed in order to determine the destination of the downloaded file. This block takes two arguments, the target path & the server response, and returns the desired file URL of the resulting download. The temporary file used during the download will be automatically deleted after being moved to the returned URL. + @param completionHandler A block to be executed when a task finishes. This block has no return value and takes three arguments: the server response, the path of the downloaded file, and the error describing the network or parsing error that occurred, if any. + */ +- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData + progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock + destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination + completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * _Nullable filePath, NSError * _Nullable error))completionHandler; + +///--------------------------------- +/// @name Getting Progress for Tasks +///--------------------------------- + +/** + Returns the upload progress of the specified task. + + @param task The session task. Must not be `nil`. + + @return An `NSProgress` object reporting the upload progress of a task, or `nil` if the progress is unavailable. + */ +- (nullable NSProgress *)uploadProgressForTask:(NSURLSessionTask *)task; + +/** + Returns the download progress of the specified task. + + @param task The session task. Must not be `nil`. + + @return An `NSProgress` object reporting the download progress of a task, or `nil` if the progress is unavailable. + */ +- (nullable NSProgress *)downloadProgressForTask:(NSURLSessionTask *)task; + +///----------------------------------------- +/// @name Setting Session Delegate Callbacks +///----------------------------------------- + +/** + Sets a block to be executed when the managed session becomes invalid, as handled by the `NSURLSessionDelegate` method `URLSession:didBecomeInvalidWithError:`. + + @param block A block object to be executed when the managed session becomes invalid. The block has no return value, and takes two arguments: the session, and the error related to the cause of invalidation. + */ +- (void)setSessionDidBecomeInvalidBlock:(nullable void (^)(NSURLSession *session, NSError *error))block; + +/** + Sets a block to be executed when a connection level authentication challenge has occurred, as handled by the `NSURLSessionDelegate` method `URLSession:didReceiveChallenge:completionHandler:`. + + @param block A block object to be executed when a connection level authentication challenge has occurred. The block returns the disposition of the authentication challenge, and takes three arguments: the session, the authentication challenge, and a pointer to the credential that should be used to resolve the challenge. + + @warning Implementing a session authentication challenge handler yourself totally bypasses AFNetworking's security policy defined in `AFSecurityPolicy`. Make sure you fully understand the implications before implementing a custom session authentication challenge handler. If you do not want to bypass AFNetworking's security policy, use `setTaskDidReceiveAuthenticationChallengeBlock:` instead. + + @see -securityPolicy + @see -setTaskDidReceiveAuthenticationChallengeBlock: + */ +- (void)setSessionDidReceiveAuthenticationChallengeBlock:(nullable NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * _Nullable __autoreleasing * _Nullable credential))block; + +///-------------------------------------- +/// @name Setting Task Delegate Callbacks +///-------------------------------------- + +/** + Sets a block to be executed when a task requires a new request body stream to send to the remote server, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:needNewBodyStream:`. + + @param block A block object to be executed when a task requires a new request body stream. + */ +- (void)setTaskNeedNewBodyStreamBlock:(nullable NSInputStream * (^)(NSURLSession *session, NSURLSessionTask *task))block; + +/** + Sets a block to be executed when an HTTP request is attempting to perform a redirection to a different URL, as handled by the `NSURLSessionTaskDelegate` method `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:`. + + @param block A block object to be executed when an HTTP request is attempting to perform a redirection to a different URL. The block returns the request to be made for the redirection, and takes four arguments: the session, the task, the redirection response, and the request corresponding to the redirection response. + */ +- (void)setTaskWillPerformHTTPRedirectionBlock:(nullable NSURLRequest * _Nullable (^)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request))block; + +/** + Sets a block to be executed when a session task has received a request specific authentication challenge, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didReceiveChallenge:completionHandler:`. + + @param authenticationChallengeHandler A block object to be executed when a session task has received a request specific authentication challenge. + + When implementing an authentication challenge handler, you should check the authentication method first (`challenge.protectionSpace.authenticationMethod `) to decide if you want to handle the authentication challenge yourself or if you want AFNetworking to handle it. If you want AFNetworking to handle the authentication challenge, just return `@(NSURLSessionAuthChallengePerformDefaultHandling)`. For example, you certainly want AFNetworking to handle certificate validation (i.e. authentication method == `NSURLAuthenticationMethodServerTrust`) as defined by the security policy. If you want to handle the challenge yourself, you have four options: + + 1. Return `nil` from the authentication challenge handler. You **MUST** call the completion handler with a disposition and credentials yourself. Use this if you need to present a user interface to let the user enter their credentials. + 2. Return an `NSError` object from the authentication challenge handler. You **MUST NOT** call the completion handler when returning an `NSError `. The returned error will be reported in the completion handler of the task. Use this if you need to abort an authentication challenge with a specific error. + 3. Return an `NSURLCredential` object from the authentication challenge handler. You **MUST NOT** call the completion handler when returning an `NSURLCredential`. The returned credentials will be used to fulfil the challenge. Use this when you can get credentials without presenting a user interface. + 4. Return an `NSNumber` object wrapping an `NSURLSessionAuthChallengeDisposition`. Supported values are `@(NSURLSessionAuthChallengePerformDefaultHandling)`, `@(NSURLSessionAuthChallengeCancelAuthenticationChallenge)` and `@(NSURLSessionAuthChallengeRejectProtectionSpace)`. You **MUST NOT** call the completion handler when returning an `NSNumber`. + + If you return anything else from the authentication challenge handler, an exception will be thrown. + + For more information about how URL sessions handle the different types of authentication challenges, see [NSURLSession](https://developer.apple.com/reference/foundation/nsurlsession?language=objc) and [URL Session Programming Guide](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html). + + @see -securityPolicy + */ +- (void)setAuthenticationChallengeHandler:(id (^)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, void (^completionHandler)(NSURLSessionAuthChallengeDisposition , NSURLCredential * _Nullable)))authenticationChallengeHandler; + +/** + Sets a block to be executed periodically to track upload progress, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`. + + @param block A block object to be called when an undetermined number of bytes have been uploaded to the server. This block has no return value and takes five arguments: the session, the task, the number of bytes written since the last time the upload progress block was called, the total bytes written, and the total bytes expected to be written during the request, as initially determined by the length of the HTTP body. This block may be called multiple times, and will execute on the main thread. + */ +- (void)setTaskDidSendBodyDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))block; + +/** + Sets a block to be executed as the last message related to a specific task, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didCompleteWithError:`. + + @param block A block object to be executed when a session task is completed. The block has no return value, and takes three arguments: the session, the task, and any error that occurred in the process of executing the task. + */ +- (void)setTaskDidCompleteBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, NSError * _Nullable error))block; + +/** + Sets a block to be executed when metrics are finalized related to a specific task, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didFinishCollectingMetrics:`. + + @param block A block object to be executed when a session task is completed. The block has no return value, and takes three arguments: the session, the task, and any metrics that were collected in the process of executing the task. + */ +#if AF_CAN_INCLUDE_SESSION_TASK_METRICS +- (void)setTaskDidFinishCollectingMetricsBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, NSURLSessionTaskMetrics * _Nullable metrics))block AF_API_AVAILABLE(ios(10), macosx(10.12), watchos(3), tvos(10)); +#endif +///------------------------------------------- +/// @name Setting Data Task Delegate Callbacks +///------------------------------------------- + +/** + Sets a block to be executed when a data task has received a response, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveResponse:completionHandler:`. + + @param block A block object to be executed when a data task has received a response. The block returns the disposition of the session response, and takes three arguments: the session, the data task, and the received response. + */ +- (void)setDataTaskDidReceiveResponseBlock:(nullable NSURLSessionResponseDisposition (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response))block; + +/** + Sets a block to be executed when a data task has become a download task, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didBecomeDownloadTask:`. + + @param block A block object to be executed when a data task has become a download task. The block has no return value, and takes three arguments: the session, the data task, and the download task it has become. + */ +- (void)setDataTaskDidBecomeDownloadTaskBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask))block; + +/** + Sets a block to be executed when a data task receives data, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveData:`. + + @param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes three arguments: the session, the data task, and the data received. This block may be called multiple times, and will execute on the session manager operation queue. + */ +- (void)setDataTaskDidReceiveDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data))block; + +/** + Sets a block to be executed to determine the caching behavior of a data task, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:willCacheResponse:completionHandler:`. + + @param block A block object to be executed to determine the caching behavior of a data task. The block returns the response to cache, and takes three arguments: the session, the data task, and the proposed cached URL response. + */ +- (void)setDataTaskWillCacheResponseBlock:(nullable NSCachedURLResponse * (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse))block; + +/** + Sets a block to be executed once all messages enqueued for a session have been delivered, as handled by the `NSURLSessionDataDelegate` method `URLSessionDidFinishEventsForBackgroundURLSession:`. + + @param block A block object to be executed once all messages enqueued for a session have been delivered. The block has no return value and takes a single argument: the session. + */ +- (void)setDidFinishEventsForBackgroundURLSessionBlock:(nullable void (^)(NSURLSession *session))block AF_API_UNAVAILABLE(macos); + +///----------------------------------------------- +/// @name Setting Download Task Delegate Callbacks +///----------------------------------------------- + +/** + Sets a block to be executed when a download task has completed a download, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didFinishDownloadingToURL:`. + + @param block A block object to be executed when a download task has completed. The block returns the URL the download should be moved to, and takes three arguments: the session, the download task, and the temporary location of the downloaded file. If the file manager encounters an error while attempting to move the temporary file to the destination, an `AFURLSessionDownloadTaskDidFailToMoveFileNotification` will be posted, with the download task as its object, and the user info of the error. + */ +- (void)setDownloadTaskDidFinishDownloadingBlock:(nullable NSURL * _Nullable (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block; + +/** + Sets a block to be executed periodically to track download progress, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:`. + + @param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes five arguments: the session, the download task, the number of bytes read since the last time the download progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times, and will execute on the session manager operation queue. + */ +- (void)setDownloadTaskDidWriteDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite))block; + +/** + Sets a block to be executed when a download task has been resumed, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`. + + @param block A block object to be executed when a download task has been resumed. The block has no return value and takes four arguments: the session, the download task, the file offset of the resumed download, and the total number of bytes expected to be downloaded. + */ +- (void)setDownloadTaskDidResumeBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes))block; + +@end + +///-------------------- +/// @name Notifications +///-------------------- + +/** + Posted when a task resumes. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidResumeNotification; + +/** + Posted when a task finishes executing. Includes a userInfo dictionary with additional information about the task. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteNotification; + +/** + Posted when a task suspends its execution. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidSuspendNotification; + +/** + Posted when a session is invalidated. + */ +FOUNDATION_EXPORT NSString * const AFURLSessionDidInvalidateNotification; + +/** + Posted when a session download task finished moving the temporary download file to a specified destination successfully. + */ +FOUNDATION_EXPORT NSString * const AFURLSessionDownloadTaskDidMoveFileSuccessfullyNotification; + +/** + Posted when a session download task encountered an error when moving the temporary download file to a specified destination. + */ +FOUNDATION_EXPORT NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification; + +/** + The raw response data of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if response data exists for the task. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteResponseDataKey; + +/** + The serialized response object of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if the response was serialized. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey; + +/** + The response serializer used to serialize the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if the task has an associated response serializer. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey; + +/** + The file path associated with the download task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if an the response data has been stored directly to disk. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteAssetPathKey; + +/** + Any error associated with the task, or the serialization of the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if an error exists. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteErrorKey; + +/** + The session task metrics taken from the download task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteSessionTaskMetrics` + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteSessionTaskMetrics; + +NS_ASSUME_NONNULL_END diff --git a/Pods/AFNetworking/AFNetworking/AFURLSessionManager.m b/Pods/AFNetworking/AFNetworking/AFURLSessionManager.m new file mode 100644 index 0000000..c8b6810 --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFURLSessionManager.m @@ -0,0 +1,1274 @@ +// AFURLSessionManager.m +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFURLSessionManager.h" +#import + +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 AFURLSessionDownloadTaskDidMoveFileSuccessfullyNotification = @"com.alamofire.networking.session.download.file-manager-succeed"; +NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification = @"com.alamofire.networking.session.download.file-manager-error"; + +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 AFNetworkingTaskDidCompleteSessionTaskMetrics = @"com.alamofire.networking.complete.sessiontaskmetrics"; + +static NSString * const AFURLSessionManagerLockName = @"com.alamofire.networking.session.manager.lock"; + +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 id (^AFURLSessionTaskAuthenticationChallengeBlock)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, void (^completionHandler)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *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); +#if AF_CAN_INCLUDE_SESSION_TASK_METRICS +typedef void (^AFURLSessionTaskDidFinishCollectingMetricsBlock)(NSURLSession *session, NSURLSessionTask *task, NSURLSessionTaskMetrics * metrics) AF_API_AVAILABLE(ios(10), macosx(10.12), watchos(3), tvos(10)); +#endif + +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 (^AFURLSessionTaskProgressBlock)(NSProgress *); + +typedef void (^AFURLSessionTaskCompletionHandler)(NSURLResponse *response, id responseObject, NSError *error); + +#pragma mark - + +@interface AFURLSessionManagerTaskDelegate : NSObject +- (instancetype)initWithTask:(NSURLSessionTask *)task; +@property (nonatomic, weak) AFURLSessionManager *manager; +@property (nonatomic, strong) NSMutableData *mutableData; +@property (nonatomic, strong) NSProgress *uploadProgress; +@property (nonatomic, strong) NSProgress *downloadProgress; +@property (nonatomic, copy) NSURL *downloadFileURL; +#if AF_CAN_INCLUDE_SESSION_TASK_METRICS +@property (nonatomic, strong) NSURLSessionTaskMetrics *sessionTaskMetrics AF_API_AVAILABLE(ios(10), macosx(10.12), watchos(3), tvos(10)); +#endif +@property (nonatomic, copy) AFURLSessionDownloadTaskDidFinishDownloadingBlock downloadTaskDidFinishDownloading; +@property (nonatomic, copy) AFURLSessionTaskProgressBlock uploadProgressBlock; +@property (nonatomic, copy) AFURLSessionTaskProgressBlock downloadProgressBlock; +@property (nonatomic, copy) AFURLSessionTaskCompletionHandler completionHandler; +@end + +@implementation AFURLSessionManagerTaskDelegate + +- (instancetype)initWithTask:(NSURLSessionTask *)task { + self = [super init]; + if (!self) { + return nil; + } + + _mutableData = [NSMutableData data]; + _uploadProgress = [[NSProgress alloc] initWithParent:nil userInfo:nil]; + _downloadProgress = [[NSProgress alloc] initWithParent:nil userInfo:nil]; + + __weak __typeof__(task) weakTask = task; + for (NSProgress *progress in @[ _uploadProgress, _downloadProgress ]) + { + progress.totalUnitCount = NSURLSessionTransferSizeUnknown; + progress.cancellable = YES; + progress.cancellationHandler = ^{ + [weakTask cancel]; + }; + progress.pausable = YES; + progress.pausingHandler = ^{ + [weakTask suspend]; + }; +#if AF_CAN_USE_AT_AVAILABLE + if (@available(macOS 10.11, *)) +#else + if ([progress respondsToSelector:@selector(setResumingHandler:)]) +#endif + { + progress.resumingHandler = ^{ + [weakTask resume]; + }; + } + + [progress addObserver:self + forKeyPath:NSStringFromSelector(@selector(fractionCompleted)) + options:NSKeyValueObservingOptionNew + context:NULL]; + } + return self; +} + +- (void)dealloc { + [self.downloadProgress removeObserver:self forKeyPath:NSStringFromSelector(@selector(fractionCompleted))]; + [self.uploadProgress removeObserver:self forKeyPath:NSStringFromSelector(@selector(fractionCompleted))]; +} + +#pragma mark - NSProgress Tracking + +- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { + if ([object isEqual:self.downloadProgress]) { + if (self.downloadProgressBlock) { + self.downloadProgressBlock(object); + } + } + else if ([object isEqual:self.uploadProgress]) { + if (self.uploadProgressBlock) { + self.uploadProgressBlock(object); + } + } +} + +static const void * const AuthenticationChallengeErrorKey = &AuthenticationChallengeErrorKey; + +#pragma mark - NSURLSessionTaskDelegate + +- (void)URLSession:(__unused NSURLSession *)session + task:(NSURLSessionTask *)task +didCompleteWithError:(NSError *)error +{ + error = objc_getAssociatedObject(task, AuthenticationChallengeErrorKey) ?: error; + __strong AFURLSessionManager *manager = self.manager; + + __block id responseObject = nil; + + 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 AF_CAN_USE_AT_AVAILABLE && AF_CAN_INCLUDE_SESSION_TASK_METRICS + if (@available(iOS 10, macOS 10.12, watchOS 3, tvOS 10, *)) { + if (self.sessionTaskMetrics) { + userInfo[AFNetworkingTaskDidCompleteSessionTaskMetrics] = self.sessionTaskMetrics; + } + } +#endif + + 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]; + }); + }); + }); + } +} + +#if AF_CAN_INCLUDE_SESSION_TASK_METRICS +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task +didFinishCollectingMetrics:(NSURLSessionTaskMetrics *)metrics AF_API_AVAILABLE(ios(10), macosx(10.12), watchos(3), tvos(10)) { + self.sessionTaskMetrics = metrics; +} +#endif + +#pragma mark - NSURLSessionDataDelegate + +- (void)URLSession:(__unused NSURLSession *)session + dataTask:(__unused NSURLSessionDataTask *)dataTask + didReceiveData:(NSData *)data +{ + self.downloadProgress.totalUnitCount = dataTask.countOfBytesExpectedToReceive; + self.downloadProgress.completedUnitCount = dataTask.countOfBytesReceived; + + [self.mutableData appendData:data]; +} + +- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task + didSendBodyData:(int64_t)bytesSent + totalBytesSent:(int64_t)totalBytesSent +totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend{ + + self.uploadProgress.totalUnitCount = task.countOfBytesExpectedToSend; + self.uploadProgress.completedUnitCount = task.countOfBytesSent; +} + +#pragma mark - NSURLSessionDownloadDelegate + +- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask + didWriteData:(int64_t)bytesWritten + totalBytesWritten:(int64_t)totalBytesWritten +totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{ + + self.downloadProgress.totalUnitCount = totalBytesExpectedToWrite; + self.downloadProgress.completedUnitCount = totalBytesWritten; +} + +- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask + didResumeAtOffset:(int64_t)fileOffset +expectedTotalBytes:(int64_t)expectedTotalBytes{ + + self.downloadProgress.totalUnitCount = expectedTotalBytes; + self.downloadProgress.completedUnitCount = fileOffset; +} + +- (void)URLSession:(NSURLSession *)session + downloadTask:(NSURLSessionDownloadTask *)downloadTask +didFinishDownloadingToURL:(NSURL *)location +{ + self.downloadFileURL = nil; + + if (self.downloadTaskDidFinishDownloading) { + self.downloadFileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location); + if (self.downloadFileURL) { + NSError *fileManagerError = nil; + + if (![[NSFileManager defaultManager] moveItemAtURL:location toURL:self.downloadFileURL error:&fileManagerError]) { + [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:fileManagerError.userInfo]; + } else { + [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidMoveFileSuccessfullyNotification object:downloadTask userInfo:nil]; + } + } + } +} + +@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 theClass, SEL originalSelector, SEL swizzledSelector) { + Method originalMethod = class_getInstanceMethod(theClass, originalSelector); + Method swizzledMethod = class_getInstanceMethod(theClass, swizzledSelector); + method_exchangeImplementations(originalMethod, swizzledMethod); +} + +static inline BOOL af_addMethod(Class theClass, SEL selector, Method method) { + return class_addMethod(theClass, 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 + */ + NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration]; + NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration]; +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wnonnull" + NSURLSessionDataTask *localDataTask = [session dataTaskWithURL:nil]; +#pragma clang diagnostic pop + IMP originalAFResumeIMP = method_getImplementation(class_getInstanceMethod([self 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]; + [session finishTasksAndInvalidate]; + } +} + ++ (void)swizzleResumeAndSuspendMethodForClass:(Class)theClass { + Method afResumeMethod = class_getInstanceMethod(self, @selector(af_resume)); + Method afSuspendMethod = class_getInstanceMethod(self, @selector(af_suspend)); + + if (af_addMethod(theClass, @selector(af_resume), afResumeMethod)) { + af_swizzleSelector(theClass, @selector(resume), @selector(af_resume)); + } + + if (af_addMethod(theClass, @selector(af_suspend), afSuspendMethod)) { + af_swizzleSelector(theClass, @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 AF_API_UNAVAILABLE(macos); +@property (readwrite, nonatomic, copy) AFURLSessionTaskWillPerformHTTPRedirectionBlock taskWillPerformHTTPRedirection; +@property (readwrite, nonatomic, copy) AFURLSessionTaskAuthenticationChallengeBlock authenticationChallengeHandler; +@property (readwrite, nonatomic, copy) AFURLSessionTaskNeedNewBodyStreamBlock taskNeedNewBodyStream; +@property (readwrite, nonatomic, copy) AFURLSessionTaskDidSendBodyDataBlock taskDidSendBodyData; +@property (readwrite, nonatomic, copy) AFURLSessionTaskDidCompleteBlock taskDidComplete; +#if AF_CAN_INCLUDE_SESSION_TASK_METRICS +@property (readwrite, nonatomic, copy) AFURLSessionTaskDidFinishCollectingMetricsBlock taskDidFinishCollectingMetrics AF_API_AVAILABLE(ios(10), macosx(10.12), watchos(3), tvos(10)); +#endif +@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.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 uploadProgress:nil downloadProgress:nil 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]; + } + }]; + + return self; +} + +- (void)dealloc { + [[NSNotificationCenter defaultCenter] removeObserver:self]; +} + +#pragma mark - + +- (NSURLSession *)session { + + @synchronized (self) { + if (!_session) { + _session = [NSURLSession sessionWithConfiguration:self.sessionConfiguration delegate:self delegateQueue:self.operationQueue]; + } + } + return _session; +} + +#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 addNotificationObserverForTask:task]; + [self.lock unlock]; +} + +- (void)addDelegateForDataTask:(NSURLSessionDataTask *)dataTask + uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock + downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler +{ + AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] initWithTask:dataTask]; + delegate.manager = self; + delegate.completionHandler = completionHandler; + + dataTask.taskDescription = self.taskDescriptionForSessionTasks; + [self setDelegate:delegate forTask:dataTask]; + + delegate.uploadProgressBlock = uploadProgressBlock; + delegate.downloadProgressBlock = downloadProgressBlock; +} + +- (void)addDelegateForUploadTask:(NSURLSessionUploadTask *)uploadTask + progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler +{ + AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] initWithTask:uploadTask]; + delegate.manager = self; + delegate.completionHandler = completionHandler; + + uploadTask.taskDescription = self.taskDescriptionForSessionTasks; + + [self setDelegate:delegate forTask:uploadTask]; + + delegate.uploadProgressBlock = uploadProgressBlock; +} + +- (void)addDelegateForDownloadTask:(NSURLSessionDownloadTask *)downloadTask + progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock + destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination + completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler +{ + AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] initWithTask:downloadTask]; + delegate.manager = self; + delegate.completionHandler = completionHandler; + + if (destination) { + delegate.downloadTaskDidFinishDownloading = ^NSURL * (NSURLSession * __unused session, NSURLSessionDownloadTask *task, NSURL *location) { + return destination(location, task.response); + }; + } + + downloadTask.taskDescription = self.taskDescriptionForSessionTasks; + + [self setDelegate:delegate forTask:downloadTask]; + + delegate.downloadProgressBlock = downloadProgressBlock; +} + +- (void)removeDelegateForTask:(NSURLSessionTask *)task { + NSParameterAssert(task); + + [self.lock lock]; + [self removeNotificationObserverForTask:task]; + [self.mutableTaskDelegatesKeyedByTaskIdentifier removeObjectForKey:@(task.taskIdentifier)]; + [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 resetSession:(BOOL)resetSession { + if (cancelPendingTasks) { + [self.session invalidateAndCancel]; + } else { + [self.session finishTasksAndInvalidate]; + } + if (resetSession) { + self.session = nil; + } +} + +#pragma mark - + +- (void)setResponseSerializer:(id )responseSerializer { + NSParameterAssert(responseSerializer); + + _responseSerializer = responseSerializer; +} + +#pragma mark - +- (void)addNotificationObserverForTask:(NSURLSessionTask *)task { + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidResume:) name:AFNSURLSessionTaskDidResumeNotification object:task]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidSuspend:) name:AFNSURLSessionTaskDidSuspendNotification object:task]; +} + +- (void)removeNotificationObserverForTask:(NSURLSessionTask *)task { + [[NSNotificationCenter defaultCenter] removeObserver:self name:AFNSURLSessionTaskDidSuspendNotification object:task]; + [[NSNotificationCenter defaultCenter] removeObserver:self name:AFNSURLSessionTaskDidResumeNotification object:task]; +} + +#pragma mark - + +- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request + uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock + downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler { + + NSURLSessionDataTask *dataTask = [self.session dataTaskWithRequest:request]; + + [self addDelegateForDataTask:dataTask uploadProgress:uploadProgressBlock downloadProgress:downloadProgressBlock completionHandler:completionHandler]; + + return dataTask; +} + +#pragma mark - + +- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request + fromFile:(NSURL *)fileURL + progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler +{ + NSURLSessionUploadTask *uploadTask = [self.session uploadTaskWithRequest:request fromFile:fileURL]; + + if (uploadTask) { + [self addDelegateForUploadTask:uploadTask + progress:uploadProgressBlock + completionHandler:completionHandler]; + } + + return uploadTask; +} + +- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request + fromData:(NSData *)bodyData + progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler +{ + NSURLSessionUploadTask *uploadTask = [self.session uploadTaskWithRequest:request fromData:bodyData]; + + [self addDelegateForUploadTask:uploadTask progress:uploadProgressBlock completionHandler:completionHandler]; + + return uploadTask; +} + +- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request + progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler +{ + NSURLSessionUploadTask *uploadTask = [self.session uploadTaskWithStreamedRequest:request]; + + [self addDelegateForUploadTask:uploadTask progress:uploadProgressBlock completionHandler:completionHandler]; + + return uploadTask; +} + +#pragma mark - + +- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request + progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock + destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination + completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler +{ + NSURLSessionDownloadTask *downloadTask = [self.session downloadTaskWithRequest:request]; + + [self addDelegateForDownloadTask:downloadTask progress:downloadProgressBlock destination:destination completionHandler:completionHandler]; + + return downloadTask; +} + +- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData + progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock + destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination + completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler +{ + NSURLSessionDownloadTask *downloadTask = [self.session downloadTaskWithResumeData:resumeData]; + + [self addDelegateForDownloadTask:downloadTask progress:downloadProgressBlock destination:destination completionHandler:completionHandler]; + + return downloadTask; +} + +#pragma mark - +- (NSProgress *)uploadProgressForTask:(NSURLSessionTask *)task { + return [[self delegateForTask:task] uploadProgress]; +} + +- (NSProgress *)downloadProgressForTask:(NSURLSessionTask *)task { + return [[self delegateForTask:task] downloadProgress]; +} + +#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; +} + +#if !TARGET_OS_OSX +- (void)setDidFinishEventsForBackgroundURLSessionBlock:(void (^)(NSURLSession *session))block { + self.didFinishEventsForBackgroundURLSession = block; +} +#endif + +#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)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; +} + +#if AF_CAN_INCLUDE_SESSION_TASK_METRICS +- (void)setTaskDidFinishCollectingMetricsBlock:(void (^)(NSURLSession * _Nonnull, NSURLSessionTask * _Nonnull, NSURLSessionTaskMetrics * _Nullable))block AF_API_AVAILABLE(ios(10), macosx(10.12), watchos(3), tvos(10)) { + self.taskDidFinishCollectingMetrics = block; +} +#endif + +#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:didReceiveChallenge:completionHandler:)) { + return self.sessionDidReceiveAuthenticationChallenge != nil; + } else 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; + } +#if !TARGET_OS_OSX + else if (selector == @selector(URLSessionDidFinishEventsForBackgroundURLSession:)) { + return self.didFinishEventsForBackgroundURLSession != nil; + } +#endif + + return [[self class] instancesRespondToSelector:selector]; +} + +#pragma mark - NSURLSessionDelegate + +- (void)URLSession:(NSURLSession *)session +didBecomeInvalidWithError:(NSError *)error +{ + if (self.sessionDidBecomeInvalid) { + self.sessionDidBecomeInvalid(session, error); + } + + [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDidInvalidateNotification object:session]; +} + +- (void)URLSession:(NSURLSession *)session +didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge + completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler +{ + NSAssert(self.sessionDidReceiveAuthenticationChallenge != nil, @"`respondsToSelector:` implementation forces `URLSession:didReceiveChallenge:completionHandler:` to be called only if `self.sessionDidReceiveAuthenticationChallenge` is not nil"); + + NSURLCredential *credential = nil; + NSURLSessionAuthChallengeDisposition disposition = self.sessionDidReceiveAuthenticationChallenge(session, challenge, &credential); + + 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 +{ + BOOL evaluateServerTrust = NO; + NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling; + NSURLCredential *credential = nil; + + if (self.authenticationChallengeHandler) { + id result = self.authenticationChallengeHandler(session, task, challenge, completionHandler); + if (result == nil) { + return; + } else if ([result isKindOfClass:NSError.class]) { + objc_setAssociatedObject(task, AuthenticationChallengeErrorKey, result, OBJC_ASSOCIATION_RETAIN); + disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge; + } else if ([result isKindOfClass:NSURLCredential.class]) { + credential = result; + disposition = NSURLSessionAuthChallengeUseCredential; + } else if ([result isKindOfClass:NSNumber.class]) { + disposition = [result integerValue]; + NSAssert(disposition == NSURLSessionAuthChallengePerformDefaultHandling || disposition == NSURLSessionAuthChallengeCancelAuthenticationChallenge || disposition == NSURLSessionAuthChallengeRejectProtectionSpace, @""); + evaluateServerTrust = disposition == NSURLSessionAuthChallengePerformDefaultHandling && [challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]; + } else { + @throw [NSException exceptionWithName:@"Invalid Return Value" reason:@"The return value from the authentication challenge handler must be nil, an NSError, an NSURLCredential or an NSNumber." userInfo:nil]; + } + } else { + evaluateServerTrust = [challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]; + } + + if (evaluateServerTrust) { + if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) { + disposition = NSURLSessionAuthChallengeUseCredential; + credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; + } else { + objc_setAssociatedObject(task, AuthenticationChallengeErrorKey, + [self serverTrustErrorForServerTrust:challenge.protectionSpace.serverTrust url:task.currentRequest.URL], + OBJC_ASSOCIATION_RETAIN); + disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge; + } + } + + if (completionHandler) { + completionHandler(disposition, credential); + } +} + +- (nonnull NSError *)serverTrustErrorForServerTrust:(nullable SecTrustRef)serverTrust url:(nullable NSURL *)url +{ + NSBundle *CFNetworkBundle = [NSBundle bundleWithIdentifier:@"com.apple.CFNetwork"]; + NSString *defaultValue = @"The certificate for this server is invalid. You might be connecting to a server that is pretending to be “%@” which could put your confidential information at risk."; + NSString *descriptionFormat = NSLocalizedStringWithDefaultValue(@"Err-1202.w", nil, CFNetworkBundle, defaultValue, @"") ?: defaultValue; + NSString *localizedDescription = [descriptionFormat componentsSeparatedByString:@"%@"].count <= 2 ? [NSString localizedStringWithFormat:descriptionFormat, url.host] : descriptionFormat; + NSMutableDictionary *userInfo = [@{ + NSLocalizedDescriptionKey: localizedDescription + } mutableCopy]; + + if (serverTrust) { + userInfo[NSURLErrorFailingURLPeerTrustErrorKey] = (__bridge id)serverTrust; + } + + if (url) { + userInfo[NSURLErrorFailingURLErrorKey] = url; + + if (url.absoluteString) { + userInfo[NSURLErrorFailingURLStringErrorKey] = url.absoluteString; + } + } + + return [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorServerCertificateUntrusted userInfo:userInfo]; +} + +- (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]; + + if (delegate) { + [delegate URLSession:session task:task didSendBodyData:bytesSent totalBytesSent:totalBytesSent totalBytesExpectedToSend:totalBytesExpectedToSend]; + } + + 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); + } +} + +#if AF_CAN_INCLUDE_SESSION_TASK_METRICS +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task +didFinishCollectingMetrics:(NSURLSessionTaskMetrics *)metrics AF_API_AVAILABLE(ios(10), macosx(10.12), watchos(3), tvos(10)) +{ + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task]; + // Metrics may fire after URLSession:task:didCompleteWithError: is called, delegate may be nil + if (delegate) { + [delegate URLSession:session task:task didFinishCollectingMetrics:metrics]; + } + + if (self.taskDidFinishCollectingMetrics) { + self.taskDidFinishCollectingMetrics(session, task, metrics); + } +} +#endif + +#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); + } +} + +#if !TARGET_OS_OSX +- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session { + if (self.didFinishEventsForBackgroundURLSession) { + dispatch_async(dispatch_get_main_queue(), ^{ + self.didFinishEventsForBackgroundURLSession(session); + }); + } +} +#endif + +#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; + + if (![[NSFileManager defaultManager] moveItemAtURL:location toURL:fileURL error:&error]) { + [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:error.userInfo]; + } else { + [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidMoveFileSuccessfullyNotification object:downloadTask userInfo:nil]; + } + + 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]; + + if (delegate) { + [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]; + + if (delegate) { + [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; +} + +- (instancetype)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 + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[[self class] allocWithZone:zone] initWithSessionConfiguration:self.session.configuration]; +} + +@end diff --git a/Pods/AFNetworking/LICENSE b/Pods/AFNetworking/LICENSE new file mode 100644 index 0000000..f611f42 --- /dev/null +++ b/Pods/AFNetworking/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2011-2020 Alamofire Software Foundation (http://alamofire.org/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/Pods/AFNetworking/README.md b/Pods/AFNetworking/README.md new file mode 100644 index 0000000..d193dfe --- /dev/null +++ b/Pods/AFNetworking/README.md @@ -0,0 +1,298 @@ +

+ AFNetworking +

+ +[![Build Status](https://github.com/AFNetworking/AFNetworking/workflows/AFNetworking%20CI/badge.svg?branch=master)](https://github.com/AFNetworking/AFNetworking/actions) +[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/AFNetworking.svg)](https://img.shields.io/cocoapods/v/AFNetworking.svg) +[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) +[![Platform](https://img.shields.io/cocoapods/p/AFNetworking.svg?style=flat)](http://cocoadocs.org/docsets/AFNetworking) +[![Twitter](https://img.shields.io/badge/twitter-@AFNetworking-blue.svg?style=flat)](http://twitter.com/AFNetworking) + +AFNetworking is a delightful networking library for iOS, macOS, watchOS, and tvOS. It's built on top of the [Foundation URL Loading System](https://developer.apple.com/documentation/foundation/url_loading_system), extending the powerful high-level networking abstractions built into Cocoa. It has a modular architecture with well-designed, feature-rich APIs that are a joy to use. + +Perhaps the most important feature of all, however, is the amazing community of developers who use and contribute to AFNetworking every day. AFNetworking powers some of the most popular and critically-acclaimed apps on the iPhone, iPad, and Mac. + +## How To Get Started + +- [Download AFNetworking](https://github.com/AFNetworking/AFNetworking/archive/master.zip) and try out the included Mac and iPhone example apps +- Read the ["Getting Started" guide](https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking), [FAQ](https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ), or [other articles on the Wiki](https://github.com/AFNetworking/AFNetworking/wiki) + +## Communication + +- If you **need help**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/afnetworking). (Tag 'afnetworking') +- If you'd like to **ask a general question**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/afnetworking). +- If you **found a bug**, _and can provide steps to reliably reproduce it_, open an issue. +- If you **have a feature request**, open an issue. +- If you **want to contribute**, submit a pull request. + +## Installation +AFNetworking supports multiple methods for installing the library in a project. + +## Installation with CocoaPods + +To integrate AFNetworking into your Xcode project using CocoaPods, specify it in your `Podfile`: + +```ruby +pod 'AFNetworking', '~> 4.0' +``` + +### Installation with Swift Package Manager + +Once you have your Swift package set up, adding AFNetworking as a dependency is as easy as adding it to the `dependencies` value of your `Package.swift`. + +```swift +dependencies: [ + .package(url: "https://github.com/AFNetworking/AFNetworking.git", .upToNextMajor(from: "4.0.0")) +] +``` + +> Note: AFNetworking's Swift package does not include it's UIKit extensions. + +### Installation with Carthage + +[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. To integrate AFNetworking, add the following to your `Cartfile`. + +```ogdl +github "AFNetworking/AFNetworking" ~> 4.0 +``` + +## Requirements + +| AFNetworking Version | Minimum iOS Target | Minimum macOS Target | Minimum watchOS Target | Minimum tvOS Target | Notes | +|:--------------------:|:---------------------------:|:----------------------------:|:----------------------------:|:----------------------------:|:-------------------------------------------------------------------------:| +| 4.x | iOS 9 | macOS 10.10 | watchOS 2.0 | tvOS 9.0 | Xcode 11+ is required. | +| 3.x | iOS 7 | OS X 10.9 | watchOS 2.0 | tvOS 9.0 | Xcode 7+ is required. `NSURLConnectionOperation` support has been removed. | +| 2.6 -> 2.6.3 | iOS 7 | OS X 10.9 | watchOS 2.0 | n/a | Xcode 7+ is required. | +| 2.0 -> 2.5.4 | iOS 6 | OS X 10.8 | n/a | n/a | Xcode 5+ is required. `NSURLSession` subspec requires iOS 7 or OS X 10.9. | +| 1.x | iOS 5 | Mac OS X 10.7 | n/a | n/a | +| 0.10.x | iOS 4 | Mac OS X 10.6 | n/a | n/a | + +(macOS projects must support [64-bit with modern Cocoa runtime](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtVersionsPlatforms.html)). + +> Programming in Swift? Try [Alamofire](https://github.com/Alamofire/Alamofire) for a more conventional set of APIs. + +## Architecture + +### NSURLSession + +- `AFURLSessionManager` +- `AFHTTPSessionManager` + +### Serialization + +* `` + - `AFHTTPRequestSerializer` + - `AFJSONRequestSerializer` + - `AFPropertyListRequestSerializer` +* `` + - `AFHTTPResponseSerializer` + - `AFJSONResponseSerializer` + - `AFXMLParserResponseSerializer` + - `AFXMLDocumentResponseSerializer` _(macOS)_ + - `AFPropertyListResponseSerializer` + - `AFImageResponseSerializer` + - `AFCompoundResponseSerializer` + +### Additional Functionality + +- `AFSecurityPolicy` +- `AFNetworkReachabilityManager` + +## Usage + +### AFURLSessionManager + +`AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to ``, ``, ``, and ``. + +#### Creating a Download Task + +```objective-c +NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; +AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; + +NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"]; +NSURLRequest *request = [NSURLRequest requestWithURL:URL]; + +NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) { + NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil]; + return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]]; +} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) { + NSLog(@"File downloaded to: %@", filePath); +}]; +[downloadTask resume]; +``` + +#### Creating an Upload Task + +```objective-c +NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; +AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; + +NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"]; +NSURLRequest *request = [NSURLRequest requestWithURL:URL]; + +NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"]; +NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + if (error) { + NSLog(@"Error: %@", error); + } else { + NSLog(@"Success: %@ %@", response, responseObject); + } +}]; +[uploadTask resume]; +``` + +#### Creating an Upload Task for a Multi-Part Request, with Progress + +```objective-c +NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id formData) { + [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil]; + } error:nil]; + +AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; + +NSURLSessionUploadTask *uploadTask; +uploadTask = [manager + uploadTaskWithStreamedRequest:request + progress:^(NSProgress * _Nonnull uploadProgress) { + // This is not called back on the main queue. + // You are responsible for dispatching to the main queue for UI updates + dispatch_async(dispatch_get_main_queue(), ^{ + //Update the progress view + [progressView setProgress:uploadProgress.fractionCompleted]; + }); + } + completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { + if (error) { + NSLog(@"Error: %@", error); + } else { + NSLog(@"%@ %@", response, responseObject); + } + }]; + +[uploadTask resume]; +``` + +#### Creating a Data Task + +```objective-c +NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; +AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; + +NSURL *URL = [NSURL URLWithString:@"http://httpbin.org/get"]; +NSURLRequest *request = [NSURLRequest requestWithURL:URL]; + +NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + if (error) { + NSLog(@"Error: %@", error); + } else { + NSLog(@"%@ %@", response, responseObject); + } +}]; +[dataTask resume]; +``` + +--- + +### Request Serialization + +Request serializers create requests from URL strings, encoding parameters as either a query string or HTTP body. + +```objective-c +NSString *URLString = @"http://example.com"; +NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]}; +``` + +#### Query String Parameter Encoding + +```objective-c +[[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil]; +``` + + GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3 + +#### URL Form Parameter Encoding + +```objective-c +[[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil]; +``` + + POST http://example.com/ + Content-Type: application/x-www-form-urlencoded + + foo=bar&baz[]=1&baz[]=2&baz[]=3 + +#### JSON Parameter Encoding + +```objective-c +[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil]; +``` + + POST http://example.com/ + Content-Type: application/json + + {"foo": "bar", "baz": [1,2,3]} + +--- + +### Network Reachability Manager + +`AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces. + +* Do not use Reachability to determine if the original request should be sent. + * You should try to send it. +* You can use Reachability to determine when a request should be automatically retried. + * Although it may still fail, a Reachability notification that the connectivity is available is a good time to retry something. +* Network reachability is a useful tool for determining why a request might have failed. + * After a network request has failed, telling the user they're offline is better than giving them a more technical but accurate error, such as "request timed out." + +See also [WWDC 2012 session 706, "Networking Best Practices."](https://developer.apple.com/videos/play/wwdc2012-706/). + +#### Shared Network Reachability + +```objective-c +[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { + NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status)); +}]; + +[[AFNetworkReachabilityManager sharedManager] startMonitoring]; +``` + +--- + +### Security Policy + +`AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections. + +Adding pinned SSL certificates to your app helps prevent man-in-the-middle attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with SSL pinning configured and enabled. + +#### Allowing Invalid SSL Certificates + +```objective-c +AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; +manager.securityPolicy.allowInvalidCertificates = YES; // not recommended for production +``` + +--- + +## Unit Tests + +AFNetworking includes a suite of unit tests within the Tests subdirectory. These tests can be run simply be executed the test action on the platform framework you would like to test. + +## Credits + +AFNetworking is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org). + +AFNetworking was originally created by [Scott Raymond](https://github.com/sco/) and [Mattt Thompson](https://github.com/mattt/) in the development of [Gowalla for iPhone](http://en.wikipedia.org/wiki/Gowalla). + +AFNetworking's logo was designed by [Alan Defibaugh](http://www.alandefibaugh.com/). + +And most of all, thanks to AFNetworking's [growing list of contributors](https://github.com/AFNetworking/AFNetworking/contributors). + +### Security Disclosure + +If you believe you have identified a security vulnerability with AFNetworking, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker. + +## License + +AFNetworking is released under the MIT license. See [LICENSE](https://github.com/AFNetworking/AFNetworking/blob/master/LICENSE) for details. diff --git a/Pods/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.h b/Pods/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.h new file mode 100644 index 0000000..1a27bb4 --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.h @@ -0,0 +1,160 @@ +// AFAutoPurgingImageCache.h +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import +#import + +#if TARGET_OS_IOS || TARGET_OS_TV +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + The `AFImageCache` protocol defines a set of APIs for adding, removing and fetching images from a cache synchronously. + */ +@protocol AFImageCache + +/** + Adds the image to the cache with the given identifier. + + @param image The image to cache. + @param identifier The unique identifier for the image in the cache. + */ +- (void)addImage:(UIImage *)image withIdentifier:(NSString *)identifier; + +/** + Removes the image from the cache matching the given identifier. + + @param identifier The unique identifier for the image in the cache. + + @return A BOOL indicating whether or not the image was removed from the cache. + */ +- (BOOL)removeImageWithIdentifier:(NSString *)identifier; + +/** + Removes all images from the cache. + + @return A BOOL indicating whether or not all images were removed from the cache. + */ +- (BOOL)removeAllImages; + +/** + Returns the image in the cache associated with the given identifier. + + @param identifier The unique identifier for the image in the cache. + + @return An image for the matching identifier, or nil. + */ +- (nullable UIImage *)imageWithIdentifier:(NSString *)identifier; +@end + + +/** + The `ImageRequestCache` protocol extends the `ImageCache` protocol by adding methods for adding, removing and fetching images from a cache given an `NSURLRequest` and additional identifier. + */ +@protocol AFImageRequestCache + +/** + Asks if the image should be cached using an identifier created from the request and additional identifier. + + @param image The image to be cached. + @param request The unique URL request identifing the image asset. + @param identifier The additional identifier to apply to the URL request to identify the image. + + @return A BOOL indicating whether or not the image should be added to the cache. YES will cache, NO will prevent caching. + */ +- (BOOL)shouldCacheImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier; + +/** + Adds the image to the cache using an identifier created from the request and additional identifier. + + @param image The image to cache. + @param request The unique URL request identifing the image asset. + @param identifier The additional identifier to apply to the URL request to identify the image. + */ +- (void)addImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier; + +/** + Removes the image from the cache using an identifier created from the request and additional identifier. + + @param request The unique URL request identifing the image asset. + @param identifier The additional identifier to apply to the URL request to identify the image. + + @return A BOOL indicating whether or not all images were removed from the cache. + */ +- (BOOL)removeImageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier; + +/** + Returns the image from the cache associated with an identifier created from the request and additional identifier. + + @param request The unique URL request identifing the image asset. + @param identifier The additional identifier to apply to the URL request to identify the image. + + @return An image for the matching request and identifier, or nil. + */ +- (nullable UIImage *)imageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier; + +@end + +/** + The `AutoPurgingImageCache` in an in-memory image cache used to store images up to a given memory capacity. When the memory capacity is reached, the image cache is sorted by last access date, then the oldest image is continuously purged until the preferred memory usage after purge is met. Each time an image is accessed through the cache, the internal access date of the image is updated. + */ +@interface AFAutoPurgingImageCache : NSObject + +/** + The total memory capacity of the cache in bytes. + */ +@property (nonatomic, assign) UInt64 memoryCapacity; + +/** + The preferred memory usage after purge in bytes. During a purge, images will be purged until the memory capacity drops below this limit. + */ +@property (nonatomic, assign) UInt64 preferredMemoryUsageAfterPurge; + +/** + The current total memory usage in bytes of all images stored within the cache. + */ +@property (nonatomic, assign, readonly) UInt64 memoryUsage; + +/** + Initialies the `AutoPurgingImageCache` instance with default values for memory capacity and preferred memory usage after purge limit. `memoryCapcity` defaults to `100 MB`. `preferredMemoryUsageAfterPurge` defaults to `60 MB`. + + @return The new `AutoPurgingImageCache` instance. + */ +- (instancetype)init; + +/** + Initialies the `AutoPurgingImageCache` instance with the given memory capacity and preferred memory usage + after purge limit. + + @param memoryCapacity The total memory capacity of the cache in bytes. + @param preferredMemoryCapacity The preferred memory usage after purge in bytes. + + @return The new `AutoPurgingImageCache` instance. + */ +- (instancetype)initWithMemoryCapacity:(UInt64)memoryCapacity preferredMemoryCapacity:(UInt64)preferredMemoryCapacity; + +@end + +NS_ASSUME_NONNULL_END + +#endif + diff --git a/Pods/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.m b/Pods/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.m new file mode 100644 index 0000000..a09e87c --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.m @@ -0,0 +1,205 @@ +// AFAutoPurgingImageCache.m +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import "AFAutoPurgingImageCache.h" + +@interface AFCachedImage : NSObject + +@property (nonatomic, strong) UIImage *image; +@property (nonatomic, copy) NSString *identifier; +@property (nonatomic, assign) UInt64 totalBytes; +@property (nonatomic, strong) NSDate *lastAccessDate; +@property (nonatomic, assign) UInt64 currentMemoryUsage; + +@end + +@implementation AFCachedImage + +- (instancetype)initWithImage:(UIImage *)image identifier:(NSString *)identifier { + if (self = [self init]) { + self.image = image; + self.identifier = identifier; + + CGSize imageSize = CGSizeMake(image.size.width * image.scale, image.size.height * image.scale); + CGFloat bytesPerPixel = 4.0; + CGFloat bytesPerSize = imageSize.width * imageSize.height; + self.totalBytes = (UInt64)bytesPerPixel * (UInt64)bytesPerSize; + self.lastAccessDate = [NSDate date]; + } + return self; +} + +- (UIImage *)accessImage { + self.lastAccessDate = [NSDate date]; + return self.image; +} + +- (NSString *)description { + NSString *descriptionString = [NSString stringWithFormat:@"Idenfitier: %@ lastAccessDate: %@ ", self.identifier, self.lastAccessDate]; + return descriptionString; + +} + +@end + +@interface AFAutoPurgingImageCache () +@property (nonatomic, strong) NSMutableDictionary *cachedImages; +@property (nonatomic, assign) UInt64 currentMemoryUsage; +@property (nonatomic, strong) dispatch_queue_t synchronizationQueue; +@end + +@implementation AFAutoPurgingImageCache + +- (instancetype)init { + return [self initWithMemoryCapacity:100 * 1024 * 1024 preferredMemoryCapacity:60 * 1024 * 1024]; +} + +- (instancetype)initWithMemoryCapacity:(UInt64)memoryCapacity preferredMemoryCapacity:(UInt64)preferredMemoryCapacity { + if (self = [super init]) { + self.memoryCapacity = memoryCapacity; + self.preferredMemoryUsageAfterPurge = preferredMemoryCapacity; + self.cachedImages = [[NSMutableDictionary alloc] init]; + + NSString *queueName = [NSString stringWithFormat:@"com.alamofire.autopurgingimagecache-%@", [[NSUUID UUID] UUIDString]]; + self.synchronizationQueue = dispatch_queue_create([queueName cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_CONCURRENT); + + [[NSNotificationCenter defaultCenter] + addObserver:self + selector:@selector(removeAllImages) + name:UIApplicationDidReceiveMemoryWarningNotification + object:nil]; + + } + return self; +} + +- (void)dealloc { + [[NSNotificationCenter defaultCenter] removeObserver:self]; +} + +- (UInt64)memoryUsage { + __block UInt64 result = 0; + dispatch_sync(self.synchronizationQueue, ^{ + result = self.currentMemoryUsage; + }); + return result; +} + +- (void)addImage:(UIImage *)image withIdentifier:(NSString *)identifier { + dispatch_barrier_async(self.synchronizationQueue, ^{ + AFCachedImage *cacheImage = [[AFCachedImage alloc] initWithImage:image identifier:identifier]; + + AFCachedImage *previousCachedImage = self.cachedImages[identifier]; + if (previousCachedImage != nil) { + self.currentMemoryUsage -= previousCachedImage.totalBytes; + } + + self.cachedImages[identifier] = cacheImage; + self.currentMemoryUsage += cacheImage.totalBytes; + }); + + dispatch_barrier_async(self.synchronizationQueue, ^{ + if (self.currentMemoryUsage > self.memoryCapacity) { + UInt64 bytesToPurge = self.currentMemoryUsage - self.preferredMemoryUsageAfterPurge; + NSMutableArray *sortedImages = [NSMutableArray arrayWithArray:self.cachedImages.allValues]; + NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"lastAccessDate" + ascending:YES]; + [sortedImages sortUsingDescriptors:@[sortDescriptor]]; + + UInt64 bytesPurged = 0; + + for (AFCachedImage *cachedImage in sortedImages) { + [self.cachedImages removeObjectForKey:cachedImage.identifier]; + bytesPurged += cachedImage.totalBytes; + if (bytesPurged >= bytesToPurge) { + break; + } + } + self.currentMemoryUsage -= bytesPurged; + } + }); +} + +- (BOOL)removeImageWithIdentifier:(NSString *)identifier { + __block BOOL removed = NO; + dispatch_barrier_sync(self.synchronizationQueue, ^{ + AFCachedImage *cachedImage = self.cachedImages[identifier]; + if (cachedImage != nil) { + [self.cachedImages removeObjectForKey:identifier]; + self.currentMemoryUsage -= cachedImage.totalBytes; + removed = YES; + } + }); + return removed; +} + +- (BOOL)removeAllImages { + __block BOOL removed = NO; + dispatch_barrier_sync(self.synchronizationQueue, ^{ + if (self.cachedImages.count > 0) { + [self.cachedImages removeAllObjects]; + self.currentMemoryUsage = 0; + removed = YES; + } + }); + return removed; +} + +- (nullable UIImage *)imageWithIdentifier:(NSString *)identifier { + __block UIImage *image = nil; + dispatch_sync(self.synchronizationQueue, ^{ + AFCachedImage *cachedImage = self.cachedImages[identifier]; + image = [cachedImage accessImage]; + }); + return image; +} + +- (void)addImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier { + [self addImage:image withIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]]; +} + +- (BOOL)removeImageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier { + return [self removeImageWithIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]]; +} + +- (nullable UIImage *)imageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier { + return [self imageWithIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]]; +} + +- (NSString *)imageCacheKeyFromURLRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)additionalIdentifier { + NSString *key = request.URL.absoluteString; + if (additionalIdentifier != nil) { + key = [key stringByAppendingString:additionalIdentifier]; + } + return key; +} + +- (BOOL)shouldCacheImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier { + return YES; +} + +@end + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/AFImageDownloader.h b/Pods/AFNetworking/UIKit+AFNetworking/AFImageDownloader.h new file mode 100644 index 0000000..3bf5a32 --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/AFImageDownloader.h @@ -0,0 +1,171 @@ +// AFImageDownloader.h +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import +#import "AFAutoPurgingImageCache.h" +#import "AFHTTPSessionManager.h" + +NS_ASSUME_NONNULL_BEGIN + +typedef NS_ENUM(NSInteger, AFImageDownloadPrioritization) { + AFImageDownloadPrioritizationFIFO, + AFImageDownloadPrioritizationLIFO +}; + +/** + The `AFImageDownloadReceipt` is an object vended by the `AFImageDownloader` when starting a data task. It can be used to cancel active tasks running on the `AFImageDownloader` session. As a general rule, image data tasks should be cancelled using the `AFImageDownloadReceipt` instead of calling `cancel` directly on the `task` itself. The `AFImageDownloader` is optimized to handle duplicate task scenarios as well as pending versus active downloads. + */ +@interface AFImageDownloadReceipt : NSObject + +/** + The data task created by the `AFImageDownloader`. +*/ +@property (nonatomic, strong) NSURLSessionDataTask *task; + +/** + The unique identifier for the success and failure blocks when duplicate requests are made. + */ +@property (nonatomic, strong) NSUUID *receiptID; +@end + +/** The `AFImageDownloader` class is responsible for downloading images in parallel on a prioritized queue. Incoming downloads are added to the front or back of the queue depending on the download prioritization. Each downloaded image is cached in the underlying `NSURLCache` as well as the in-memory image cache. By default, any download request with a cached image equivalent in the image cache will automatically be served the cached image representation. + */ +@interface AFImageDownloader : NSObject + +/** + The image cache used to store all downloaded images in. `AFAutoPurgingImageCache` by default. + */ +@property (nonatomic, strong, nullable) id imageCache; + +/** + The `AFHTTPSessionManager` used to download images. By default, this is configured with an `AFImageResponseSerializer`, and a shared `NSURLCache` for all image downloads. + */ +@property (nonatomic, strong) AFHTTPSessionManager *sessionManager; + +/** + Defines the order prioritization of incoming download requests being inserted into the queue. `AFImageDownloadPrioritizationFIFO` by default. + */ +@property (nonatomic, assign) AFImageDownloadPrioritization downloadPrioritization; + +/** + The shared default instance of `AFImageDownloader` initialized with default values. + */ ++ (instancetype)defaultInstance; + +/** + Creates a default `NSURLCache` with common usage parameter values. + + @returns The default `NSURLCache` instance. + */ ++ (NSURLCache *)defaultURLCache; + +/** + The default `NSURLSessionConfiguration` with common usage parameter values. + */ ++ (NSURLSessionConfiguration *)defaultURLSessionConfiguration; + +/** + Default initializer + + @return An instance of `AFImageDownloader` initialized with default values. + */ +- (instancetype)init; + +/** + Initializer with specific `URLSessionConfiguration` + + @param configuration The `NSURLSessionConfiguration` to be be used + + @return An instance of `AFImageDownloader` initialized with default values and custom `NSURLSessionConfiguration` + */ +- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration; + +/** + Initializes the `AFImageDownloader` instance with the given session manager, download prioritization, maximum active download count and image cache. + + @param sessionManager The session manager to use to download images. + @param downloadPrioritization The download prioritization of the download queue. + @param maximumActiveDownloads The maximum number of active downloads allowed at any given time. Recommend `4`. + @param imageCache The image cache used to store all downloaded images in. + + @return The new `AFImageDownloader` instance. + */ +- (instancetype)initWithSessionManager:(AFHTTPSessionManager *)sessionManager + downloadPrioritization:(AFImageDownloadPrioritization)downloadPrioritization + maximumActiveDownloads:(NSInteger)maximumActiveDownloads + imageCache:(nullable id )imageCache; + +/** + Creates a data task using the `sessionManager` instance for the specified URL request. + + If the same data task is already in the queue or currently being downloaded, the success and failure blocks are + appended to the already existing task. Once the task completes, all success or failure blocks attached to the + task are executed in the order they were added. + + @param request The URL request. + @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. + @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. + + @return The image download receipt for the data task if available. `nil` if the image is stored in the cache. + cache and the URL request cache policy allows the cache to be used. + */ +- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; + +/** + Creates a data task using the `sessionManager` instance for the specified URL request. + + If the same data task is already in the queue or currently being downloaded, the success and failure blocks are + appended to the already existing task. Once the task completes, all success or failure blocks attached to the + task are executed in the order they were added. + + @param request The URL request. + @param receiptID The identifier to use for the download receipt that will be created for this request. This must be a unique identifier that does not represent any other request. + @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. + @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. + + @return The image download receipt for the data task if available. `nil` if the image is stored in the cache. + cache and the URL request cache policy allows the cache to be used. + */ +- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request + withReceiptID:(NSUUID *)receiptID + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; + +/** + Cancels the data task in the receipt by removing the corresponding success and failure blocks and cancelling the data task if necessary. + + If the data task is pending in the queue, it will be cancelled if no other success and failure blocks are registered with the data task. If the data task is currently executing or is already completed, the success and failure blocks are removed and will not be called when the task finishes. + + @param imageDownloadReceipt The image download receipt to cancel. + */ +- (void)cancelTaskForImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt; + +@end + +#endif + +NS_ASSUME_NONNULL_END diff --git a/Pods/AFNetworking/UIKit+AFNetworking/AFImageDownloader.m b/Pods/AFNetworking/UIKit+AFNetworking/AFImageDownloader.m new file mode 100644 index 0000000..008a782 --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/AFImageDownloader.m @@ -0,0 +1,421 @@ +// AFImageDownloader.m +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import "AFImageDownloader.h" +#import "AFHTTPSessionManager.h" + +@interface AFImageDownloaderResponseHandler : NSObject +@property (nonatomic, strong) NSUUID *uuid; +@property (nonatomic, copy) void (^successBlock)(NSURLRequest *, NSHTTPURLResponse *, UIImage *); +@property (nonatomic, copy) void (^failureBlock)(NSURLRequest *, NSHTTPURLResponse *, NSError *); +@end + +@implementation AFImageDownloaderResponseHandler + +- (instancetype)initWithUUID:(NSUUID *)uuid + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure { + if (self = [self init]) { + self.uuid = uuid; + self.successBlock = success; + self.failureBlock = failure; + } + return self; +} + +- (NSString *)description { + return [NSString stringWithFormat: @"UUID: %@", [self.uuid UUIDString]]; +} + +@end + +@interface AFImageDownloaderMergedTask : NSObject +@property (nonatomic, strong) NSString *URLIdentifier; +@property (nonatomic, strong) NSUUID *identifier; +@property (nonatomic, strong) NSURLSessionDataTask *task; +@property (nonatomic, strong) NSMutableArray *responseHandlers; + +@end + +@implementation AFImageDownloaderMergedTask + +- (instancetype)initWithURLIdentifier:(NSString *)URLIdentifier identifier:(NSUUID *)identifier task:(NSURLSessionDataTask *)task { + if (self = [self init]) { + self.URLIdentifier = URLIdentifier; + self.task = task; + self.identifier = identifier; + self.responseHandlers = [[NSMutableArray alloc] init]; + } + return self; +} + +- (void)addResponseHandler:(AFImageDownloaderResponseHandler *)handler { + [self.responseHandlers addObject:handler]; +} + +- (void)removeResponseHandler:(AFImageDownloaderResponseHandler *)handler { + [self.responseHandlers removeObject:handler]; +} + +@end + +@implementation AFImageDownloadReceipt + +- (instancetype)initWithReceiptID:(NSUUID *)receiptID task:(NSURLSessionDataTask *)task { + if (self = [self init]) { + self.receiptID = receiptID; + self.task = task; + } + return self; +} + +@end + +@interface AFImageDownloader () + +@property (nonatomic, strong) dispatch_queue_t synchronizationQueue; +@property (nonatomic, strong) dispatch_queue_t responseQueue; + +@property (nonatomic, assign) NSInteger maximumActiveDownloads; +@property (nonatomic, assign) NSInteger activeRequestCount; + +@property (nonatomic, strong) NSMutableArray *queuedMergedTasks; +@property (nonatomic, strong) NSMutableDictionary *mergedTasks; + +@end + +@implementation AFImageDownloader + ++ (NSURLCache *)defaultURLCache { + NSUInteger memoryCapacity = 20 * 1024 * 1024; // 20MB + NSUInteger diskCapacity = 150 * 1024 * 1024; // 150MB + NSURL *cacheURL = [[[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory + inDomain:NSUserDomainMask + appropriateForURL:nil + create:YES + error:nil] + URLByAppendingPathComponent:@"com.alamofire.imagedownloader"]; + +#if TARGET_OS_MACCATALYST + return [[NSURLCache alloc] initWithMemoryCapacity:memoryCapacity + diskCapacity:diskCapacity + directoryURL:cacheURL]; +#else + return [[NSURLCache alloc] initWithMemoryCapacity:memoryCapacity + diskCapacity:diskCapacity + diskPath:[cacheURL path]]; +#endif +} + ++ (NSURLSessionConfiguration *)defaultURLSessionConfiguration { + NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; + + //TODO set the default HTTP headers + + configuration.HTTPShouldSetCookies = YES; + configuration.HTTPShouldUsePipelining = NO; + + configuration.requestCachePolicy = NSURLRequestUseProtocolCachePolicy; + configuration.allowsCellularAccess = YES; + configuration.timeoutIntervalForRequest = 60.0; + configuration.URLCache = [AFImageDownloader defaultURLCache]; + + return configuration; +} + +- (instancetype)init { + NSURLSessionConfiguration *defaultConfiguration = [self.class defaultURLSessionConfiguration]; + return [self initWithSessionConfiguration:defaultConfiguration]; +} + +- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration { + AFHTTPSessionManager *sessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration]; + sessionManager.responseSerializer = [AFImageResponseSerializer serializer]; + + return [self initWithSessionManager:sessionManager + downloadPrioritization:AFImageDownloadPrioritizationFIFO + maximumActiveDownloads:4 + imageCache:[[AFAutoPurgingImageCache alloc] init]]; +} + +- (instancetype)initWithSessionManager:(AFHTTPSessionManager *)sessionManager + downloadPrioritization:(AFImageDownloadPrioritization)downloadPrioritization + maximumActiveDownloads:(NSInteger)maximumActiveDownloads + imageCache:(id )imageCache { + if (self = [super init]) { + self.sessionManager = sessionManager; + + self.downloadPrioritization = downloadPrioritization; + self.maximumActiveDownloads = maximumActiveDownloads; + self.imageCache = imageCache; + + self.queuedMergedTasks = [[NSMutableArray alloc] init]; + self.mergedTasks = [[NSMutableDictionary alloc] init]; + self.activeRequestCount = 0; + + NSString *name = [NSString stringWithFormat:@"com.alamofire.imagedownloader.synchronizationqueue-%@", [[NSUUID UUID] UUIDString]]; + self.synchronizationQueue = dispatch_queue_create([name cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_SERIAL); + + name = [NSString stringWithFormat:@"com.alamofire.imagedownloader.responsequeue-%@", [[NSUUID UUID] UUIDString]]; + self.responseQueue = dispatch_queue_create([name cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_CONCURRENT); + } + + return self; +} + ++ (instancetype)defaultInstance { + static AFImageDownloader *sharedInstance = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + sharedInstance = [[self alloc] init]; + }); + return sharedInstance; +} + +- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request + success:(void (^)(NSURLRequest * _Nonnull, NSHTTPURLResponse * _Nullable, UIImage * _Nonnull))success + failure:(void (^)(NSURLRequest * _Nonnull, NSHTTPURLResponse * _Nullable, NSError * _Nonnull))failure { + return [self downloadImageForURLRequest:request withReceiptID:[NSUUID UUID] success:success failure:failure]; +} + +- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request + withReceiptID:(nonnull NSUUID *)receiptID + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure { + __block NSURLSessionDataTask *task = nil; + dispatch_sync(self.synchronizationQueue, ^{ + NSString *URLIdentifier = request.URL.absoluteString; + if (URLIdentifier == nil) { + if (failure) { + NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorBadURL userInfo:nil]; + dispatch_async(dispatch_get_main_queue(), ^{ + failure(request, nil, error); + }); + } + return; + } + + // 1) Append the success and failure blocks to a pre-existing request if it already exists + AFImageDownloaderMergedTask *existingMergedTask = self.mergedTasks[URLIdentifier]; + if (existingMergedTask != nil) { + AFImageDownloaderResponseHandler *handler = [[AFImageDownloaderResponseHandler alloc] initWithUUID:receiptID success:success failure:failure]; + [existingMergedTask addResponseHandler:handler]; + task = existingMergedTask.task; + return; + } + + // 2) Attempt to load the image from the image cache if the cache policy allows it + switch (request.cachePolicy) { + case NSURLRequestUseProtocolCachePolicy: + case NSURLRequestReturnCacheDataElseLoad: + case NSURLRequestReturnCacheDataDontLoad: { + UIImage *cachedImage = [self.imageCache imageforRequest:request withAdditionalIdentifier:nil]; + if (cachedImage != nil) { + if (success) { + dispatch_async(dispatch_get_main_queue(), ^{ + success(request, nil, cachedImage); + }); + } + return; + } + break; + } + default: + break; + } + + // 3) Create the request and set up authentication, validation and response serialization + NSUUID *mergedTaskIdentifier = [NSUUID UUID]; + NSURLSessionDataTask *createdTask; + __weak __typeof__(self) weakSelf = self; + + createdTask = [self.sessionManager + dataTaskWithRequest:request + uploadProgress:nil + downloadProgress:nil + completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { + dispatch_async(self.responseQueue, ^{ + __strong __typeof__(weakSelf) strongSelf = weakSelf; + AFImageDownloaderMergedTask *mergedTask = [strongSelf safelyGetMergedTask:URLIdentifier]; + if ([mergedTask.identifier isEqual:mergedTaskIdentifier]) { + mergedTask = [strongSelf safelyRemoveMergedTaskWithURLIdentifier:URLIdentifier]; + if (error) { + for (AFImageDownloaderResponseHandler *handler in mergedTask.responseHandlers) { + if (handler.failureBlock) { + dispatch_async(dispatch_get_main_queue(), ^{ + handler.failureBlock(request, (NSHTTPURLResponse *)response, error); + }); + } + } + } else { + if ([strongSelf.imageCache shouldCacheImage:responseObject forRequest:request withAdditionalIdentifier:nil]) { + [strongSelf.imageCache addImage:responseObject forRequest:request withAdditionalIdentifier:nil]; + } + + for (AFImageDownloaderResponseHandler *handler in mergedTask.responseHandlers) { + if (handler.successBlock) { + dispatch_async(dispatch_get_main_queue(), ^{ + handler.successBlock(request, (NSHTTPURLResponse *)response, responseObject); + }); + } + } + + } + } + [strongSelf safelyDecrementActiveTaskCount]; + [strongSelf safelyStartNextTaskIfNecessary]; + }); + }]; + + // 4) Store the response handler for use when the request completes + AFImageDownloaderResponseHandler *handler = [[AFImageDownloaderResponseHandler alloc] initWithUUID:receiptID + success:success + failure:failure]; + AFImageDownloaderMergedTask *mergedTask = [[AFImageDownloaderMergedTask alloc] + initWithURLIdentifier:URLIdentifier + identifier:mergedTaskIdentifier + task:createdTask]; + [mergedTask addResponseHandler:handler]; + self.mergedTasks[URLIdentifier] = mergedTask; + + // 5) Either start the request or enqueue it depending on the current active request count + if ([self isActiveRequestCountBelowMaximumLimit]) { + [self startMergedTask:mergedTask]; + } else { + [self enqueueMergedTask:mergedTask]; + } + + task = mergedTask.task; + }); + if (task) { + return [[AFImageDownloadReceipt alloc] initWithReceiptID:receiptID task:task]; + } else { + return nil; + } +} + +- (void)cancelTaskForImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt { + dispatch_sync(self.synchronizationQueue, ^{ + NSString *URLIdentifier = imageDownloadReceipt.task.originalRequest.URL.absoluteString; + AFImageDownloaderMergedTask *mergedTask = self.mergedTasks[URLIdentifier]; + NSUInteger index = [mergedTask.responseHandlers indexOfObjectPassingTest:^BOOL(AFImageDownloaderResponseHandler * _Nonnull handler, __unused NSUInteger idx, __unused BOOL * _Nonnull stop) { + return handler.uuid == imageDownloadReceipt.receiptID; + }]; + + if (index != NSNotFound) { + AFImageDownloaderResponseHandler *handler = mergedTask.responseHandlers[index]; + [mergedTask removeResponseHandler:handler]; + NSString *failureReason = [NSString stringWithFormat:@"ImageDownloader cancelled URL request: %@",imageDownloadReceipt.task.originalRequest.URL.absoluteString]; + NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey:failureReason}; + NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo]; + if (handler.failureBlock) { + dispatch_async(dispatch_get_main_queue(), ^{ + handler.failureBlock(imageDownloadReceipt.task.originalRequest, nil, error); + }); + } + } + + if (mergedTask.responseHandlers.count == 0) { + [mergedTask.task cancel]; + [self removeMergedTaskWithURLIdentifier:URLIdentifier]; + } + }); +} + +- (AFImageDownloaderMergedTask *)safelyRemoveMergedTaskWithURLIdentifier:(NSString *)URLIdentifier { + __block AFImageDownloaderMergedTask *mergedTask = nil; + dispatch_sync(self.synchronizationQueue, ^{ + mergedTask = [self removeMergedTaskWithURLIdentifier:URLIdentifier]; + }); + return mergedTask; +} + +//This method should only be called from safely within the synchronizationQueue +- (AFImageDownloaderMergedTask *)removeMergedTaskWithURLIdentifier:(NSString *)URLIdentifier { + AFImageDownloaderMergedTask *mergedTask = self.mergedTasks[URLIdentifier]; + [self.mergedTasks removeObjectForKey:URLIdentifier]; + return mergedTask; +} + +- (void)safelyDecrementActiveTaskCount { + dispatch_sync(self.synchronizationQueue, ^{ + if (self.activeRequestCount > 0) { + self.activeRequestCount -= 1; + } + }); +} + +- (void)safelyStartNextTaskIfNecessary { + dispatch_sync(self.synchronizationQueue, ^{ + if ([self isActiveRequestCountBelowMaximumLimit]) { + while (self.queuedMergedTasks.count > 0) { + AFImageDownloaderMergedTask *mergedTask = [self dequeueMergedTask]; + if (mergedTask.task.state == NSURLSessionTaskStateSuspended) { + [self startMergedTask:mergedTask]; + break; + } + } + } + }); +} + +- (void)startMergedTask:(AFImageDownloaderMergedTask *)mergedTask { + [mergedTask.task resume]; + ++self.activeRequestCount; +} + +- (void)enqueueMergedTask:(AFImageDownloaderMergedTask *)mergedTask { + switch (self.downloadPrioritization) { + case AFImageDownloadPrioritizationFIFO: + [self.queuedMergedTasks addObject:mergedTask]; + break; + case AFImageDownloadPrioritizationLIFO: + [self.queuedMergedTasks insertObject:mergedTask atIndex:0]; + break; + } +} + +- (AFImageDownloaderMergedTask *)dequeueMergedTask { + AFImageDownloaderMergedTask *mergedTask = nil; + mergedTask = [self.queuedMergedTasks firstObject]; + [self.queuedMergedTasks removeObject:mergedTask]; + return mergedTask; +} + +- (BOOL)isActiveRequestCountBelowMaximumLimit { + return self.activeRequestCount < self.maximumActiveDownloads; +} + +- (AFImageDownloaderMergedTask *)safelyGetMergedTask:(NSString *)URLIdentifier { + __block AFImageDownloaderMergedTask *mergedTask; + dispatch_sync(self.synchronizationQueue, ^(){ + mergedTask = self.mergedTasks[URLIdentifier]; + }); + return mergedTask; +} + +@end + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h b/Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h new file mode 100644 index 0000000..3bcf289 --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h @@ -0,0 +1,103 @@ +// AFNetworkActivityIndicatorManager.h +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +#import + +#if TARGET_OS_IOS + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + `AFNetworkActivityIndicatorManager` manages the state of the network activity indicator in the status bar. When enabled, it will listen for notifications indicating that a session task has started or finished, and start or stop animating the indicator accordingly. The number of active requests is incremented and decremented much like a stack or a semaphore, and the activity indicator will animate so long as that number is greater than zero. + + You should enable the shared instance of `AFNetworkActivityIndicatorManager` when your application finishes launching. In `AppDelegate application:didFinishLaunchingWithOptions:` you can do so with the following code: + + [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES]; + + By setting `enabled` to `YES` for `sharedManager`, the network activity indicator will show and hide automatically as requests start and finish. You should not ever need to call `incrementActivityCount` or `decrementActivityCount` yourself. + + See the Apple Human Interface Guidelines section about the Network Activity Indicator for more information: + http://developer.apple.com/library/iOS/#documentation/UserExperience/Conceptual/MobileHIG/UIElementGuidelines/UIElementGuidelines.html#//apple_ref/doc/uid/TP40006556-CH13-SW44 + */ +NS_EXTENSION_UNAVAILABLE_IOS("Use view controller based solutions where appropriate instead.") +@interface AFNetworkActivityIndicatorManager : NSObject + +/** + A Boolean value indicating whether the manager is enabled. + + If YES, the manager will change status bar network activity indicator according to network operation notifications it receives. The default value is NO. + */ +@property (nonatomic, assign, getter = isEnabled) BOOL enabled; + +/** + A Boolean value indicating whether the network activity indicator manager is currently active. +*/ +@property (readonly, nonatomic, assign, getter=isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible; + +/** + A time interval indicating the minimum duration of networking activity that should occur before the activity indicator is displayed. The default value 1 second. If the network activity indicator should be displayed immediately when network activity occurs, this value should be set to 0 seconds. + + Apple's HIG describes the following: + + > Display the network activity indicator to provide feedback when your app accesses the network for more than a couple of seconds. If the operation finishes sooner than that, you don’t have to show the network activity indicator, because the indicator is likely to disappear before users notice its presence. + + */ +@property (nonatomic, assign) NSTimeInterval activationDelay; + +/** + A time interval indicating the duration of time of no networking activity required before the activity indicator is disabled. This allows for continuous display of the network activity indicator across multiple requests. The default value is 0.17 seconds. + */ + +@property (nonatomic, assign) NSTimeInterval completionDelay; + +/** + Returns the shared network activity indicator manager object for the system. + + @return The systemwide network activity indicator manager. + */ ++ (instancetype)sharedManager; + +/** + Increments the number of active network requests. If this number was zero before incrementing, this will start animating the status bar network activity indicator. + */ +- (void)incrementActivityCount; + +/** + Decrements the number of active network requests. If this number becomes zero after decrementing, this will stop animating the status bar network activity indicator. + */ +- (void)decrementActivityCount; + +/** + Set the a custom method to be executed when the network activity indicator manager should be hidden/shown. By default, this is null, and the UIApplication Network Activity Indicator will be managed automatically. If this block is set, it is the responsiblity of the caller to manager the network activity indicator going forward. + + @param block A block to be executed when the network activity indicator status changes. + */ +- (void)setNetworkingActivityActionWithBlock:(nullable void (^)(BOOL networkActivityIndicatorVisible))block; + +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m b/Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m new file mode 100644 index 0000000..8cb5677 --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m @@ -0,0 +1,239 @@ +// AFNetworkActivityIndicatorManager.m +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFNetworkActivityIndicatorManager.h" + +#if TARGET_OS_IOS +#import "AFURLSessionManager.h" + +typedef NS_ENUM(NSInteger, AFNetworkActivityManagerState) { + AFNetworkActivityManagerStateNotActive, + AFNetworkActivityManagerStateDelayingStart, + AFNetworkActivityManagerStateActive, + AFNetworkActivityManagerStateDelayingEnd +}; + +static NSTimeInterval const kDefaultAFNetworkActivityManagerActivationDelay = 1.0; +static NSTimeInterval const kDefaultAFNetworkActivityManagerCompletionDelay = 0.17; + +static NSURLRequest * AFNetworkRequestFromNotification(NSNotification *notification) { + if ([[notification object] respondsToSelector:@selector(originalRequest)]) { + return [(NSURLSessionTask *)[notification object] originalRequest]; + } else { + return nil; + } +} + +typedef void (^AFNetworkActivityActionBlock)(BOOL networkActivityIndicatorVisible); + +@interface AFNetworkActivityIndicatorManager () +@property (readwrite, nonatomic, assign) NSInteger activityCount; +@property (readwrite, nonatomic, strong) NSTimer *activationDelayTimer; +@property (readwrite, nonatomic, strong) NSTimer *completionDelayTimer; +@property (readonly, nonatomic, getter = isNetworkActivityOccurring) BOOL networkActivityOccurring; +@property (nonatomic, copy) AFNetworkActivityActionBlock networkActivityActionBlock; +@property (nonatomic, assign) AFNetworkActivityManagerState currentState; +@property (nonatomic, assign, getter=isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible; + +- (void)updateCurrentStateForNetworkActivityChange; +@end + +@implementation AFNetworkActivityIndicatorManager + ++ (instancetype)sharedManager { + static AFNetworkActivityIndicatorManager *_sharedManager = nil; + static dispatch_once_t oncePredicate; + dispatch_once(&oncePredicate, ^{ + _sharedManager = [[self alloc] init]; + }); + + return _sharedManager; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + self.currentState = AFNetworkActivityManagerStateNotActive; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidStart:) name:AFNetworkingTaskDidResumeNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingTaskDidSuspendNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingTaskDidCompleteNotification object:nil]; + self.activationDelay = kDefaultAFNetworkActivityManagerActivationDelay; + self.completionDelay = kDefaultAFNetworkActivityManagerCompletionDelay; + + return self; +} + +- (void)dealloc { + [[NSNotificationCenter defaultCenter] removeObserver:self]; + + [_activationDelayTimer invalidate]; + [_completionDelayTimer invalidate]; +} + +- (void)setEnabled:(BOOL)enabled { + _enabled = enabled; + if (enabled == NO) { + [self setCurrentState:AFNetworkActivityManagerStateNotActive]; + } +} + +- (void)setNetworkingActivityActionWithBlock:(void (^)(BOOL networkActivityIndicatorVisible))block { + self.networkActivityActionBlock = block; +} + +- (BOOL)isNetworkActivityOccurring { + @synchronized(self) { + return self.activityCount > 0; + } +} + +- (void)setNetworkActivityIndicatorVisible:(BOOL)networkActivityIndicatorVisible { + if (_networkActivityIndicatorVisible != networkActivityIndicatorVisible) { + @synchronized(self) { + _networkActivityIndicatorVisible = networkActivityIndicatorVisible; + } + if (self.networkActivityActionBlock) { + self.networkActivityActionBlock(networkActivityIndicatorVisible); + } else { + [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:networkActivityIndicatorVisible]; + } + } +} + + +- (void)incrementActivityCount { + @synchronized(self) { + self.activityCount++; + } + dispatch_async(dispatch_get_main_queue(), ^{ + [self updateCurrentStateForNetworkActivityChange]; + }); +} + +- (void)decrementActivityCount { + @synchronized(self) { + self.activityCount = MAX(_activityCount - 1, 0); + } + dispatch_async(dispatch_get_main_queue(), ^{ + [self updateCurrentStateForNetworkActivityChange]; + }); +} + +- (void)networkRequestDidStart:(NSNotification *)notification { + if ([AFNetworkRequestFromNotification(notification) URL]) { + [self incrementActivityCount]; + } +} + +- (void)networkRequestDidFinish:(NSNotification *)notification { + if ([AFNetworkRequestFromNotification(notification) URL]) { + [self decrementActivityCount]; + } +} + +#pragma mark - Internal State Management +- (void)setCurrentState:(AFNetworkActivityManagerState)currentState { + @synchronized(self) { + if (_currentState != currentState) { + _currentState = currentState; + switch (currentState) { + case AFNetworkActivityManagerStateNotActive: + [self cancelActivationDelayTimer]; + [self cancelCompletionDelayTimer]; + [self setNetworkActivityIndicatorVisible:NO]; + break; + case AFNetworkActivityManagerStateDelayingStart: + [self startActivationDelayTimer]; + break; + case AFNetworkActivityManagerStateActive: + [self cancelCompletionDelayTimer]; + [self setNetworkActivityIndicatorVisible:YES]; + break; + case AFNetworkActivityManagerStateDelayingEnd: + [self startCompletionDelayTimer]; + break; + } + } + } +} + +- (void)updateCurrentStateForNetworkActivityChange { + if (self.enabled) { + switch (self.currentState) { + case AFNetworkActivityManagerStateNotActive: + if (self.isNetworkActivityOccurring) { + [self setCurrentState:AFNetworkActivityManagerStateDelayingStart]; + } + break; + case AFNetworkActivityManagerStateDelayingStart: + //No op. Let the delay timer finish out. + break; + case AFNetworkActivityManagerStateActive: + if (!self.isNetworkActivityOccurring) { + [self setCurrentState:AFNetworkActivityManagerStateDelayingEnd]; + } + break; + case AFNetworkActivityManagerStateDelayingEnd: + if (self.isNetworkActivityOccurring) { + [self setCurrentState:AFNetworkActivityManagerStateActive]; + } + break; + } + } +} + +- (void)startActivationDelayTimer { + self.activationDelayTimer = [NSTimer + timerWithTimeInterval:self.activationDelay target:self selector:@selector(activationDelayTimerFired) userInfo:nil repeats:NO]; + [[NSRunLoop mainRunLoop] addTimer:self.activationDelayTimer forMode:NSRunLoopCommonModes]; +} + +- (void)activationDelayTimerFired { + if (self.networkActivityOccurring) { + [self setCurrentState:AFNetworkActivityManagerStateActive]; + } else { + [self setCurrentState:AFNetworkActivityManagerStateNotActive]; + } +} + +- (void)startCompletionDelayTimer { + [self.completionDelayTimer invalidate]; + self.completionDelayTimer = [NSTimer timerWithTimeInterval:self.completionDelay target:self selector:@selector(completionDelayTimerFired) userInfo:nil repeats:NO]; + [[NSRunLoop mainRunLoop] addTimer:self.completionDelayTimer forMode:NSRunLoopCommonModes]; +} + +- (void)completionDelayTimerFired { + [self setCurrentState:AFNetworkActivityManagerStateNotActive]; +} + +- (void)cancelActivationDelayTimer { + [self.activationDelayTimer invalidate]; +} + +- (void)cancelCompletionDelayTimer { + [self.completionDelayTimer invalidate]; +} + +@end + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h b/Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h new file mode 100644 index 0000000..d424c9b --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h @@ -0,0 +1,48 @@ +// UIActivityIndicatorView+AFNetworking.h +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import + +/** + This category adds methods to the UIKit framework's `UIActivityIndicatorView` class. The methods in this category provide support for automatically starting and stopping animation depending on the loading state of a session task. + */ +@interface UIActivityIndicatorView (AFNetworking) + +///---------------------------------- +/// @name Animating for Session Tasks +///---------------------------------- + +/** + Binds the animating state to the state of the specified task. + + @param task The task. If `nil`, automatic updating from any previously specified operation will be disabled. + */ +- (void)setAnimatingWithStateOfTask:(nullable NSURLSessionTask *)task; + +@end + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m b/Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m new file mode 100644 index 0000000..602a72d --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m @@ -0,0 +1,114 @@ +// UIActivityIndicatorView+AFNetworking.m +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "UIActivityIndicatorView+AFNetworking.h" +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import "AFURLSessionManager.h" + +@interface AFActivityIndicatorViewNotificationObserver : NSObject +@property (readonly, nonatomic, weak) UIActivityIndicatorView *activityIndicatorView; +- (instancetype)initWithActivityIndicatorView:(UIActivityIndicatorView *)activityIndicatorView; + +- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task; + +@end + +@implementation UIActivityIndicatorView (AFNetworking) + +- (AFActivityIndicatorViewNotificationObserver *)af_notificationObserver { + AFActivityIndicatorViewNotificationObserver *notificationObserver = objc_getAssociatedObject(self, @selector(af_notificationObserver)); + if (notificationObserver == nil) { + notificationObserver = [[AFActivityIndicatorViewNotificationObserver alloc] initWithActivityIndicatorView:self]; + objc_setAssociatedObject(self, @selector(af_notificationObserver), notificationObserver, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + return notificationObserver; +} + +- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task { + [[self af_notificationObserver] setAnimatingWithStateOfTask:task]; +} + +@end + +@implementation AFActivityIndicatorViewNotificationObserver + +- (instancetype)initWithActivityIndicatorView:(UIActivityIndicatorView *)activityIndicatorView +{ + self = [super init]; + if (self) { + _activityIndicatorView = activityIndicatorView; + } + return self; +} + +- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task { + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; + + [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; + + if (task) { + if (task.state != NSURLSessionTaskStateCompleted) { + UIActivityIndicatorView *activityIndicatorView = self.activityIndicatorView; + if (task.state == NSURLSessionTaskStateRunning) { + [activityIndicatorView startAnimating]; + } else { + [activityIndicatorView stopAnimating]; + } + + [notificationCenter addObserver:self selector:@selector(af_startAnimating) name:AFNetworkingTaskDidResumeNotification object:task]; + [notificationCenter addObserver:self selector:@selector(af_stopAnimating) name:AFNetworkingTaskDidCompleteNotification object:task]; + [notificationCenter addObserver:self selector:@selector(af_stopAnimating) name:AFNetworkingTaskDidSuspendNotification object:task]; + } + } +} + +#pragma mark - + +- (void)af_startAnimating { + dispatch_async(dispatch_get_main_queue(), ^{ + [self.activityIndicatorView startAnimating]; + }); +} + +- (void)af_stopAnimating { + dispatch_async(dispatch_get_main_queue(), ^{ + [self.activityIndicatorView stopAnimating]; + }); +} + +#pragma mark - + +- (void)dealloc { + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; + + [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; +} + +@end + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h b/Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h new file mode 100644 index 0000000..d33e0d4 --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h @@ -0,0 +1,175 @@ +// UIButton+AFNetworking.h +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import + +NS_ASSUME_NONNULL_BEGIN + +@class AFImageDownloader; + +/** + This category adds methods to the UIKit framework's `UIButton` class. The methods in this category provide support for loading remote images and background images asynchronously from a URL. + + @warning Compound values for control `state` (such as `UIControlStateHighlighted | UIControlStateDisabled`) are unsupported. + */ +@interface UIButton (AFNetworking) + +///------------------------------------ +/// @name Accessing the Image Downloader +///------------------------------------ + +/** + Set the shared image downloader used to download images. + + @param imageDownloader The shared image downloader used to download images. +*/ ++ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader; + +/** + The shared image downloader used to download images. + */ ++ (AFImageDownloader *)sharedImageDownloader; + +///-------------------- +/// @name Setting Image +///-------------------- + +/** + Asynchronously downloads an image from the specified URL, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + @param state The control state. + @param url The URL used for the image request. + */ +- (void)setImageForState:(UIControlState)state + withURL:(NSURL *)url; + +/** + Asynchronously downloads an image from the specified URL, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + @param state The control state. + @param url The URL used for the image request. + @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the button will not change its image until the image request finishes. + */ +- (void)setImageForState:(UIControlState)state + withURL:(NSURL *)url + placeholderImage:(nullable UIImage *)placeholderImage; + +/** + Asynchronously downloads an image from the specified URL request, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + If a success block is specified, it is the responsibility of the block to set the image of the button before returning. If no success block is specified, the default behavior of setting the image with `setImage:forState:` is applied. + + @param state The control state. + @param urlRequest The URL request used for the image request. + @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the button will not change its image until the image request finishes. + @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. + @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. + */ +- (void)setImageForState:(UIControlState)state + withURLRequest:(NSURLRequest *)urlRequest + placeholderImage:(nullable UIImage *)placeholderImage + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; + + +///------------------------------- +/// @name Setting Background Image +///------------------------------- + +/** + Asynchronously downloads an image from the specified URL, and sets it as the background image for the specified state once the request is finished. Any previous background image request for the receiver will be cancelled. + + If the background image is cached locally, the background image is set immediately, otherwise the specified placeholder background image will be set immediately, and then the remote background image will be set once the request is finished. + + @param state The control state. + @param url The URL used for the background image request. + */ +- (void)setBackgroundImageForState:(UIControlState)state + withURL:(NSURL *)url; + +/** + Asynchronously downloads an image from the specified URL, and sets it as the background image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + @param state The control state. + @param url The URL used for the background image request. + @param placeholderImage The background image to be set initially, until the background image request finishes. If `nil`, the button will not change its background image until the background image request finishes. + */ +- (void)setBackgroundImageForState:(UIControlState)state + withURL:(NSURL *)url + placeholderImage:(nullable UIImage *)placeholderImage; + +/** + Asynchronously downloads an image from the specified URL request, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + If a success block is specified, it is the responsibility of the block to set the image of the button before returning. If no success block is specified, the default behavior of setting the image with `setBackgroundImage:forState:` is applied. + + @param state The control state. + @param urlRequest The URL request used for the image request. + @param placeholderImage The background image to be set initially, until the background image request finishes. If `nil`, the button will not change its background image until the background image request finishes. + @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. + @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. + */ +- (void)setBackgroundImageForState:(UIControlState)state + withURLRequest:(NSURLRequest *)urlRequest + placeholderImage:(nullable UIImage *)placeholderImage + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; + + +///------------------------------ +/// @name Canceling Image Loading +///------------------------------ + +/** + Cancels any executing image task for the specified control state of the receiver, if one exists. + + @param state The control state. + */ +- (void)cancelImageDownloadTaskForState:(UIControlState)state; + +/** + Cancels any executing background image task for the specified control state of the receiver, if one exists. + + @param state The control state. + */ +- (void)cancelBackgroundImageDownloadTaskForState:(UIControlState)state; + +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.m b/Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.m new file mode 100644 index 0000000..03aaf2a --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.m @@ -0,0 +1,302 @@ +// UIButton+AFNetworking.m +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "UIButton+AFNetworking.h" + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import "UIImageView+AFNetworking.h" +#import "AFImageDownloader.h" + +@interface UIButton (_AFNetworking) +@end + +@implementation UIButton (_AFNetworking) + +#pragma mark - + +static char AFImageDownloadReceiptNormal; +static char AFImageDownloadReceiptHighlighted; +static char AFImageDownloadReceiptSelected; +static char AFImageDownloadReceiptDisabled; + +static const char * af_imageDownloadReceiptKeyForState(UIControlState state) { + switch (state) { + case UIControlStateHighlighted: + return &AFImageDownloadReceiptHighlighted; + case UIControlStateSelected: + return &AFImageDownloadReceiptSelected; + case UIControlStateDisabled: + return &AFImageDownloadReceiptDisabled; + case UIControlStateNormal: + default: + return &AFImageDownloadReceiptNormal; + } +} + +- (AFImageDownloadReceipt *)af_imageDownloadReceiptForState:(UIControlState)state { + return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, af_imageDownloadReceiptKeyForState(state)); +} + +- (void)af_setImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt + forState:(UIControlState)state +{ + objc_setAssociatedObject(self, af_imageDownloadReceiptKeyForState(state), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#pragma mark - + +static char AFBackgroundImageDownloadReceiptNormal; +static char AFBackgroundImageDownloadReceiptHighlighted; +static char AFBackgroundImageDownloadReceiptSelected; +static char AFBackgroundImageDownloadReceiptDisabled; + +static const char * af_backgroundImageDownloadReceiptKeyForState(UIControlState state) { + switch (state) { + case UIControlStateHighlighted: + return &AFBackgroundImageDownloadReceiptHighlighted; + case UIControlStateSelected: + return &AFBackgroundImageDownloadReceiptSelected; + case UIControlStateDisabled: + return &AFBackgroundImageDownloadReceiptDisabled; + case UIControlStateNormal: + default: + return &AFBackgroundImageDownloadReceiptNormal; + } +} + +- (AFImageDownloadReceipt *)af_backgroundImageDownloadReceiptForState:(UIControlState)state { + return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, af_backgroundImageDownloadReceiptKeyForState(state)); +} + +- (void)af_setBackgroundImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt + forState:(UIControlState)state +{ + objc_setAssociatedObject(self, af_backgroundImageDownloadReceiptKeyForState(state), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +@end + +#pragma mark - + +@implementation UIButton (AFNetworking) + ++ (AFImageDownloader *)sharedImageDownloader { + + return objc_getAssociatedObject([UIButton class], @selector(sharedImageDownloader)) ?: [AFImageDownloader defaultInstance]; +} + ++ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader { + objc_setAssociatedObject([UIButton class], @selector(sharedImageDownloader), imageDownloader, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#pragma mark - + +- (void)setImageForState:(UIControlState)state + withURL:(NSURL *)url +{ + [self setImageForState:state withURL:url placeholderImage:nil]; +} + +- (void)setImageForState:(UIControlState)state + withURL:(NSURL *)url + placeholderImage:(UIImage *)placeholderImage +{ + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; + [request addValue:@"image/*" forHTTPHeaderField:@"Accept"]; + + [self setImageForState:state withURLRequest:request placeholderImage:placeholderImage success:nil failure:nil]; +} + +- (void)setImageForState:(UIControlState)state + withURLRequest:(NSURLRequest *)urlRequest + placeholderImage:(nullable UIImage *)placeholderImage + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure +{ + if ([self isActiveTaskURLEqualToURLRequest:urlRequest forState:state]) { + return; + } + + [self cancelImageDownloadTaskForState:state]; + + AFImageDownloader *downloader = [[self class] sharedImageDownloader]; + id imageCache = downloader.imageCache; + + //Use the image from the image cache if it exists + UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil]; + if (cachedImage) { + if (success) { + success(urlRequest, nil, cachedImage); + } else { + [self setImage:cachedImage forState:state]; + } + [self af_setImageDownloadReceipt:nil forState:state]; + } else { + if (placeholderImage) { + [self setImage:placeholderImage forState:state]; + } + + __weak __typeof(self)weakSelf = self; + NSUUID *downloadID = [NSUUID UUID]; + AFImageDownloadReceipt *receipt; + receipt = [downloader + downloadImageForURLRequest:urlRequest + withReceiptID:downloadID + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if ([[strongSelf af_imageDownloadReceiptForState:state].receiptID isEqual:downloadID]) { + if (success) { + success(request, response, responseObject); + } else if (responseObject) { + [strongSelf setImage:responseObject forState:state]; + } + [strongSelf af_setImageDownloadReceipt:nil forState:state]; + } + + } + failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if ([[strongSelf af_imageDownloadReceiptForState:state].receiptID isEqual:downloadID]) { + if (failure) { + failure(request, response, error); + } + [strongSelf af_setImageDownloadReceipt:nil forState:state]; + } + }]; + + [self af_setImageDownloadReceipt:receipt forState:state]; + } +} + +#pragma mark - + +- (void)setBackgroundImageForState:(UIControlState)state + withURL:(NSURL *)url +{ + [self setBackgroundImageForState:state withURL:url placeholderImage:nil]; +} + +- (void)setBackgroundImageForState:(UIControlState)state + withURL:(NSURL *)url + placeholderImage:(nullable UIImage *)placeholderImage +{ + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; + [request addValue:@"image/*" forHTTPHeaderField:@"Accept"]; + + [self setBackgroundImageForState:state withURLRequest:request placeholderImage:placeholderImage success:nil failure:nil]; +} + +- (void)setBackgroundImageForState:(UIControlState)state + withURLRequest:(NSURLRequest *)urlRequest + placeholderImage:(nullable UIImage *)placeholderImage + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure +{ + if ([self isActiveBackgroundTaskURLEqualToURLRequest:urlRequest forState:state]) { + return; + } + + [self cancelBackgroundImageDownloadTaskForState:state]; + + AFImageDownloader *downloader = [[self class] sharedImageDownloader]; + id imageCache = downloader.imageCache; + + //Use the image from the image cache if it exists + UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil]; + if (cachedImage) { + if (success) { + success(urlRequest, nil, cachedImage); + } else { + [self setBackgroundImage:cachedImage forState:state]; + } + [self af_setBackgroundImageDownloadReceipt:nil forState:state]; + } else { + if (placeholderImage) { + [self setBackgroundImage:placeholderImage forState:state]; + } + + __weak __typeof(self)weakSelf = self; + NSUUID *downloadID = [NSUUID UUID]; + AFImageDownloadReceipt *receipt; + receipt = [downloader + downloadImageForURLRequest:urlRequest + withReceiptID:downloadID + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if ([[strongSelf af_backgroundImageDownloadReceiptForState:state].receiptID isEqual:downloadID]) { + if (success) { + success(request, response, responseObject); + } else if (responseObject) { + [strongSelf setBackgroundImage:responseObject forState:state]; + } + [strongSelf af_setBackgroundImageDownloadReceipt:nil forState:state]; + } + + } + failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if ([[strongSelf af_backgroundImageDownloadReceiptForState:state].receiptID isEqual:downloadID]) { + if (failure) { + failure(request, response, error); + } + [strongSelf af_setBackgroundImageDownloadReceipt:nil forState:state]; + } + }]; + + [self af_setBackgroundImageDownloadReceipt:receipt forState:state]; + } +} + +#pragma mark - + +- (void)cancelImageDownloadTaskForState:(UIControlState)state { + AFImageDownloadReceipt *receipt = [self af_imageDownloadReceiptForState:state]; + if (receipt != nil) { + [[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:receipt]; + [self af_setImageDownloadReceipt:nil forState:state]; + } +} + +- (void)cancelBackgroundImageDownloadTaskForState:(UIControlState)state { + AFImageDownloadReceipt *receipt = [self af_backgroundImageDownloadReceiptForState:state]; + if (receipt != nil) { + [[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:receipt]; + [self af_setBackgroundImageDownloadReceipt:nil forState:state]; + } +} + +- (BOOL)isActiveTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest forState:(UIControlState)state { + AFImageDownloadReceipt *receipt = [self af_imageDownloadReceiptForState:state]; + return [receipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString]; +} + +- (BOOL)isActiveBackgroundTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest forState:(UIControlState)state { + AFImageDownloadReceipt *receipt = [self af_backgroundImageDownloadReceiptForState:state]; + return [receipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString]; +} + + +@end + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h b/Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h new file mode 100644 index 0000000..8929252 --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h @@ -0,0 +1,109 @@ +// UIImageView+AFNetworking.h +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import + +NS_ASSUME_NONNULL_BEGIN + +@class AFImageDownloader; + +/** + This category adds methods to the UIKit framework's `UIImageView` class. The methods in this category provide support for loading remote images asynchronously from a URL. + */ +@interface UIImageView (AFNetworking) + +///------------------------------------ +/// @name Accessing the Image Downloader +///------------------------------------ + +/** + Set the shared image downloader used to download images. + + @param imageDownloader The shared image downloader used to download images. + */ ++ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader; + +/** + The shared image downloader used to download images. + */ ++ (AFImageDownloader *)sharedImageDownloader; + +///-------------------- +/// @name Setting Image +///-------------------- + +/** + Asynchronously downloads an image from the specified URL, and sets it once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + By default, URL requests have a `Accept` header field value of "image / *", a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:` + + @param url The URL used for the image request. + */ +- (void)setImageWithURL:(NSURL *)url; + +/** + Asynchronously downloads an image from the specified URL, and sets it once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + By default, URL requests have a `Accept` header field value of "image / *", a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:` + + @param url The URL used for the image request. + @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes. + */ +- (void)setImageWithURL:(NSURL *)url + placeholderImage:(nullable UIImage *)placeholderImage; + +/** + Asynchronously downloads an image from the specified URL request, and sets it once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + If a success block is specified, it is the responsibility of the block to set the image of the image view before returning. If no success block is specified, the default behavior of setting the image with `self.image = image` is applied. + + @param urlRequest The URL request used for the image request. + @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes. + @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. + @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. + */ +- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest + placeholderImage:(nullable UIImage *)placeholderImage + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; + +/** + Cancels any executing image operation for the receiver, if one exists. + */ +- (void)cancelImageDownloadTask; + +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.m b/Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.m new file mode 100644 index 0000000..8ae4950 --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.m @@ -0,0 +1,159 @@ +// UIImageView+AFNetworking.m +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "UIImageView+AFNetworking.h" + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import "AFImageDownloader.h" + +@interface UIImageView (_AFNetworking) +@property (readwrite, nonatomic, strong, setter = af_setActiveImageDownloadReceipt:) AFImageDownloadReceipt *af_activeImageDownloadReceipt; +@end + +@implementation UIImageView (_AFNetworking) + +- (AFImageDownloadReceipt *)af_activeImageDownloadReceipt { + return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, @selector(af_activeImageDownloadReceipt)); +} + +- (void)af_setActiveImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt { + objc_setAssociatedObject(self, @selector(af_activeImageDownloadReceipt), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +@end + +#pragma mark - + +@implementation UIImageView (AFNetworking) + ++ (AFImageDownloader *)sharedImageDownloader { + return objc_getAssociatedObject([UIImageView class], @selector(sharedImageDownloader)) ?: [AFImageDownloader defaultInstance]; +} + ++ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader { + objc_setAssociatedObject([UIImageView class], @selector(sharedImageDownloader), imageDownloader, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#pragma mark - + +- (void)setImageWithURL:(NSURL *)url { + [self setImageWithURL:url placeholderImage:nil]; +} + +- (void)setImageWithURL:(NSURL *)url + placeholderImage:(UIImage *)placeholderImage +{ + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; + [request addValue:@"image/*" forHTTPHeaderField:@"Accept"]; + + [self setImageWithURLRequest:request placeholderImage:placeholderImage success:nil failure:nil]; +} + +- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest + placeholderImage:(UIImage *)placeholderImage + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success + failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure +{ + if ([urlRequest URL] == nil) { + self.image = placeholderImage; + if (failure) { + NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorBadURL userInfo:nil]; + failure(urlRequest, nil, error); + } + return; + } + + if ([self isActiveTaskURLEqualToURLRequest:urlRequest]) { + return; + } + + [self cancelImageDownloadTask]; + + AFImageDownloader *downloader = [[self class] sharedImageDownloader]; + id imageCache = downloader.imageCache; + + //Use the image from the image cache if it exists + UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil]; + if (cachedImage) { + if (success) { + success(urlRequest, nil, cachedImage); + } else { + self.image = cachedImage; + } + [self clearActiveDownloadInformation]; + } else { + if (placeholderImage) { + self.image = placeholderImage; + } + + __weak __typeof(self)weakSelf = self; + NSUUID *downloadID = [NSUUID UUID]; + AFImageDownloadReceipt *receipt; + receipt = [downloader + downloadImageForURLRequest:urlRequest + withReceiptID:downloadID + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if ([strongSelf.af_activeImageDownloadReceipt.receiptID isEqual:downloadID]) { + if (success) { + success(request, response, responseObject); + } else if (responseObject) { + strongSelf.image = responseObject; + } + [strongSelf clearActiveDownloadInformation]; + } + + } + failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if ([strongSelf.af_activeImageDownloadReceipt.receiptID isEqual:downloadID]) { + if (failure) { + failure(request, response, error); + } + [strongSelf clearActiveDownloadInformation]; + } + }]; + + self.af_activeImageDownloadReceipt = receipt; + } +} + +- (void)cancelImageDownloadTask { + if (self.af_activeImageDownloadReceipt != nil) { + [[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:self.af_activeImageDownloadReceipt]; + [self clearActiveDownloadInformation]; + } +} + +- (void)clearActiveDownloadInformation { + self.af_activeImageDownloadReceipt = nil; +} + +- (BOOL)isActiveTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest { + return [self.af_activeImageDownloadReceipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString]; +} + +@end + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h b/Pods/AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h new file mode 100644 index 0000000..aa9c0b0 --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h @@ -0,0 +1,43 @@ +// UIKit+AFNetworking.h +// +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +#ifndef _UIKIT_AFNETWORKING_ + #define _UIKIT_AFNETWORKING_ + +#if TARGET_OS_IOS || TARGET_OS_TV + #import "AFAutoPurgingImageCache.h" + #import "AFImageDownloader.h" + #import "UIActivityIndicatorView+AFNetworking.h" + #import "UIButton+AFNetworking.h" + #import "UIImageView+AFNetworking.h" + #import "UIProgressView+AFNetworking.h" +#endif + +#if TARGET_OS_IOS + #import "AFNetworkActivityIndicatorManager.h" + #import "UIRefreshControl+AFNetworking.h" + #import "WKWebView+AFNetworking.h" +#endif + +#endif /* _UIKIT_AFNETWORKING_ */ diff --git a/Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h b/Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h new file mode 100644 index 0000000..8ea0a73 --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h @@ -0,0 +1,64 @@ +// UIProgressView+AFNetworking.h +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import + +NS_ASSUME_NONNULL_BEGIN + + +/** + This category adds methods to the UIKit framework's `UIProgressView` class. The methods in this category provide support for binding the progress to the upload and download progress of a session task. + */ +@interface UIProgressView (AFNetworking) + +///------------------------------------ +/// @name Setting Session Task Progress +///------------------------------------ + +/** + Binds the progress to the upload progress of the specified session task. + + @param task The session task. + @param animated `YES` if the change should be animated, `NO` if the change should happen immediately. + */ +- (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task + animated:(BOOL)animated; + +/** + Binds the progress to the download progress of the specified session task. + + @param task The session task. + @param animated `YES` if the change should be animated, `NO` if the change should happen immediately. + */ +- (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task + animated:(BOOL)animated; + +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.m b/Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.m new file mode 100644 index 0000000..2ae753e --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.m @@ -0,0 +1,126 @@ +// UIProgressView+AFNetworking.m +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "UIProgressView+AFNetworking.h" + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import "AFURLSessionManager.h" + +static void * AFTaskCountOfBytesSentContext = &AFTaskCountOfBytesSentContext; +static void * AFTaskCountOfBytesReceivedContext = &AFTaskCountOfBytesReceivedContext; + +#pragma mark - + +@implementation UIProgressView (AFNetworking) + +- (BOOL)af_uploadProgressAnimated { + return [(NSNumber *)objc_getAssociatedObject(self, @selector(af_uploadProgressAnimated)) boolValue]; +} + +- (void)af_setUploadProgressAnimated:(BOOL)animated { + objc_setAssociatedObject(self, @selector(af_uploadProgressAnimated), @(animated), OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +- (BOOL)af_downloadProgressAnimated { + return [(NSNumber *)objc_getAssociatedObject(self, @selector(af_downloadProgressAnimated)) boolValue]; +} + +- (void)af_setDownloadProgressAnimated:(BOOL)animated { + objc_setAssociatedObject(self, @selector(af_downloadProgressAnimated), @(animated), OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#pragma mark - + +- (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task + animated:(BOOL)animated +{ + if (task.state == NSURLSessionTaskStateCompleted) { + return; + } + + [task addObserver:self forKeyPath:@"state" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesSentContext]; + [task addObserver:self forKeyPath:@"countOfBytesSent" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesSentContext]; + + [self af_setUploadProgressAnimated:animated]; +} + +- (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task + animated:(BOOL)animated +{ + if (task.state == NSURLSessionTaskStateCompleted) { + return; + } + + [task addObserver:self forKeyPath:@"state" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext]; + [task addObserver:self forKeyPath:@"countOfBytesReceived" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext]; + + [self af_setDownloadProgressAnimated:animated]; +} + +#pragma mark - NSKeyValueObserving + +- (void)observeValueForKeyPath:(NSString *)keyPath + ofObject:(id)object + change:(__unused NSDictionary *)change + context:(void *)context +{ + if (context == AFTaskCountOfBytesSentContext || context == AFTaskCountOfBytesReceivedContext) { + if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesSent))]) { + if ([object countOfBytesExpectedToSend] > 0) { + dispatch_async(dispatch_get_main_queue(), ^{ + [self setProgress:[object countOfBytesSent] / ([object countOfBytesExpectedToSend] * 1.0f) animated:self.af_uploadProgressAnimated]; + }); + } + } + + if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesReceived))]) { + if ([object countOfBytesExpectedToReceive] > 0) { + dispatch_async(dispatch_get_main_queue(), ^{ + [self setProgress:[object countOfBytesReceived] / ([object countOfBytesExpectedToReceive] * 1.0f) animated:self.af_downloadProgressAnimated]; + }); + } + } + + if ([keyPath isEqualToString:NSStringFromSelector(@selector(state))]) { + if ([(NSURLSessionTask *)object state] == NSURLSessionTaskStateCompleted) { + @try { + [object removeObserver:self forKeyPath:NSStringFromSelector(@selector(state))]; + + if (context == AFTaskCountOfBytesSentContext) { + [object removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesSent))]; + } + + if (context == AFTaskCountOfBytesReceivedContext) { + [object removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesReceived))]; + } + } + @catch (NSException * __unused exception) {} + } + } + } +} + +@end + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h b/Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h new file mode 100644 index 0000000..215eafc --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h @@ -0,0 +1,53 @@ +// UIRefreshControl+AFNetworking.m +// +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +#import + +#if TARGET_OS_IOS + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + This category adds methods to the UIKit framework's `UIRefreshControl` class. The methods in this category provide support for automatically beginning and ending refreshing depending on the loading state of a session task. + */ +@interface UIRefreshControl (AFNetworking) + +///----------------------------------- +/// @name Refreshing for Session Tasks +///----------------------------------- + +/** + Binds the refreshing state to the state of the specified task. + + @param task The task. If `nil`, automatic updating from any previously specified operation will be disabled. + */ +- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task; + +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.m b/Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.m new file mode 100644 index 0000000..cd46916 --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.m @@ -0,0 +1,113 @@ +// UIRefreshControl+AFNetworking.m +// +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "UIRefreshControl+AFNetworking.h" +#import + +#if TARGET_OS_IOS + +#import "AFURLSessionManager.h" + +@interface AFRefreshControlNotificationObserver : NSObject +@property (readonly, nonatomic, weak) UIRefreshControl *refreshControl; +- (instancetype)initWithActivityRefreshControl:(UIRefreshControl *)refreshControl; + +- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task; + +@end + +@implementation UIRefreshControl (AFNetworking) + +- (AFRefreshControlNotificationObserver *)af_notificationObserver { + AFRefreshControlNotificationObserver *notificationObserver = objc_getAssociatedObject(self, @selector(af_notificationObserver)); + if (notificationObserver == nil) { + notificationObserver = [[AFRefreshControlNotificationObserver alloc] initWithActivityRefreshControl:self]; + objc_setAssociatedObject(self, @selector(af_notificationObserver), notificationObserver, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + return notificationObserver; +} + +- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task { + [[self af_notificationObserver] setRefreshingWithStateOfTask:task]; +} + +@end + +@implementation AFRefreshControlNotificationObserver + +- (instancetype)initWithActivityRefreshControl:(UIRefreshControl *)refreshControl +{ + self = [super init]; + if (self) { + _refreshControl = refreshControl; + } + return self; +} + +- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task { + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; + + [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; + + if (task) { + UIRefreshControl *refreshControl = self.refreshControl; + if (task.state == NSURLSessionTaskStateRunning) { + [refreshControl beginRefreshing]; + + [notificationCenter addObserver:self selector:@selector(af_beginRefreshing) name:AFNetworkingTaskDidResumeNotification object:task]; + [notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingTaskDidCompleteNotification object:task]; + [notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingTaskDidSuspendNotification object:task]; + } else { + [refreshControl endRefreshing]; + } + } +} + +#pragma mark - + +- (void)af_beginRefreshing { + dispatch_async(dispatch_get_main_queue(), ^{ + [self.refreshControl beginRefreshing]; + }); +} + +- (void)af_endRefreshing { + dispatch_async(dispatch_get_main_queue(), ^{ + [self.refreshControl endRefreshing]; + }); +} + +#pragma mark - + +- (void)dealloc { + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; + + [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; +} + +@end + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/WKWebView+AFNetworking.h b/Pods/AFNetworking/UIKit+AFNetworking/WKWebView+AFNetworking.h new file mode 100644 index 0000000..680fedf --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/WKWebView+AFNetworking.h @@ -0,0 +1,80 @@ +// WkWebView+AFNetworking.h +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +#import + +#if TARGET_OS_IOS + +#import +#import + +NS_ASSUME_NONNULL_BEGIN + +@class AFHTTPSessionManager; + +@interface WKWebView (AFNetworking) + +/** + The session manager used to download all request + */ +@property (nonatomic, strong) AFHTTPSessionManager *sessionManager; + +/** + Asynchronously loads the specified request. + + @param request A URL request identifying the location of the content to load. This must not be `nil`. + @param navigation The WKNavigation object that containts information for tracking the loading progress of a webpage. This must not be `nil`. + @param progress A progress object monitoring the current download progress. + @param success A block object to be executed when the request finishes loading successfully. This block returns the HTML string to be loaded by the web view, and takes two arguments: the response, and the response string. + @param failure A block object to be executed when the data task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a single argument: the error that occurred. + */ +- (void)loadRequest:(NSURLRequest *)request + navigation:(WKNavigation * _Nonnull)navigation + progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress + success:(nullable NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success + failure:(nullable void (^)(NSError *error))failure; + +/** + Asynchronously loads the data associated with a particular request with a specified MIME type and text encoding. + + @param request A URL request identifying the location of the content to load. This must not be `nil`. + @param navigation The WKNavigation object that containts information for tracking the loading progress of a webpage. This must not be `nil`. + @param MIMEType The MIME type of the content. Defaults to the content type of the response if not specified. + @param textEncodingName The IANA encoding name, as in `utf-8` or `utf-16`. Defaults to the response text encoding if not specified. + @param progress A progress object monitoring the current download progress. + @param success A block object to be executed when the request finishes loading successfully. This block returns the data to be loaded by the web view and takes two arguments: the response, and the downloaded data. + @param failure A block object to be executed when the data task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a single argument: the error that occurred. + */ +- (void)loadRequest:(NSURLRequest *)request + navigation:(WKNavigation * _Nonnull)navigation + MIMEType:(nullable NSString *)MIMEType + textEncodingName:(nullable NSString *)textEncodingName + progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress + success:(nullable NSData * (^)(NSHTTPURLResponse *response, NSData *data))success + failure:(nullable void (^)(NSError *error))failure; + +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/WKWebView+AFNetworking.m b/Pods/AFNetworking/UIKit+AFNetworking/WKWebView+AFNetworking.m new file mode 100644 index 0000000..6eca3c3 --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/WKWebView+AFNetworking.m @@ -0,0 +1,154 @@ +// WkWebView+AFNetworking.m +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "WKWebView+AFNetworking.h" + +#import + +#if TARGET_OS_IOS + +#import "AFHTTPSessionManager.h" +#import "AFURLResponseSerialization.h" +#import "AFURLRequestSerialization.h" + +@interface WKWebView (_AFNetworking) +@property (readwrite, nonatomic, strong, setter = af_setURLSessionTask:) NSURLSessionDataTask *af_URLSessionTask; +@end + +@implementation WKWebView (_AFNetworking) + +- (NSURLSessionDataTask *)af_URLSessionTask { + return (NSURLSessionDataTask *)objc_getAssociatedObject(self, @selector(af_URLSessionTask)); +} + +- (void)af_setURLSessionTask:(NSURLSessionDataTask *)af_URLSessionTask { + objc_setAssociatedObject(self, @selector(af_URLSessionTask), af_URLSessionTask, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +@end + +#pragma mark - + +@implementation WKWebView (AFNetworking) + +- (AFHTTPSessionManager *)sessionManager { + static AFHTTPSessionManager *_af_defaultHTTPSessionManager = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + _af_defaultHTTPSessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; + _af_defaultHTTPSessionManager.requestSerializer = [AFHTTPRequestSerializer serializer]; + _af_defaultHTTPSessionManager.responseSerializer = [AFHTTPResponseSerializer serializer]; + }); + + return objc_getAssociatedObject(self, @selector(sessionManager)) ?: _af_defaultHTTPSessionManager; +} + +- (void)setSessionManager:(AFHTTPSessionManager *)sessionManager { + objc_setAssociatedObject(self, @selector(sessionManager), sessionManager, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +- (AFHTTPResponseSerializer *)responseSerializer { + static AFHTTPResponseSerializer *_af_defaultResponseSerializer = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + _af_defaultResponseSerializer = [AFHTTPResponseSerializer serializer]; + }); + + return objc_getAssociatedObject(self, @selector(responseSerializer)) ?: _af_defaultResponseSerializer; +} + +- (void)setResponseSerializer:(AFHTTPResponseSerializer *)responseSerializer { + objc_setAssociatedObject(self, @selector(responseSerializer), responseSerializer, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#pragma mark - + +- (void)loadRequest:(NSURLRequest *)request + navigation:(WKNavigation * _Nonnull)navigation + progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress + success:(nullable NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success + failure:(nullable void (^)(NSError *error))failure { + [self loadRequest:request navigation:navigation MIMEType:nil textEncodingName:nil progress:progress success:^NSData * _Nonnull(NSHTTPURLResponse * _Nonnull response, NSData * _Nonnull data) { + NSStringEncoding stringEncoding = NSUTF8StringEncoding; + if (response.textEncodingName) { + CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)response.textEncodingName); + if (encoding != kCFStringEncodingInvalidId) { + stringEncoding = CFStringConvertEncodingToNSStringEncoding(encoding); + } + } + + NSString *string = [[NSString alloc] initWithData:data encoding:stringEncoding]; + if (success) { + string = success(response, string); + } + + return [string dataUsingEncoding:stringEncoding]; + } failure:failure]; +} + +- (void)loadRequest:(NSURLRequest *)request + navigation:(WKNavigation * _Nonnull)navigation + MIMEType:(nullable NSString *)MIMEType + textEncodingName:(nullable NSString *)textEncodingName + progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress + success:(nullable NSData * (^)(NSHTTPURLResponse *response, NSData *data))success + failure:(nullable void (^)(NSError *error))failure { + NSParameterAssert(request); + + if (self.af_URLSessionTask.state == NSURLSessionTaskStateRunning || self.af_URLSessionTask.state == NSURLSessionTaskStateSuspended) { + [self.af_URLSessionTask cancel]; + } + self.af_URLSessionTask = nil; + + __weak __typeof(self)weakSelf = self; + __block NSURLSessionDataTask *dataTask; + __strong __typeof(weakSelf) strongSelf = weakSelf; + __strong __typeof(weakSelf.navigationDelegate) strongSelfDelegate = strongSelf.navigationDelegate; + dataTask = [self.sessionManager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { + if (error) { + if (failure) { + failure(error); + } + } else { + if (success) { + success((NSHTTPURLResponse *)response, responseObject); + } + [strongSelf loadData:responseObject MIMEType:MIMEType characterEncodingName:textEncodingName baseURL:[dataTask.currentRequest URL]]; + + if ([strongSelfDelegate respondsToSelector:@selector(webView:didFinishNavigation:)]) { + [strongSelfDelegate webView:strongSelf didFinishNavigation:navigation]; + } + } + }]; + self.af_URLSessionTask = dataTask; + if (progress != nil) { + *progress = [self.sessionManager downloadProgressForTask:dataTask]; + } + [self.af_URLSessionTask resume]; + + if ([strongSelfDelegate respondsToSelector:@selector(webView:didStartProvisionalNavigation:)]) { + [strongSelfDelegate webView:self didStartProvisionalNavigation:navigation]; + } +} + +@end + +#endif diff --git a/Pods/Bugly/Bugly.framework/Bugly b/Pods/Bugly/Bugly.framework/Bugly new file mode 100644 index 0000000..c3ae3e2 Binary files /dev/null and b/Pods/Bugly/Bugly.framework/Bugly differ diff --git a/Pods/Bugly/Bugly.framework/Headers/Bugly.h b/Pods/Bugly/Bugly.framework/Headers/Bugly.h new file mode 100644 index 0000000..74c143e --- /dev/null +++ b/Pods/Bugly/Bugly.framework/Headers/Bugly.h @@ -0,0 +1,163 @@ +// +// Bugly.h +// +// Version: 2.6(1) +// +// Copyright (c) 2017年 Tencent. All rights reserved. +// + +#import + +#import "BuglyConfig.h" +#import "BuglyLog.h" + +BLY_START_NONNULL + +@interface Bugly : NSObject + +/** + * 初始化Bugly,使用默认BuglyConfigs + * + * @param appId 注册Bugly分配的应用唯一标识 + */ ++ (void)startWithAppId:(NSString * BLY_NULLABLE)appId; + +/** + * 使用指定配置初始化Bugly + * + * @param appId 注册Bugly分配的应用唯一标识 + * @param config 传入配置的 BuglyConfig + */ ++ (void)startWithAppId:(NSString * BLY_NULLABLE)appId + config:(BuglyConfig * BLY_NULLABLE)config; + +/** + * 使用指定配置初始化Bugly + * + * @param appId 注册Bugly分配的应用唯一标识 + * @param development 是否开发设备 + * @param config 传入配置的 BuglyConfig + */ ++ (void)startWithAppId:(NSString * BLY_NULLABLE)appId + developmentDevice:(BOOL)development + config:(BuglyConfig * BLY_NULLABLE)config; + +/** + * 设置用户标识 + * + * @param userId 用户标识 + */ ++ (void)setUserIdentifier:(NSString *)userId; + +/** + * 更新版本信息 + * + * @param version 应用版本信息 + */ ++ (void)updateAppVersion:(NSString *)version; + +/** + * 设置关键数据,随崩溃信息上报 + * + * @param value KEY + * @param key VALUE + */ ++ (void)setUserValue:(NSString *)value + forKey:(NSString *)key; + +/** + * 获取USER ID + * + * @return USER ID + */ ++ (NSString *)buglyUserIdentifier; + +/** + * 获取关键数据 + * + * @return 关键数据 + */ ++ (NSDictionary * BLY_NULLABLE)allUserValues; + +/** + * 设置标签 + * + * @param tag 标签ID,可在网站生成 + */ ++ (void)setTag:(NSUInteger)tag; + +/** + * 获取当前设置标签 + * + * @return 当前标签ID + */ ++ (NSUInteger)currentTag; + +/** + * 获取设备ID + * + * @return 设备ID + */ ++ (NSString *)buglyDeviceId; + +/** + * 上报自定义Objective-C异常 + * + * @param exception 异常信息 + */ ++ (void)reportException:(NSException *)exception; + +/** + * 上报错误 + * + * @param error 错误信息 + */ ++ (void)reportError:(NSError *)error; + +/** + * @brief 上报自定义错误 + * + * @param category 类型(Cocoa=3,CSharp=4,JS=5,Lua=6) + * @param aName 名称 + * @param aReason 错误原因 + * @param aStackArray 堆栈 + * @param info 附加数据 + * @param terminate 上报后是否退出应用进程 + */ ++ (void)reportExceptionWithCategory:(NSUInteger)category + name:(NSString *)aName + reason:(NSString *)aReason + callStack:(NSArray *)aStackArray + extraInfo:(NSDictionary *)info + terminateApp:(BOOL)terminate; + +/** + * SDK 版本信息 + * + * @return SDK版本号 + */ ++ (NSString *)sdkVersion; + +/** + * APP 版本信息 + * + * @return SDK版本号 + */ ++ (NSString *)appVersion; + +/** + * App 是否发生了连续闪退 + * 如果 启动SDK 且 5秒内 闪退,且次数达到 3次 则判定为连续闪退 + * + * @return 是否连续闪退 + */ ++ (BOOL)isAppCrashedOnStartUpExceedTheLimit; + +/** + * 关闭bugly监控 + */ ++ (void)closeCrashReport; + +BLY_END_NONNULL + +@end diff --git a/Pods/Bugly/Bugly.framework/Headers/BuglyConfig.h b/Pods/Bugly/Bugly.framework/Headers/BuglyConfig.h new file mode 100644 index 0000000..16e253b --- /dev/null +++ b/Pods/Bugly/Bugly.framework/Headers/BuglyConfig.h @@ -0,0 +1,149 @@ +// +// BuglyConfig.h +// Bugly +// +// Copyright (c) 2016年 Tencent. All rights reserved. +// + +#pragma once + +#define BLY_UNAVAILABLE(x) __attribute__((unavailable(x))) + +#if __has_feature(nullability) +#define BLY_NONNULL __nonnull +#define BLY_NULLABLE __nullable +#define BLY_START_NONNULL _Pragma("clang assume_nonnull begin") +#define BLY_END_NONNULL _Pragma("clang assume_nonnull end") +#else +#define BLY_NONNULL +#define BLY_NULLABLE +#define BLY_START_NONNULL +#define BLY_END_NONNULL +#endif + +#import + +#import "BuglyLog.h" + +BLY_START_NONNULL + +@protocol BuglyDelegate + +@optional +/** + * 发生异常时回调 + * + * @param exception 异常信息 + * + * @return 返回需上报记录,随异常上报一起上报 + */ +- (NSString * BLY_NULLABLE)attachmentForException:(NSException * BLY_NULLABLE)exception; + +/** + * 发生sigkill时回调 + * + * @param exception 异常信息 + * + * @return 返回需上报记录,随sigkill异常上报一起上报,返回值由app开发者决定 + */ +- (NSString * BLY_NULLABLE)attachmentForSigkill; + +/** + * 策略激活时回调 + * + * @param tacticInfo + * + * @return app是否弹框展示 + */ +- (BOOL) h5AlertForTactic:(NSDictionary *)tacticInfo; + +@end + +@interface BuglyConfig : NSObject + +/** + * SDK Debug信息开关, 默认关闭 + */ +@property (nonatomic, assign) BOOL debugMode; + +/** + * 设置自定义渠道标识 + */ +@property (nonatomic, copy) NSString *channel; + +/** + * 设置自定义版本号 + */ +@property (nonatomic, copy) NSString *version; + +/** + * 设置自定义设备唯一标识 + */ +@property (nonatomic, copy) NSString *deviceIdentifier; + +/** + * 卡顿监控开关,默认关闭 + */ +@property (nonatomic) BOOL blockMonitorEnable; + +/** + * 卡顿监控判断间隔,单位为秒 + */ +@property (nonatomic) NSTimeInterval blockMonitorTimeout; + +/** + * 设置 App Groups Id (如有使用 Bugly iOS Extension SDK,请设置该值) + */ +@property (nonatomic, copy) NSString *applicationGroupIdentifier; + +/** + * 进程内还原开关,默认开启 + */ +@property (nonatomic) BOOL symbolicateInProcessEnable; + +/** + * 非正常退出事件记录开关,默认关闭 + */ +@property (nonatomic) BOOL unexpectedTerminatingDetectionEnable; + +/** + * 页面信息记录开关,默认开启 + */ +@property (nonatomic) BOOL viewControllerTrackingEnable; + +/** + * Bugly Delegate + */ +@property (nonatomic, assign) id delegate; + +/** + * 控制自定义日志上报,默认值为BuglyLogLevelSilent,即关闭日志记录功能。 + * 如果设置为BuglyLogLevelWarn,则在崩溃时会上报Warn、Error接口打印的日志 + */ +@property (nonatomic, assign) BuglyLogLevel reportLogLevel; + +/** + * 崩溃数据过滤器,如果崩溃堆栈的模块名包含过滤器中设置的关键字,则崩溃数据不会进行上报 + * 例如,过滤崩溃堆栈中包含搜狗输入法的数据,可以添加过滤器关键字SogouInputIPhone.dylib等 + */ +@property (nonatomic, copy) NSArray *excludeModuleFilter; + +/** + * 控制台日志上报开关,默认开启 + */ +@property (nonatomic, assign) BOOL consolelogEnable; + +/** + * 崩溃退出超时,如果监听到崩溃后,App一直没有退出,则到达超时时间后会自动abort进程退出 + * 默认值 5s, 单位 秒 + * 当赋值为0时,则不会自动abort进程退出 + */ +@property (nonatomic, assign) NSUInteger crashAbortTimeout; + +/** + * 设置自定义联网、crash上报域名 + */ +@property (nonatomic, copy) NSString *crashServerUrl; + +@end +BLY_END_NONNULL diff --git a/Pods/Bugly/Bugly.framework/Headers/BuglyLog.h b/Pods/Bugly/Bugly.framework/Headers/BuglyLog.h new file mode 100644 index 0000000..2768e14 --- /dev/null +++ b/Pods/Bugly/Bugly.framework/Headers/BuglyLog.h @@ -0,0 +1,78 @@ +// +// BuglyLog.h +// Bugly +// +// Copyright (c) 2017年 Tencent. All rights reserved. +// + +#import + +// Log level for Bugly Log +typedef NS_ENUM(NSUInteger, BuglyLogLevel) { + BuglyLogLevelSilent = 0, + BuglyLogLevelError = 1, + BuglyLogLevelWarn = 2, + BuglyLogLevelInfo = 3, + BuglyLogLevelDebug = 4, + BuglyLogLevelVerbose = 5, +}; +#pragma mark - + +OBJC_EXTERN void BLYLog(BuglyLogLevel level, NSString *format, ...) NS_FORMAT_FUNCTION(2, 3); + +OBJC_EXTERN void BLYLogv(BuglyLogLevel level, NSString *format, va_list args) NS_FORMAT_FUNCTION(2, 0); + +#pragma mark - +#define BUGLY_LOG_MACRO(_level, fmt, ...) [BuglyLog level:_level tag:nil log:fmt, ##__VA_ARGS__] + +#define BLYLogError(fmt, ...) BUGLY_LOG_MACRO(BuglyLogLevelError, fmt, ##__VA_ARGS__) +#define BLYLogWarn(fmt, ...) BUGLY_LOG_MACRO(BuglyLogLevelWarn, fmt, ##__VA_ARGS__) +#define BLYLogInfo(fmt, ...) BUGLY_LOG_MACRO(BuglyLogLevelInfo, fmt, ##__VA_ARGS__) +#define BLYLogDebug(fmt, ...) BUGLY_LOG_MACRO(BuglyLogLevelDebug, fmt, ##__VA_ARGS__) +#define BLYLogVerbose(fmt, ...) BUGLY_LOG_MACRO(BuglyLogLevelVerbose, fmt, ##__VA_ARGS__) + +#pragma mark - Interface +@interface BuglyLog : NSObject + +/** + * @brief 初始化日志模块 + * + * @param level 设置默认日志级别,默认BLYLogLevelSilent + * + * @param printConsole 是否打印到控制台,默认NO + */ ++ (void)initLogger:(BuglyLogLevel) level consolePrint:(BOOL)printConsole; + +/** + * @brief 打印BLYLogLevelInfo日志 + * + * @param format 日志内容 总日志大小限制为:字符串长度30k,条数200 + */ ++ (void)log:(NSString *)format, ... NS_FORMAT_FUNCTION(1, 2); + +/** + * @brief 打印日志 + * + * @param level 日志级别 + * @param message 日志内容 总日志大小限制为:字符串长度30k,条数200 + */ ++ (void)level:(BuglyLogLevel) level logs:(NSString *)message; + +/** + * @brief 打印日志 + * + * @param level 日志级别 + * @param format 日志内容 总日志大小限制为:字符串长度30k,条数200 + */ ++ (void)level:(BuglyLogLevel) level log:(NSString *)format, ... NS_FORMAT_FUNCTION(2, 3); + +/** + * @brief 打印日志 + * + * @param level 日志级别 + * @param tag 日志模块分类 + * @param format 日志内容 总日志大小限制为:字符串长度30k,条数200 + */ ++ (void)level:(BuglyLogLevel) level tag:(NSString *) tag log:(NSString *)format, ... NS_FORMAT_FUNCTION(3, 4); + +@end diff --git a/Pods/Bugly/Bugly.framework/Modules/module.modulemap b/Pods/Bugly/Bugly.framework/Modules/module.modulemap new file mode 100644 index 0000000..c536705 --- /dev/null +++ b/Pods/Bugly/Bugly.framework/Modules/module.modulemap @@ -0,0 +1,12 @@ +framework module Bugly { + umbrella header "Bugly.h" + + export * + module * { export * } + + link framework "Foundation" + link framework "Security" + link framework "SystemConfiguration" + link "c++" + link "z" +} diff --git a/Pods/Bugly/Bugly.framework/PrivacyInfo.xcprivacy b/Pods/Bugly/Bugly.framework/PrivacyInfo.xcprivacy new file mode 100644 index 0000000..78568c6 --- /dev/null +++ b/Pods/Bugly/Bugly.framework/PrivacyInfo.xcprivacy @@ -0,0 +1,41 @@ + + + + + NSPrivacyAccessedAPITypes + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategoryFileTimestamp + NSPrivacyAccessedAPITypeReasons + + C617.1 + + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategorySystemBootTime + NSPrivacyAccessedAPITypeReasons + + 35F9.1 + + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategoryDiskSpace + NSPrivacyAccessedAPITypeReasons + + E174.1 + + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategoryUserDefaults + NSPrivacyAccessedAPITypeReasons + + CA92.1 + + + + + diff --git a/Pods/MJExtension/LICENSE b/Pods/MJExtension/LICENSE new file mode 100644 index 0000000..9c294c6 --- /dev/null +++ b/Pods/MJExtension/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2013-2019 MJExtension (https://github.com/CoderMJLee/MJExtension) + +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. diff --git a/Pods/MJExtension/MJExtension/MJExtension.h b/Pods/MJExtension/MJExtension/MJExtension.h new file mode 100644 index 0000000..f2ede55 --- /dev/null +++ b/Pods/MJExtension/MJExtension/MJExtension.h @@ -0,0 +1,27 @@ +// +// MJExtension.h +// MJExtension +// +// Created by mj on 14-1-15. +// Copyright (c) 2014年 小码哥. All rights reserved. +// + +#import +#import "NSObject+MJCoding.h" +#import "NSObject+MJProperty.h" +#import "NSObject+MJClass.h" +#import "NSObject+MJKeyValue.h" +#import "NSString+MJExtension.h" +#import "MJExtensionConst.h" + +#import "MJFoundation.h" + +//! Project version number for MJExtension. +FOUNDATION_EXPORT double MJExtensionVersionNumber; + +//! Project version string for MJExtension. +FOUNDATION_EXPORT const unsigned char MJExtensionVersionString[]; + +// In this header, you should import all the public headers of your framework using statements like #import + + diff --git a/Pods/MJExtension/MJExtension/MJExtensionConst.h b/Pods/MJExtension/MJExtension/MJExtensionConst.h new file mode 100644 index 0000000..5120431 --- /dev/null +++ b/Pods/MJExtension/MJExtension/MJExtensionConst.h @@ -0,0 +1,111 @@ + +#ifndef __MJExtensionConst__H__ +#define __MJExtensionConst__H__ + +#import + +#ifndef MJ_LOCK +#define MJ_LOCK(lock) dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER); +#endif + +#ifndef MJ_UNLOCK +#define MJ_UNLOCK(lock) dispatch_semaphore_signal(lock); +#endif + +// 信号量 +#define MJExtensionSemaphoreCreate \ +extern dispatch_semaphore_t mje_signalSemaphore; \ +extern dispatch_once_t mje_onceTokenSemaphore; \ +dispatch_once(&mje_onceTokenSemaphore, ^{ \ + mje_signalSemaphore = dispatch_semaphore_create(1); \ +}); + +// 过期 +#define MJExtensionDeprecated(instead) NS_DEPRECATED(2_0, 2_0, 2_0, 2_0, instead) + +// 构建错误 +#define MJExtensionBuildError(clazz, msg) \ +NSError *error = [NSError errorWithDomain:msg code:250 userInfo:nil]; \ +[clazz setMj_error:error]; + +// 日志输出 +#ifdef DEBUG +#define MJExtensionLog(...) NSLog(__VA_ARGS__) +#else +#define MJExtensionLog(...) +#endif + +/** + * 断言 + * @param condition 条件 + * @param returnValue 返回值 + */ +#define MJExtensionAssertError(condition, returnValue, clazz, msg) \ +[clazz setMj_error:nil]; \ +if ((condition) == NO) { \ + MJExtensionBuildError(clazz, msg); \ + return returnValue;\ +} + +#define MJExtensionAssert2(condition, returnValue) \ +if ((condition) == NO) return returnValue; + +/** + * 断言 + * @param condition 条件 + */ +#define MJExtensionAssert(condition) MJExtensionAssert2(condition, ) + +/** + * 断言 + * @param param 参数 + * @param returnValue 返回值 + */ +#define MJExtensionAssertParamNotNil2(param, returnValue) \ +MJExtensionAssert2((param) != nil, returnValue) + +/** + * 断言 + * @param param 参数 + */ +#define MJExtensionAssertParamNotNil(param) MJExtensionAssertParamNotNil2(param, ) + +/** + * 打印所有的属性 + */ +#define MJLogAllIvars \ +- (NSString *)description \ +{ \ + return [self mj_keyValues].description; \ +} +#define MJExtensionLogAllProperties MJLogAllIvars + +/** 仅在 Debugger 展示所有的属性 */ +#define MJImplementDebugDescription \ +- (NSString *)debugDescription \ +{ \ +return [self mj_keyValues].debugDescription; \ +} + +/** + * 类型(属性类型) + */ +FOUNDATION_EXPORT NSString *const MJPropertyTypeInt; +FOUNDATION_EXPORT NSString *const MJPropertyTypeShort; +FOUNDATION_EXPORT NSString *const MJPropertyTypeFloat; +FOUNDATION_EXPORT NSString *const MJPropertyTypeDouble; +FOUNDATION_EXPORT NSString *const MJPropertyTypeLong; +FOUNDATION_EXPORT NSString *const MJPropertyTypeLongLong; +FOUNDATION_EXPORT NSString *const MJPropertyTypeChar; +FOUNDATION_EXPORT NSString *const MJPropertyTypeBOOL1; +FOUNDATION_EXPORT NSString *const MJPropertyTypeBOOL2; +FOUNDATION_EXPORT NSString *const MJPropertyTypePointer; + +FOUNDATION_EXPORT NSString *const MJPropertyTypeIvar; +FOUNDATION_EXPORT NSString *const MJPropertyTypeMethod; +FOUNDATION_EXPORT NSString *const MJPropertyTypeBlock; +FOUNDATION_EXPORT NSString *const MJPropertyTypeClass; +FOUNDATION_EXPORT NSString *const MJPropertyTypeSEL; +FOUNDATION_EXPORT NSString *const MJPropertyTypeId; + +#endif diff --git a/Pods/MJExtension/MJExtension/MJExtensionConst.m b/Pods/MJExtension/MJExtension/MJExtensionConst.m new file mode 100644 index 0000000..24bcca5 --- /dev/null +++ b/Pods/MJExtension/MJExtension/MJExtensionConst.m @@ -0,0 +1,27 @@ +#ifndef __MJExtensionConst__M__ +#define __MJExtensionConst__M__ + +#import + +/** + * 成员变量类型(属性类型) + */ +NSString *const MJPropertyTypeInt = @"i"; +NSString *const MJPropertyTypeShort = @"s"; +NSString *const MJPropertyTypeFloat = @"f"; +NSString *const MJPropertyTypeDouble = @"d"; +NSString *const MJPropertyTypeLong = @"l"; +NSString *const MJPropertyTypeLongLong = @"q"; +NSString *const MJPropertyTypeChar = @"c"; +NSString *const MJPropertyTypeBOOL1 = @"c"; +NSString *const MJPropertyTypeBOOL2 = @"b"; +NSString *const MJPropertyTypePointer = @"*"; + +NSString *const MJPropertyTypeIvar = @"^{objc_ivar=}"; +NSString *const MJPropertyTypeMethod = @"^{objc_method=}"; +NSString *const MJPropertyTypeBlock = @"@?"; +NSString *const MJPropertyTypeClass = @"#"; +NSString *const MJPropertyTypeSEL = @":"; +NSString *const MJPropertyTypeId = @"@"; + +#endif \ No newline at end of file diff --git a/Pods/MJExtension/MJExtension/MJFoundation.h b/Pods/MJExtension/MJExtension/MJFoundation.h new file mode 100644 index 0000000..f2c1967 --- /dev/null +++ b/Pods/MJExtension/MJExtension/MJFoundation.h @@ -0,0 +1,16 @@ +// +// MJFoundation.h +// MJExtensionExample +// +// Created by MJ Lee on 14/7/16. +// Copyright (c) 2014年 小码哥. All rights reserved. +// + +#import + +@interface MJFoundation : NSObject + ++ (BOOL)isClassFromFoundation:(Class)c; ++ (BOOL)isFromNSObjectProtocolProperty:(NSString *)propertyName; + +@end diff --git a/Pods/MJExtension/MJExtension/MJFoundation.m b/Pods/MJExtension/MJExtension/MJFoundation.m new file mode 100644 index 0000000..31e107d --- /dev/null +++ b/Pods/MJExtension/MJExtension/MJFoundation.m @@ -0,0 +1,70 @@ +// +// MJFoundation.m +// MJExtensionExample +// +// Created by MJ Lee on 14/7/16. +// Copyright (c) 2014年 小码哥. All rights reserved. +// + +#import "MJFoundation.h" +#import "MJExtensionConst.h" +#import +#import "objc/runtime.h" + +@implementation MJFoundation + ++ (BOOL)isClassFromFoundation:(Class)c +{ + if (c == [NSObject class] || c == [NSManagedObject class]) return YES; + + static NSSet *foundationClasses; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + // 集合中没有NSObject,因为几乎所有的类都是继承自NSObject,具体是不是NSObject需要特殊判断 + foundationClasses = [NSSet setWithObjects: + [NSURL class], + [NSDate class], + [NSValue class], + [NSData class], + [NSError class], + [NSArray class], + [NSDictionary class], + [NSString class], + [NSAttributedString class], nil]; + }); + + __block BOOL result = NO; + [foundationClasses enumerateObjectsUsingBlock:^(Class foundationClass, BOOL *stop) { + if ([c isSubclassOfClass:foundationClass]) { + result = YES; + *stop = YES; + } + }]; + return result; +} + ++ (BOOL)isFromNSObjectProtocolProperty:(NSString *)propertyName +{ + if (!propertyName) return NO; + + static NSSet *objectProtocolPropertyNames; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + unsigned int count = 0; + objc_property_t *propertyList = protocol_copyPropertyList(@protocol(NSObject), &count); + NSMutableSet *propertyNames = [NSMutableSet setWithCapacity:count]; + for (int i = 0; i < count; i++) { + objc_property_t property = propertyList[i]; + NSString *propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding]; + if (propertyName) { + [propertyNames addObject:propertyName]; + } + } + objectProtocolPropertyNames = [propertyNames copy]; + free(propertyList); + }); + + return [objectProtocolPropertyNames containsObject:propertyName]; +} + +@end diff --git a/Pods/MJExtension/MJExtension/MJProperty.h b/Pods/MJExtension/MJExtension/MJProperty.h new file mode 100644 index 0000000..90ac6bc --- /dev/null +++ b/Pods/MJExtension/MJExtension/MJProperty.h @@ -0,0 +1,53 @@ +// +// MJProperty.h +// MJExtensionExample +// +// Created by MJ Lee on 15/4/17. +// Copyright (c) 2015年 小码哥. All rights reserved. +// 包装一个成员属性 + +#import +#import +#import "MJPropertyType.h" +#import "MJPropertyKey.h" + +/** + * 包装一个成员 + */ +@interface MJProperty : NSObject +/** 成员属性 */ +@property (nonatomic, assign) objc_property_t property; +/** 成员属性的名字 */ +@property (nonatomic, readonly) NSString *name; + +/** 成员属性的类型 */ +@property (nonatomic, readonly) MJPropertyType *type; +/** 成员属性来源于哪个类(可能是父类) */ +@property (nonatomic, assign) Class srcClass; + +/**** 同一个成员属性 - 父类和子类的行为可能不一致(originKey、propertyKeys、objectClassInArray) ****/ +/** 设置最原始的key */ +- (void)setOriginKey:(id)originKey forClass:(Class)c; +/** 对应着字典中的多级key(里面存放的数组,数组里面都是MJPropertyKey对象) */ +- (NSArray *)propertyKeysForClass:(Class)c; + +/** 模型数组中的模型类型 */ +- (void)setObjectClassInArray:(Class)objectClass forClass:(Class)c; +- (Class)objectClassInArrayForClass:(Class)c; +/**** 同一个成员变量 - 父类和子类的行为可能不一致(key、keys、objectClassInArray) ****/ + +/** + * 设置object的成员变量值 + */ +- (void)setValue:(id)value forObject:(id)object; +/** + * 得到object的成员属性值 + */ +- (id)valueForObject:(id)object; + +/** + * 初始化 + */ ++ (instancetype)cachedPropertyWithProperty:(objc_property_t)property; + +@end diff --git a/Pods/MJExtension/MJExtension/MJProperty.m b/Pods/MJExtension/MJExtension/MJProperty.m new file mode 100644 index 0000000..dcda032 --- /dev/null +++ b/Pods/MJExtension/MJExtension/MJProperty.m @@ -0,0 +1,211 @@ +// +// MJProperty.m +// MJExtensionExample +// +// Created by MJ Lee on 15/4/17. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "MJProperty.h" +#import "MJFoundation.h" +#import "MJExtensionConst.h" +#import +#include "TargetConditionals.h" + +@interface MJProperty() +@property (strong, nonatomic) NSMutableDictionary *propertyKeysDict; +@property (strong, nonatomic) NSMutableDictionary *objectClassInArrayDict; +@property (strong, nonatomic) dispatch_semaphore_t propertyKeysLock; +@property (strong, nonatomic) dispatch_semaphore_t objectClassInArrayLock; +@end + +@implementation MJProperty + +#pragma mark - 初始化 +- (instancetype)init +{ + if (self = [super init]) { + _propertyKeysDict = [NSMutableDictionary dictionary]; + _objectClassInArrayDict = [NSMutableDictionary dictionary]; + _propertyKeysLock = dispatch_semaphore_create(1); + _objectClassInArrayLock = dispatch_semaphore_create(1); + } + return self; +} + +#pragma mark - 缓存 ++ (instancetype)cachedPropertyWithProperty:(objc_property_t)property +{ + MJProperty *propertyObj = objc_getAssociatedObject(self, property); + if (propertyObj == nil) { + propertyObj = [[self alloc] init]; + propertyObj.property = property; + objc_setAssociatedObject(self, property, propertyObj, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + return propertyObj; +} + +#pragma mark - 公共方法 +- (void)setProperty:(objc_property_t)property +{ + _property = property; + + MJExtensionAssertParamNotNil(property); + + // 1.属性名 + _name = @(property_getName(property)); + + // 2.成员类型 + NSString *attrs = @(property_getAttributes(property)); + NSUInteger dotLoc = [attrs rangeOfString:@","].location; + NSString *code = nil; + NSUInteger loc = 1; + if (dotLoc == NSNotFound) { // 没有, + code = [attrs substringFromIndex:loc]; + } else { + code = [attrs substringWithRange:NSMakeRange(loc, dotLoc - loc)]; + } + _type = [MJPropertyType cachedTypeWithCode:code]; +} + +/** + * 获得成员变量的值 + */ +- (id)valueForObject:(id)object +{ + if (self.type.KVCDisabled) return [NSNull null]; + + id value = [object valueForKey:self.name]; + + // 32位BOOL类型转换json后成Int类型 + /** https://github.com/CoderMJLee/MJExtension/issues/545 */ + // 32 bit device OR 32 bit Simulator +#if defined(__arm__) || (TARGET_OS_SIMULATOR && !__LP64__) + if (self.type.isBoolType) { + value = @([(NSNumber *)value boolValue]); + } +#endif + + return value; +} + +/** + * 设置成员变量的值 + */ +- (void)setValue:(id)value forObject:(id)object +{ + if (self.type.KVCDisabled || value == nil) return; + [object setValue:value forKey:self.name]; +} + +/** + * 通过字符串key创建对应的keys + */ +- (NSArray *)propertyKeysWithStringKey:(NSString *)stringKey +{ + if (stringKey.length == 0) return nil; + + NSMutableArray *propertyKeys = [NSMutableArray array]; + // 如果有多级映射 + NSArray *oldKeys = [stringKey componentsSeparatedByString:@"."]; + + for (NSString *oldKey in oldKeys) { + NSUInteger start = [oldKey rangeOfString:@"["].location; + if (start != NSNotFound) { // 有索引的key + NSString *prefixKey = [oldKey substringToIndex:start]; + NSString *indexKey = prefixKey; + if (prefixKey.length) { + MJPropertyKey *propertyKey = [[MJPropertyKey alloc] init]; + propertyKey.name = prefixKey; + [propertyKeys addObject:propertyKey]; + + indexKey = [oldKey stringByReplacingOccurrencesOfString:prefixKey withString:@""]; + } + + /** 解析索引 **/ + // 元素 + NSArray *cmps = [[indexKey stringByReplacingOccurrencesOfString:@"[" withString:@""] componentsSeparatedByString:@"]"]; + for (NSInteger i = 0; i + +typedef enum { + MJPropertyKeyTypeDictionary = 0, // 字典的key + MJPropertyKeyTypeArray // 数组的key +} MJPropertyKeyType; + +/** + * 属性的key + */ +@interface MJPropertyKey : NSObject +/** key的名字 */ +@property (copy, nonatomic) NSString *name; +/** key的种类,可能是@"10",可能是@"age" */ +@property (assign, nonatomic) MJPropertyKeyType type; + +/** + * 根据当前的key,也就是name,从object(字典或者数组)中取值 + */ +- (id)valueInObject:(id)object; + +@end diff --git a/Pods/MJExtension/MJExtension/MJPropertyKey.m b/Pods/MJExtension/MJExtension/MJPropertyKey.m new file mode 100644 index 0000000..438d019 --- /dev/null +++ b/Pods/MJExtension/MJExtension/MJPropertyKey.m @@ -0,0 +1,25 @@ +// +// MJPropertyKey.m +// MJExtensionExample +// +// Created by MJ Lee on 15/8/11. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "MJPropertyKey.h" + +@implementation MJPropertyKey + +- (id)valueInObject:(id)object +{ + if ([object isKindOfClass:[NSDictionary class]] && self.type == MJPropertyKeyTypeDictionary) { + return object[self.name]; + } else if ([object isKindOfClass:[NSArray class]] && self.type == MJPropertyKeyTypeArray) { + NSArray *array = object; + NSUInteger index = self.name.intValue; + if (index < array.count) return array[index]; + return nil; + } + return nil; +} +@end diff --git a/Pods/MJExtension/MJExtension/MJPropertyType.h b/Pods/MJExtension/MJExtension/MJPropertyType.h new file mode 100755 index 0000000..8c53f27 --- /dev/null +++ b/Pods/MJExtension/MJExtension/MJPropertyType.h @@ -0,0 +1,39 @@ +// +// MJPropertyType.h +// MJExtension +// +// Created by mj on 14-1-15. +// Copyright (c) 2014年 小码哥. All rights reserved. +// 包装一种类型 + +#import + +/** + * 包装一种类型 + */ +@interface MJPropertyType : NSObject +/** 类型标识符 */ +@property (nonatomic, copy) NSString *code; + +/** 是否为id类型 */ +@property (nonatomic, readonly, getter=isIdType) BOOL idType; + +/** 是否为基本数字类型:int、float等 */ +@property (nonatomic, readonly, getter=isNumberType) BOOL numberType; + +/** 是否为BOOL类型 */ +@property (nonatomic, readonly, getter=isBoolType) BOOL boolType; + +/** 对象类型(如果是基本数据类型,此值为nil) */ +@property (nonatomic, readonly) Class typeClass; + +/** 类型是否来自于Foundation框架,比如NSString、NSArray */ +@property (nonatomic, readonly, getter = isFromFoundation) BOOL fromFoundation; +/** 类型是否不支持KVC */ +@property (nonatomic, readonly, getter = isKVCDisabled) BOOL KVCDisabled; + +/** + * 获得缓存的类型对象 + */ ++ (instancetype)cachedTypeWithCode:(NSString *)code; +@end \ No newline at end of file diff --git a/Pods/MJExtension/MJExtension/MJPropertyType.m b/Pods/MJExtension/MJExtension/MJPropertyType.m new file mode 100755 index 0000000..77d6b30 --- /dev/null +++ b/Pods/MJExtension/MJExtension/MJPropertyType.m @@ -0,0 +1,71 @@ +// +// MJPropertyType.m +// MJExtension +// +// Created by mj on 14-1-15. +// Copyright (c) 2014年 小码哥. All rights reserved. +// + +#import "MJPropertyType.h" +#import "MJExtension.h" +#import "MJFoundation.h" +#import "MJExtensionConst.h" + +@implementation MJPropertyType + ++ (instancetype)cachedTypeWithCode:(NSString *)code +{ + MJExtensionAssertParamNotNil2(code, nil); + + static NSMutableDictionary *types; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + types = [NSMutableDictionary dictionary]; + }); + + MJPropertyType *type = types[code]; + if (type == nil) { + type = [[self alloc] init]; + type.code = code; + types[code] = type; + } + return type; +} + +#pragma mark - 公共方法 +- (void)setCode:(NSString *)code +{ + _code = code; + + MJExtensionAssertParamNotNil(code); + + if ([code isEqualToString:MJPropertyTypeId]) { + _idType = YES; + } else if (code.length == 0) { + _KVCDisabled = YES; + } else if (code.length > 3 && [code hasPrefix:@"@\""]) { + // 去掉@"和",截取中间的类型名称 + _code = [code substringWithRange:NSMakeRange(2, code.length - 3)]; + _typeClass = NSClassFromString(_code); + _fromFoundation = [MJFoundation isClassFromFoundation:_typeClass]; + _numberType = [_typeClass isSubclassOfClass:[NSNumber class]]; + + } else if ([code isEqualToString:MJPropertyTypeSEL] || + [code isEqualToString:MJPropertyTypeIvar] || + [code isEqualToString:MJPropertyTypeMethod]) { + _KVCDisabled = YES; + } + + // 是否为数字类型 + NSString *lowerCode = _code.lowercaseString; + NSArray *numberTypes = @[MJPropertyTypeInt, MJPropertyTypeShort, MJPropertyTypeBOOL1, MJPropertyTypeBOOL2, MJPropertyTypeFloat, MJPropertyTypeDouble, MJPropertyTypeLong, MJPropertyTypeLongLong, MJPropertyTypeChar]; + if ([numberTypes containsObject:lowerCode]) { + _numberType = YES; + + if ([lowerCode isEqualToString:MJPropertyTypeBOOL1] + || [lowerCode isEqualToString:MJPropertyTypeBOOL2]) { + _boolType = YES; + } + } +} +@end diff --git a/Pods/MJExtension/MJExtension/NSObject+MJClass.h b/Pods/MJExtension/MJExtension/NSObject+MJClass.h new file mode 100644 index 0000000..260c8fc --- /dev/null +++ b/Pods/MJExtension/MJExtension/NSObject+MJClass.h @@ -0,0 +1,90 @@ +// +// NSObject+MJClass.h +// MJExtensionExample +// +// Created by MJ Lee on 15/8/11. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import + +/** + * 遍历所有类的block(父类) + */ +typedef void (^MJClassesEnumeration)(Class c, BOOL *stop); + +/** 这个数组中的属性名才会进行字典和模型的转换 */ +typedef NSArray * (^MJAllowedPropertyNames)(void); +/** 这个数组中的属性名才会进行归档 */ +typedef NSArray * (^MJAllowedCodingPropertyNames)(void); + +/** 这个数组中的属性名将会被忽略:不进行字典和模型的转换 */ +typedef NSArray * (^MJIgnoredPropertyNames)(void); +/** 这个数组中的属性名将会被忽略:不进行归档 */ +typedef NSArray * (^MJIgnoredCodingPropertyNames)(void); + +/** + * 类相关的扩展 + */ +@interface NSObject (MJClass) +/** + * 遍历所有的类 + */ ++ (void)mj_enumerateClasses:(MJClassesEnumeration)enumeration; ++ (void)mj_enumerateAllClasses:(MJClassesEnumeration)enumeration; + +#pragma mark - 属性白名单配置 +/** + * 这个数组中的属性名才会进行字典和模型的转换 + * + * @param allowedPropertyNames 这个数组中的属性名才会进行字典和模型的转换 + */ ++ (void)mj_setupAllowedPropertyNames:(MJAllowedPropertyNames)allowedPropertyNames; + +/** + * 这个数组中的属性名才会进行字典和模型的转换 + */ ++ (NSMutableArray *)mj_totalAllowedPropertyNames; + +#pragma mark - 属性黑名单配置 +/** + * 这个数组中的属性名将会被忽略:不进行字典和模型的转换 + * + * @param ignoredPropertyNames 这个数组中的属性名将会被忽略:不进行字典和模型的转换 + */ ++ (void)mj_setupIgnoredPropertyNames:(MJIgnoredPropertyNames)ignoredPropertyNames; + +/** + * 这个数组中的属性名将会被忽略:不进行字典和模型的转换 + */ ++ (NSMutableArray *)mj_totalIgnoredPropertyNames; + +#pragma mark - 归档属性白名单配置 +/** + * 这个数组中的属性名才会进行归档 + * + * @param allowedCodingPropertyNames 这个数组中的属性名才会进行归档 + */ ++ (void)mj_setupAllowedCodingPropertyNames:(MJAllowedCodingPropertyNames)allowedCodingPropertyNames; + +/** + * 这个数组中的属性名才会进行字典和模型的转换 + */ ++ (NSMutableArray *)mj_totalAllowedCodingPropertyNames; + +#pragma mark - 归档属性黑名单配置 +/** + * 这个数组中的属性名将会被忽略:不进行归档 + * + * @param ignoredCodingPropertyNames 这个数组中的属性名将会被忽略:不进行归档 + */ ++ (void)mj_setupIgnoredCodingPropertyNames:(MJIgnoredCodingPropertyNames)ignoredCodingPropertyNames; + +/** + * 这个数组中的属性名将会被忽略:不进行归档 + */ ++ (NSMutableArray *)mj_totalIgnoredCodingPropertyNames; + +#pragma mark - 内部使用 ++ (void)mj_setupBlockReturnValue:(id (^)(void))block key:(const char *)key; +@end diff --git a/Pods/MJExtension/MJExtension/NSObject+MJClass.m b/Pods/MJExtension/MJExtension/NSObject+MJClass.m new file mode 100644 index 0000000..c476751 --- /dev/null +++ b/Pods/MJExtension/MJExtension/NSObject+MJClass.m @@ -0,0 +1,174 @@ +// +// NSObject+MJClass.m +// MJExtensionExample +// +// Created by MJ Lee on 15/8/11. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "NSObject+MJClass.h" +#import "NSObject+MJCoding.h" +#import "NSObject+MJKeyValue.h" +#import "MJFoundation.h" +#import + +static const char MJAllowedPropertyNamesKey = '\0'; +static const char MJIgnoredPropertyNamesKey = '\0'; +static const char MJAllowedCodingPropertyNamesKey = '\0'; +static const char MJIgnoredCodingPropertyNamesKey = '\0'; + +@implementation NSObject (MJClass) + ++ (NSMutableDictionary *)mj_classDictForKey:(const void *)key +{ + static NSMutableDictionary *allowedPropertyNamesDict; + static NSMutableDictionary *ignoredPropertyNamesDict; + static NSMutableDictionary *allowedCodingPropertyNamesDict; + static NSMutableDictionary *ignoredCodingPropertyNamesDict; + + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + allowedPropertyNamesDict = [NSMutableDictionary dictionary]; + ignoredPropertyNamesDict = [NSMutableDictionary dictionary]; + allowedCodingPropertyNamesDict = [NSMutableDictionary dictionary]; + ignoredCodingPropertyNamesDict = [NSMutableDictionary dictionary]; + }); + + if (key == &MJAllowedPropertyNamesKey) return allowedPropertyNamesDict; + if (key == &MJIgnoredPropertyNamesKey) return ignoredPropertyNamesDict; + if (key == &MJAllowedCodingPropertyNamesKey) return allowedCodingPropertyNamesDict; + if (key == &MJIgnoredCodingPropertyNamesKey) return ignoredCodingPropertyNamesDict; + return nil; +} + ++ (void)mj_enumerateClasses:(MJClassesEnumeration)enumeration +{ + // 1.没有block就直接返回 + if (enumeration == nil) return; + + // 2.停止遍历的标记 + BOOL stop = NO; + + // 3.当前正在遍历的类 + Class c = self; + + // 4.开始遍历每一个类 + while (c && !stop) { + // 4.1.执行操作 + enumeration(c, &stop); + + // 4.2.获得父类 + c = class_getSuperclass(c); + + if ([MJFoundation isClassFromFoundation:c]) break; + } +} + ++ (void)mj_enumerateAllClasses:(MJClassesEnumeration)enumeration +{ + // 1.没有block就直接返回 + if (enumeration == nil) return; + + // 2.停止遍历的标记 + BOOL stop = NO; + + // 3.当前正在遍历的类 + Class c = self; + + // 4.开始遍历每一个类 + while (c && !stop) { + // 4.1.执行操作 + enumeration(c, &stop); + + // 4.2.获得父类 + c = class_getSuperclass(c); + } +} + +#pragma mark - 属性黑名单配置 ++ (void)mj_setupIgnoredPropertyNames:(MJIgnoredPropertyNames)ignoredPropertyNames +{ + [self mj_setupBlockReturnValue:ignoredPropertyNames key:&MJIgnoredPropertyNamesKey]; +} + ++ (NSMutableArray *)mj_totalIgnoredPropertyNames +{ + return [self mj_totalObjectsWithSelector:@selector(mj_ignoredPropertyNames) key:&MJIgnoredPropertyNamesKey]; +} + +#pragma mark - 归档属性黑名单配置 ++ (void)mj_setupIgnoredCodingPropertyNames:(MJIgnoredCodingPropertyNames)ignoredCodingPropertyNames +{ + [self mj_setupBlockReturnValue:ignoredCodingPropertyNames key:&MJIgnoredCodingPropertyNamesKey]; +} + ++ (NSMutableArray *)mj_totalIgnoredCodingPropertyNames +{ + return [self mj_totalObjectsWithSelector:@selector(mj_ignoredCodingPropertyNames) key:&MJIgnoredCodingPropertyNamesKey]; +} + +#pragma mark - 属性白名单配置 ++ (void)mj_setupAllowedPropertyNames:(MJAllowedPropertyNames)allowedPropertyNames; +{ + [self mj_setupBlockReturnValue:allowedPropertyNames key:&MJAllowedPropertyNamesKey]; +} + ++ (NSMutableArray *)mj_totalAllowedPropertyNames +{ + return [self mj_totalObjectsWithSelector:@selector(mj_allowedPropertyNames) key:&MJAllowedPropertyNamesKey]; +} + +#pragma mark - 归档属性白名单配置 ++ (void)mj_setupAllowedCodingPropertyNames:(MJAllowedCodingPropertyNames)allowedCodingPropertyNames +{ + [self mj_setupBlockReturnValue:allowedCodingPropertyNames key:&MJAllowedCodingPropertyNamesKey]; +} + ++ (NSMutableArray *)mj_totalAllowedCodingPropertyNames +{ + return [self mj_totalObjectsWithSelector:@selector(mj_allowedCodingPropertyNames) key:&MJAllowedCodingPropertyNamesKey]; +} + +#pragma mark - block和方法处理:存储block的返回值 ++ (void)mj_setupBlockReturnValue:(id (^)(void))block key:(const char *)key { + MJExtensionSemaphoreCreate + MJ_LOCK(mje_signalSemaphore); + if (block) { + objc_setAssociatedObject(self, key, block(), OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } else { + objc_setAssociatedObject(self, key, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + + // 清空数据 + [[self mj_classDictForKey:key] removeAllObjects]; + MJ_UNLOCK(mje_signalSemaphore); +} + ++ (NSMutableArray *)mj_totalObjectsWithSelector:(SEL)selector key:(const char *)key +{ + MJExtensionSemaphoreCreate + MJ_LOCK(mje_signalSemaphore); + NSMutableArray *array = [self mj_classDictForKey:key][NSStringFromClass(self)]; + if (array == nil) { + // 创建、存储 + [self mj_classDictForKey:key][NSStringFromClass(self)] = array = [NSMutableArray array]; + + if ([self respondsToSelector:selector]) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-performSelector-leaks" + NSArray *subArray = [self performSelector:selector]; +#pragma clang diagnostic pop + if (subArray) { + [array addObjectsFromArray:subArray]; + } + } + + [self mj_enumerateAllClasses:^(__unsafe_unretained Class c, BOOL *stop) { + NSArray *subArray = objc_getAssociatedObject(c, key); + [array addObjectsFromArray:subArray]; + }]; + } + MJ_UNLOCK(mje_signalSemaphore); + return array; +} +@end diff --git a/Pods/MJExtension/MJExtension/NSObject+MJCoding.h b/Pods/MJExtension/MJExtension/NSObject+MJCoding.h new file mode 100755 index 0000000..aeeb4eb --- /dev/null +++ b/Pods/MJExtension/MJExtension/NSObject+MJCoding.h @@ -0,0 +1,66 @@ +// +// NSObject+MJCoding.h +// MJExtension +// +// Created by mj on 14-1-15. +// Copyright (c) 2014年 小码哥. All rights reserved. +// + +#import +#import "MJExtensionConst.h" + +/** + * Codeing协议 + */ +@protocol MJCoding +@optional +/** + * 这个数组中的属性名才会进行归档 + */ ++ (NSArray *)mj_allowedCodingPropertyNames; +/** + * 这个数组中的属性名将会被忽略:不进行归档 + */ ++ (NSArray *)mj_ignoredCodingPropertyNames; +@end + +@interface NSObject (MJCoding) +/** + * 解码(从文件中解析对象) + */ +- (void)mj_decode:(NSCoder *)decoder; +/** + * 编码(将对象写入文件中) + */ +- (void)mj_encode:(NSCoder *)encoder; +@end + +/** + 归档的实现 + */ +#define MJCodingImplementation \ +- (id)initWithCoder:(NSCoder *)decoder \ +{ \ +if (self = [super init]) { \ +[self mj_decode:decoder]; \ +} \ +return self; \ +} \ +\ +- (void)encodeWithCoder:(NSCoder *)encoder \ +{ \ +[self mj_encode:encoder]; \ +}\ + +#define MJExtensionCodingImplementation MJCodingImplementation + +#define MJSecureCodingImplementation(CLASS, FLAG) \ +@interface CLASS (MJSecureCoding) \ +@end \ +@implementation CLASS (MJSecureCoding) \ +MJCodingImplementation \ ++ (BOOL)supportsSecureCoding { \ +return FLAG; \ +} \ +@end \ + diff --git a/Pods/MJExtension/MJExtension/NSObject+MJCoding.m b/Pods/MJExtension/MJExtension/NSObject+MJCoding.m new file mode 100755 index 0000000..614514a --- /dev/null +++ b/Pods/MJExtension/MJExtension/NSObject+MJCoding.m @@ -0,0 +1,59 @@ +// +// NSObject+MJCoding.m +// MJExtension +// +// Created by mj on 14-1-15. +// Copyright (c) 2014年 小码哥. All rights reserved. +// + +#import "NSObject+MJCoding.h" +#import "NSObject+MJClass.h" +#import "NSObject+MJProperty.h" +#import "MJProperty.h" + +@implementation NSObject (MJCoding) + +- (void)mj_encode:(NSCoder *)encoder +{ + Class clazz = [self class]; + + NSArray *allowedCodingPropertyNames = [clazz mj_totalAllowedCodingPropertyNames]; + NSArray *ignoredCodingPropertyNames = [clazz mj_totalIgnoredCodingPropertyNames]; + + [clazz mj_enumerateProperties:^(MJProperty *property, BOOL *stop) { + // 检测是否被忽略 + if (allowedCodingPropertyNames.count && ![allowedCodingPropertyNames containsObject:property.name]) return; + if ([ignoredCodingPropertyNames containsObject:property.name]) return; + + id value = [property valueForObject:self]; + if (value == nil) return; + [encoder encodeObject:value forKey:property.name]; + }]; +} + +- (void)mj_decode:(NSCoder *)decoder +{ + Class clazz = [self class]; + + NSArray *allowedCodingPropertyNames = [clazz mj_totalAllowedCodingPropertyNames]; + NSArray *ignoredCodingPropertyNames = [clazz mj_totalIgnoredCodingPropertyNames]; + + [clazz mj_enumerateProperties:^(MJProperty *property, BOOL *stop) { + // 检测是否被忽略 + if (allowedCodingPropertyNames.count && ![allowedCodingPropertyNames containsObject:property.name]) return; + if ([ignoredCodingPropertyNames containsObject:property.name]) return; + + // fixed `-[NSKeyedUnarchiver validateAllowedClass:forKey:] allowed unarchiving safe plist type ''NSNumber'(This will be disallowed in the future.)` warning. + Class genericClass = [property objectClassInArrayForClass:property.srcClass]; + // If genericClass exists, property.type.typeClass would be a collection type(Array, Set, Dictionary). This scenario([obj, nil, obj, nil]) would not happened. + NSSet *classes = [NSSet setWithObjects:NSNumber.class, + property.type.typeClass, genericClass, nil]; + id value = [decoder decodeObjectOfClasses:classes forKey:property.name]; + if (value == nil) { // 兼容以前的MJExtension版本 + value = [decoder decodeObjectForKey:[@"_" stringByAppendingString:property.name]]; + } + if (value == nil) return; + [property setValue:value forObject:self]; + }]; +} +@end diff --git a/Pods/MJExtension/MJExtension/NSObject+MJKeyValue.h b/Pods/MJExtension/MJExtension/NSObject+MJKeyValue.h new file mode 100755 index 0000000..3609357 --- /dev/null +++ b/Pods/MJExtension/MJExtension/NSObject+MJKeyValue.h @@ -0,0 +1,194 @@ +// +// NSObject+MJKeyValue.h +// MJExtension +// +// Created by mj on 13-8-24. +// Copyright (c) 2013年 小码哥. All rights reserved. +// + +#import +#import "MJExtensionConst.h" +#import +#import "MJProperty.h" + +/** + * KeyValue协议 + */ +@protocol MJKeyValue +@optional +/** + * 只有这个数组中的属性名才允许进行字典和模型的转换 + */ ++ (NSArray *)mj_allowedPropertyNames; + +/** + * 这个数组中的属性名将会被忽略:不进行字典和模型的转换 + */ ++ (NSArray *)mj_ignoredPropertyNames; + +/** + * 将属性名换为其他key去字典中取值 + * + * @return 字典中的key是属性名,value是从字典中取值用的key + */ ++ (NSDictionary *)mj_replacedKeyFromPropertyName; + +/** + * 将属性名换为其他key去字典中取值 + * + * @return 从字典中取值用的key + */ ++ (id)mj_replacedKeyFromPropertyName121:(NSString *)propertyName; + +/** + * 数组中需要转换的模型类 + * + * @return 字典中的key是数组属性名,value是数组中存放模型的Class(Class类型或者NSString类型) + */ ++ (NSDictionary *)mj_objectClassInArray; + + +/** 特殊地区在字符串格式化数字时使用 */ ++ (NSLocale *)mj_numberLocale; + +/** + * 旧值换新值,用于过滤字典中的值 + * + * @param oldValue 旧值 + * + * @return 新值 + */ +- (id)mj_newValueFromOldValue:(id)oldValue property:(MJProperty *)property; + +/** + * 当字典转模型完毕时调用 + */ +- (void)mj_keyValuesDidFinishConvertingToObject MJExtensionDeprecated("请使用`mj_didConvertToObjectWithKeyValues:`替代"); +- (void)mj_keyValuesDidFinishConvertingToObject:(NSDictionary *)keyValues MJExtensionDeprecated("请使用`mj_didConvertToObjectWithKeyValues:`替代"); +- (void)mj_didConvertToObjectWithKeyValues:(NSDictionary *)keyValues; + +/** + * 当模型转字典完毕时调用 + */ +- (void)mj_objectDidFinishConvertingToKeyValues MJExtensionDeprecated("请使用`mj_objectDidConvertToKeyValues:`替代"); +- (void)mj_objectDidConvertToKeyValues:(NSMutableDictionary *)keyValues; + +@end + +@interface NSObject (MJKeyValue) +#pragma mark - 类方法 +/** + * 字典转模型过程中遇到的错误 + */ ++ (NSError *)mj_error; + +/** + * 模型转字典时,字典的key是否参考replacedKeyFromPropertyName等方法(父类设置了,子类也会继承下来) + */ ++ (void)mj_referenceReplacedKeyWhenCreatingKeyValues:(BOOL)reference; + +#pragma mark - 对象方法 +/** + * 将字典的键值对转成模型属性 + * @param keyValues 字典(可以是NSDictionary、NSData、NSString) + */ +- (instancetype)mj_setKeyValues:(id)keyValues; + +/** + * 将字典的键值对转成模型属性 + * @param keyValues 字典(可以是NSDictionary、NSData、NSString) + * @param context CoreData上下文 + */ +- (instancetype)mj_setKeyValues:(id)keyValues context:(NSManagedObjectContext *)context; + +/** + * 将模型转成字典 + * @return 字典 + */ +- (NSMutableDictionary *)mj_keyValues; +- (NSMutableDictionary *)mj_keyValuesWithKeys:(NSArray *)keys; +- (NSMutableDictionary *)mj_keyValuesWithIgnoredKeys:(NSArray *)ignoredKeys; + +/** + * 通过模型数组来创建一个字典数组 + * @param objectArray 模型数组 + * @return 字典数组 + */ ++ (NSMutableArray *)mj_keyValuesArrayWithObjectArray:(NSArray *)objectArray; ++ (NSMutableArray *)mj_keyValuesArrayWithObjectArray:(NSArray *)objectArray keys:(NSArray *)keys; ++ (NSMutableArray *)mj_keyValuesArrayWithObjectArray:(NSArray *)objectArray ignoredKeys:(NSArray *)ignoredKeys; + +#pragma mark - 字典转模型 +/** + * 通过字典来创建一个模型 + * @param keyValues 字典(可以是NSDictionary、NSData、NSString) + * @return 新建的对象 + */ ++ (instancetype)mj_objectWithKeyValues:(id)keyValues; + +/** + * 通过字典来创建一个CoreData模型 + * @param keyValues 字典(可以是NSDictionary、NSData、NSString) + * @param context CoreData上下文 + * @return 新建的对象 + */ ++ (instancetype)mj_objectWithKeyValues:(id)keyValues context:(NSManagedObjectContext *)context; + +/** + * 通过plist来创建一个模型 + * @param filename 文件名(仅限于mainBundle中的文件) + * @return 新建的对象 + */ ++ (instancetype)mj_objectWithFilename:(NSString *)filename; + +/** + * 通过plist来创建一个模型 + * @param file 文件全路径 + * @return 新建的对象 + */ ++ (instancetype)mj_objectWithFile:(NSString *)file; + +#pragma mark - 字典数组转模型数组 +/** + * 通过字典数组来创建一个模型数组 + * @param keyValuesArray 字典数组(可以是NSDictionary、NSData、NSString) + * @return 模型数组 + */ ++ (NSMutableArray *)mj_objectArrayWithKeyValuesArray:(id)keyValuesArray; + +/** + * 通过字典数组来创建一个模型数组 + * @param keyValuesArray 字典数组(可以是NSDictionary、NSData、NSString) + * @param context CoreData上下文 + * @return 模型数组 + */ ++ (NSMutableArray *)mj_objectArrayWithKeyValuesArray:(id)keyValuesArray context:(NSManagedObjectContext *)context; + +/** + * 通过plist来创建一个模型数组 + * @param filename 文件名(仅限于mainBundle中的文件) + * @return 模型数组 + */ ++ (NSMutableArray *)mj_objectArrayWithFilename:(NSString *)filename; + +/** + * 通过plist来创建一个模型数组 + * @param file 文件全路径 + * @return 模型数组 + */ ++ (NSMutableArray *)mj_objectArrayWithFile:(NSString *)file; + +#pragma mark - 转换为JSON +/** + * 转换为JSON Data + */ +- (NSData *)mj_JSONData; +/** + * 转换为字典或者数组 + */ +- (id)mj_JSONObject; +/** + * 转换为JSON 字符串 + */ +- (NSString *)mj_JSONString; +@end diff --git a/Pods/MJExtension/MJExtension/NSObject+MJKeyValue.m b/Pods/MJExtension/MJExtension/NSObject+MJKeyValue.m new file mode 100755 index 0000000..c48e003 --- /dev/null +++ b/Pods/MJExtension/MJExtension/NSObject+MJKeyValue.m @@ -0,0 +1,524 @@ +// +// NSObject+MJKeyValue.m +// MJExtension +// +// Created by mj on 13-8-24. +// Copyright (c) 2013年 小码哥. All rights reserved. +// + +#import "NSObject+MJKeyValue.h" +#import "NSObject+MJProperty.h" +#import "NSString+MJExtension.h" +#import "MJProperty.h" +#import "MJPropertyType.h" +#import "MJExtensionConst.h" +#import "MJFoundation.h" +#import "NSString+MJExtension.h" +#import "NSObject+MJClass.h" + +@implementation NSDecimalNumber(MJKeyValue) + +- (id)mj_standardValueWithTypeCode:(NSString *)typeCode { + // 由于这里涉及到编译器问题, 暂时保留 Long, 实际上在 64 位系统上, 这 2 个精度范围相同, + // 32 位略有不同, 其余都可使用 Double 进行强转不丢失精度 + if ([typeCode isEqualToString:MJPropertyTypeLongLong]) { + return @(self.longLongValue); + } else if ([typeCode isEqualToString:MJPropertyTypeLongLong.uppercaseString]) { + return @(self.unsignedLongLongValue); + } else if ([typeCode isEqualToString:MJPropertyTypeLong]) { + return @(self.longValue); + } else if ([typeCode isEqualToString:MJPropertyTypeLong.uppercaseString]) { + return @(self.unsignedLongValue); + } else { + return @(self.doubleValue); + } +} + +@end + +@implementation NSObject (MJKeyValue) + +#pragma mark - 错误 +static const char MJErrorKey = '\0'; ++ (NSError *)mj_error +{ + return objc_getAssociatedObject(self, &MJErrorKey); +} + ++ (void)setMj_error:(NSError *)error +{ + objc_setAssociatedObject(self, &MJErrorKey, error, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#pragma mark - 模型 -> 字典时的参考 +/** 模型转字典时,字典的key是否参考replacedKeyFromPropertyName等方法(父类设置了,子类也会继承下来) */ +static const char MJReferenceReplacedKeyWhenCreatingKeyValuesKey = '\0'; + ++ (void)mj_referenceReplacedKeyWhenCreatingKeyValues:(BOOL)reference +{ + objc_setAssociatedObject(self, &MJReferenceReplacedKeyWhenCreatingKeyValuesKey, @(reference), OBJC_ASSOCIATION_ASSIGN); +} + ++ (BOOL)mj_isReferenceReplacedKeyWhenCreatingKeyValues +{ + __block id value = objc_getAssociatedObject(self, &MJReferenceReplacedKeyWhenCreatingKeyValuesKey); + if (!value) { + [self mj_enumerateAllClasses:^(__unsafe_unretained Class c, BOOL *stop) { + value = objc_getAssociatedObject(c, &MJReferenceReplacedKeyWhenCreatingKeyValuesKey); + + if (value) *stop = YES; + }]; + } + return [value boolValue]; +} + +#pragma mark - --常用的对象-- ++ (void)load +{ + // 默认设置 + [self mj_referenceReplacedKeyWhenCreatingKeyValues:YES]; +} + +#pragma mark - --公共方法-- +#pragma mark - 字典 -> 模型 +- (instancetype)mj_setKeyValues:(id)keyValues +{ + return [self mj_setKeyValues:keyValues context:nil]; +} + +/** + 核心代码: + */ +- (instancetype)mj_setKeyValues:(id)keyValues context:(NSManagedObjectContext *)context +{ + // 获得JSON对象 + keyValues = [keyValues mj_JSONObject]; + + MJExtensionAssertError([keyValues isKindOfClass:[NSDictionary class]], self, [self class], @"keyValues参数不是一个字典"); + + Class clazz = [self class]; + NSArray *allowedPropertyNames = [clazz mj_totalAllowedPropertyNames]; + NSArray *ignoredPropertyNames = [clazz mj_totalIgnoredPropertyNames]; + + NSLocale *numberLocale = nil; + if ([self.class respondsToSelector:@selector(mj_numberLocale)]) { + numberLocale = self.class.mj_numberLocale; + } + + //通过封装的方法回调一个通过运行时编写的,用于返回属性列表的方法。 + [clazz mj_enumerateProperties:^(MJProperty *property, BOOL *stop) { + @try { + // 0.检测是否被忽略 + if (allowedPropertyNames.count && ![allowedPropertyNames containsObject:property.name]) return; + if ([ignoredPropertyNames containsObject:property.name]) return; + + // 1.取出属性值 + id value; + NSArray *propertyKeyses = [property propertyKeysForClass:clazz]; + for (NSArray *propertyKeys in propertyKeyses) { + value = keyValues; + for (MJPropertyKey *propertyKey in propertyKeys) { + value = [propertyKey valueInObject:value]; + } + if (value) break; + } + + // 值的过滤 + id newValue = [clazz mj_getNewValueFromObject:self oldValue:value property:property]; + if (newValue != value) { // 有过滤后的新值 + [property setValue:newValue forObject:self]; + return; + } + + // 如果没有值,就直接返回 + if (!value || value == [NSNull null]) return; + + // 2.复杂处理 + MJPropertyType *type = property.type; + Class propertyClass = type.typeClass; + Class objectClass = [property objectClassInArrayForClass:[self class]]; + + // 不可变 -> 可变处理 + if (propertyClass == [NSMutableArray class] && [value isKindOfClass:[NSArray class]]) { + value = [NSMutableArray arrayWithArray:value]; + } else if (propertyClass == [NSMutableDictionary class] && [value isKindOfClass:[NSDictionary class]]) { + value = [NSMutableDictionary dictionaryWithDictionary:value]; + } else if (propertyClass == [NSMutableString class] && [value isKindOfClass:[NSString class]]) { + value = [NSMutableString stringWithString:value]; + } else if (propertyClass == [NSMutableData class] && [value isKindOfClass:[NSData class]]) { + value = [NSMutableData dataWithData:value]; + } + + if (!type.isFromFoundation && propertyClass) { // 模型属性 + value = [propertyClass mj_objectWithKeyValues:value context:context]; + } else if (objectClass) { + if (objectClass == [NSURL class] && [value isKindOfClass:[NSArray class]]) { + // string array -> url array + NSMutableArray *urlArray = [NSMutableArray array]; + for (NSString *string in value) { + if (![string isKindOfClass:[NSString class]]) continue; + [urlArray addObject:string.mj_url]; + } + value = urlArray; + } else { // 字典数组-->模型数组 + value = [objectClass mj_objectArrayWithKeyValuesArray:value context:context]; + } + } else if (propertyClass == [NSString class]) { + if ([value isKindOfClass:[NSNumber class]]) { + // NSNumber -> NSString + value = [value description]; + } else if ([value isKindOfClass:[NSURL class]]) { + // NSURL -> NSString + value = [value absoluteString]; + } + } else if ([value isKindOfClass:[NSString class]]) { + if (propertyClass == [NSURL class]) { + // NSString -> NSURL + // 字符串转码 + value = [value mj_url]; + } else if (type.isNumberType) { + NSString *oldValue = value; + + // NSString -> NSDecimalNumber, 使用 DecimalNumber 来转换数字, 避免丢失精度以及溢出 + NSDecimalNumber *decimalValue = [NSDecimalNumber decimalNumberWithString:oldValue + locale:numberLocale]; + + // 检查特殊情况 + if (decimalValue == NSDecimalNumber.notANumber) { + value = @(0); + }else if (propertyClass != [NSDecimalNumber class]) { + value = [decimalValue mj_standardValueWithTypeCode:type.code]; + } else { + value = decimalValue; + } + + // 如果是BOOL + if (type.isBoolType) { + // 字符串转BOOL(字符串没有charValue方法) + // 系统会调用字符串的charValue转为BOOL类型 + NSString *lower = [oldValue lowercaseString]; + if ([lower isEqualToString:@"yes"] || [lower isEqualToString:@"true"]) { + value = @YES; + } else if ([lower isEqualToString:@"no"] || [lower isEqualToString:@"false"]) { + value = @NO; + } + } + } + } else if ([value isKindOfClass:[NSNumber class]] && propertyClass == [NSDecimalNumber class]){ + // 过滤 NSDecimalNumber类型 + if (![value isKindOfClass:[NSDecimalNumber class]]) { + value = [NSDecimalNumber decimalNumberWithDecimal:[((NSNumber *)value) decimalValue]]; + } + } + + // 经过转换后, 最终检查 value 与 property 是否匹配 + if (propertyClass && ![value isKindOfClass:propertyClass]) { + value = nil; + } + + // 3.赋值 + [property setValue:value forObject:self]; + } @catch (NSException *exception) { + MJExtensionBuildError([self class], exception.reason); + MJExtensionLog(@"%@", exception); +#ifdef DEBUG + [exception raise]; +#endif + } + }]; + + // 转换完毕 + if ([self respondsToSelector:@selector(mj_didConvertToObjectWithKeyValues:)]) { + [self mj_didConvertToObjectWithKeyValues:keyValues]; + } +#pragma clang diagnostic push +#pragma clang diagnostic ignored"-Wdeprecated-declarations" + if ([self respondsToSelector:@selector(mj_keyValuesDidFinishConvertingToObject)]) { + [self mj_keyValuesDidFinishConvertingToObject]; + } + if ([self respondsToSelector:@selector(mj_keyValuesDidFinishConvertingToObject:)]) { + [self mj_keyValuesDidFinishConvertingToObject:keyValues]; + } +#pragma clang diagnostic pop + return self; +} + ++ (instancetype)mj_objectWithKeyValues:(id)keyValues +{ + return [self mj_objectWithKeyValues:keyValues context:nil]; +} + ++ (instancetype)mj_objectWithKeyValues:(id)keyValues context:(NSManagedObjectContext *)context +{ + // 获得JSON对象 + keyValues = [keyValues mj_JSONObject]; + MJExtensionAssertError([keyValues isKindOfClass:[NSDictionary class]], nil, [self class], @"keyValues参数不是一个字典"); + + if ([self isSubclassOfClass:[NSManagedObject class]] && context) { + NSString *entityName = [(NSManagedObject *)self entity].name; + return [[NSEntityDescription insertNewObjectForEntityForName:entityName inManagedObjectContext:context] mj_setKeyValues:keyValues context:context]; + } + return [[[self alloc] init] mj_setKeyValues:keyValues]; +} + ++ (instancetype)mj_objectWithFilename:(NSString *)filename +{ + MJExtensionAssertError(filename != nil, nil, [self class], @"filename参数为nil"); + + return [self mj_objectWithFile:[[NSBundle mainBundle] pathForResource:filename ofType:nil]]; +} + ++ (instancetype)mj_objectWithFile:(NSString *)file +{ + MJExtensionAssertError(file != nil, nil, [self class], @"file参数为nil"); + + return [self mj_objectWithKeyValues:[NSDictionary dictionaryWithContentsOfFile:file]]; +} + +#pragma mark - 字典数组 -> 模型数组 ++ (NSMutableArray *)mj_objectArrayWithKeyValuesArray:(NSArray *)keyValuesArray +{ + return [self mj_objectArrayWithKeyValuesArray:keyValuesArray context:nil]; +} + ++ (NSMutableArray *)mj_objectArrayWithKeyValuesArray:(id)keyValuesArray context:(NSManagedObjectContext *)context +{ + // 如果是JSON字符串 + keyValuesArray = [keyValuesArray mj_JSONObject]; + + // 1.判断真实性 + MJExtensionAssertError([keyValuesArray isKindOfClass:[NSArray class]], nil, [self class], @"keyValuesArray参数不是一个数组"); + + // 如果数组里面放的是NSString、NSNumber等数据 + if ([MJFoundation isClassFromFoundation:self]) return [NSMutableArray arrayWithArray:keyValuesArray]; + + + // 2.创建数组 + NSMutableArray *modelArray = [NSMutableArray array]; + + // 3.遍历 + for (NSDictionary *keyValues in keyValuesArray) { + if ([keyValues isKindOfClass:[NSArray class]]){ + [modelArray addObject:[self mj_objectArrayWithKeyValuesArray:keyValues context:context]]; + } else { + id model = [self mj_objectWithKeyValues:keyValues context:context]; + if (model) [modelArray addObject:model]; + } + } + + return modelArray; +} + ++ (NSMutableArray *)mj_objectArrayWithFilename:(NSString *)filename +{ + MJExtensionAssertError(filename != nil, nil, [self class], @"filename参数为nil"); + + return [self mj_objectArrayWithFile:[[NSBundle mainBundle] pathForResource:filename ofType:nil]]; +} + ++ (NSMutableArray *)mj_objectArrayWithFile:(NSString *)file +{ + MJExtensionAssertError(file != nil, nil, [self class], @"file参数为nil"); + + return [self mj_objectArrayWithKeyValuesArray:[NSArray arrayWithContentsOfFile:file]]; +} + +#pragma mark - 模型 -> 字典 +- (NSMutableDictionary *)mj_keyValues +{ + return [self mj_keyValuesWithKeys:nil ignoredKeys:nil]; +} + +- (NSMutableDictionary *)mj_keyValuesWithKeys:(NSArray *)keys +{ + return [self mj_keyValuesWithKeys:keys ignoredKeys:nil]; +} + +- (NSMutableDictionary *)mj_keyValuesWithIgnoredKeys:(NSArray *)ignoredKeys +{ + return [self mj_keyValuesWithKeys:nil ignoredKeys:ignoredKeys]; +} + +- (NSMutableDictionary *)mj_keyValuesWithKeys:(NSArray *)keys ignoredKeys:(NSArray *)ignoredKeys +{ + // 如果自己不是模型类, 那就返回自己 + // 模型类过滤掉 NSNull + // 唯一一个不返回自己的 + if ([self isMemberOfClass:NSNull.class]) { return nil; } + // 这里虽然返回了自己, 但是其实是有报错信息的. + // TODO: 报错机制不好, 需要重做 + MJExtensionAssertError(![MJFoundation isClassFromFoundation:[self class]], (NSMutableDictionary *)self, [self class], @"不是自定义的模型类") + + id keyValues = [NSMutableDictionary dictionary]; + + Class clazz = [self class]; + NSArray *allowedPropertyNames = [clazz mj_totalAllowedPropertyNames]; + NSArray *ignoredPropertyNames = [clazz mj_totalIgnoredPropertyNames]; + + [clazz mj_enumerateProperties:^(MJProperty *property, BOOL *stop) { + @try { + // 0.检测是否被忽略 + if (allowedPropertyNames.count && ![allowedPropertyNames containsObject:property.name]) return; + if ([ignoredPropertyNames containsObject:property.name]) return; + if (keys.count && ![keys containsObject:property.name]) return; + if ([ignoredKeys containsObject:property.name]) return; + + // 1.取出属性值 + id value = [property valueForObject:self]; + if (!value) return; + + // 2.如果是模型属性 + MJPropertyType *type = property.type; + Class propertyClass = type.typeClass; + if (!type.isFromFoundation && propertyClass) { + value = [value mj_keyValues]; + } else if ([value isKindOfClass:[NSArray class]]) { + // 3.处理数组里面有模型的情况 + value = [NSObject mj_keyValuesArrayWithObjectArray:value]; + } else if (propertyClass == [NSURL class]) { + value = [value absoluteString]; + } + + // 4.赋值 + if ([clazz mj_isReferenceReplacedKeyWhenCreatingKeyValues]) { + NSArray *propertyKeys = [[property propertyKeysForClass:clazz] firstObject]; + NSUInteger keyCount = propertyKeys.count; + // 创建字典 + __block id innerContainer = keyValues; + [propertyKeys enumerateObjectsUsingBlock:^(MJPropertyKey *propertyKey, NSUInteger idx, BOOL *stop) { + // 下一个属性 + MJPropertyKey *nextPropertyKey = nil; + if (idx != keyCount - 1) { + nextPropertyKey = propertyKeys[idx + 1]; + } + + if (nextPropertyKey) { // 不是最后一个key + // 当前propertyKey对应的字典或者数组 + id tempInnerContainer = [propertyKey valueInObject:innerContainer]; + if (tempInnerContainer == nil || [tempInnerContainer isKindOfClass:[NSNull class]]) { + if (nextPropertyKey.type == MJPropertyKeyTypeDictionary) { + tempInnerContainer = [NSMutableDictionary dictionary]; + } else { + tempInnerContainer = [NSMutableArray array]; + } + if (propertyKey.type == MJPropertyKeyTypeDictionary) { + innerContainer[propertyKey.name] = tempInnerContainer; + } else { + innerContainer[propertyKey.name.intValue] = tempInnerContainer; + } + } + + if ([tempInnerContainer isKindOfClass:[NSMutableArray class]]) { + NSMutableArray *tempInnerContainerArray = tempInnerContainer; + int index = nextPropertyKey.name.intValue; + while (tempInnerContainerArray.count < index + 1) { + [tempInnerContainerArray addObject:[NSNull null]]; + } + } + + innerContainer = tempInnerContainer; + } else { // 最后一个key + if (propertyKey.type == MJPropertyKeyTypeDictionary) { + innerContainer[propertyKey.name] = value; + } else { + innerContainer[propertyKey.name.intValue] = value; + } + } + }]; + } else { + keyValues[property.name] = value; + } + } @catch (NSException *exception) { + MJExtensionBuildError([self class], exception.reason); + MJExtensionLog(@"%@", exception); +#ifdef DEBUG + [exception raise]; +#endif + } + }]; + + // 转换完毕 + if ([self respondsToSelector:@selector(mj_objectDidConvertToKeyValues:)]) { + [self mj_objectDidConvertToKeyValues:keyValues]; + } +#pragma clang diagnostic push +#pragma clang diagnostic ignored"-Wdeprecated-declarations" + if ([self respondsToSelector:@selector(mj_objectDidFinishConvertingToKeyValues)]) { + [self mj_objectDidFinishConvertingToKeyValues]; + } +#pragma clang diagnostic pop + + return keyValues; +} +#pragma mark - 模型数组 -> 字典数组 ++ (NSMutableArray *)mj_keyValuesArrayWithObjectArray:(NSArray *)objectArray +{ + return [self mj_keyValuesArrayWithObjectArray:objectArray keys:nil ignoredKeys:nil]; +} + ++ (NSMutableArray *)mj_keyValuesArrayWithObjectArray:(NSArray *)objectArray keys:(NSArray *)keys +{ + return [self mj_keyValuesArrayWithObjectArray:objectArray keys:keys ignoredKeys:nil]; +} + ++ (NSMutableArray *)mj_keyValuesArrayWithObjectArray:(NSArray *)objectArray ignoredKeys:(NSArray *)ignoredKeys +{ + return [self mj_keyValuesArrayWithObjectArray:objectArray keys:nil ignoredKeys:ignoredKeys]; +} + ++ (NSMutableArray *)mj_keyValuesArrayWithObjectArray:(NSArray *)objectArray keys:(NSArray *)keys ignoredKeys:(NSArray *)ignoredKeys +{ + // 0.判断真实性 + MJExtensionAssertError([objectArray isKindOfClass:[NSArray class]], nil, [self class], @"objectArray参数不是一个数组"); + + // 1.创建数组 + NSMutableArray *keyValuesArray = [NSMutableArray array]; + for (id object in objectArray) { + if (keys) { + id convertedObj = [object mj_keyValuesWithKeys:keys]; + if (!convertedObj) { continue; } + [keyValuesArray addObject:convertedObj]; + } else { + id convertedObj = [object mj_keyValuesWithIgnoredKeys:ignoredKeys]; + if (!convertedObj) { continue; } + [keyValuesArray addObject:convertedObj]; + } + } + return keyValuesArray; +} + +#pragma mark - 转换为JSON +- (NSData *)mj_JSONData +{ + if ([self isKindOfClass:[NSString class]]) { + return [((NSString *)self) dataUsingEncoding:NSUTF8StringEncoding]; + } else if ([self isKindOfClass:[NSData class]]) { + return (NSData *)self; + } + + return [NSJSONSerialization dataWithJSONObject:[self mj_JSONObject] options:kNilOptions error:nil]; +} + +- (id)mj_JSONObject +{ + if ([self isKindOfClass:[NSString class]]) { + return [NSJSONSerialization JSONObjectWithData:[((NSString *)self) dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil]; + } else if ([self isKindOfClass:[NSData class]]) { + return [NSJSONSerialization JSONObjectWithData:(NSData *)self options:kNilOptions error:nil]; + } + + return self.mj_keyValues; +} + +- (NSString *)mj_JSONString +{ + if ([self isKindOfClass:[NSString class]]) { + return (NSString *)self; + } else if ([self isKindOfClass:[NSData class]]) { + return [[NSString alloc] initWithData:(NSData *)self encoding:NSUTF8StringEncoding]; + } + + return [[NSString alloc] initWithData:[self mj_JSONData] encoding:NSUTF8StringEncoding]; +} + +@end diff --git a/Pods/MJExtension/MJExtension/NSObject+MJProperty.h b/Pods/MJExtension/MJExtension/NSObject+MJProperty.h new file mode 100644 index 0000000..1bf88e9 --- /dev/null +++ b/Pods/MJExtension/MJExtension/NSObject+MJProperty.h @@ -0,0 +1,70 @@ +// +// NSObject+MJProperty.h +// MJExtensionExample +// +// Created by MJ Lee on 15/4/17. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import +#import "MJExtensionConst.h" + +@class MJProperty; + +/** + * 遍历成员变量用的block + * + * @param property 成员的包装对象 + * @param stop YES代表停止遍历,NO代表继续遍历 + */ +typedef void (^MJPropertiesEnumeration)(MJProperty *property, BOOL *stop); + +/** 将属性名换为其他key去字典中取值 */ +typedef NSDictionary * (^MJReplacedKeyFromPropertyName)(void); +typedef id (^MJReplacedKeyFromPropertyName121)(NSString *propertyName); +/** 数组中需要转换的模型类 */ +typedef NSDictionary * (^MJObjectClassInArray)(void); +/** 用于过滤字典中的值 */ +typedef id (^MJNewValueFromOldValue)(id object, id oldValue, MJProperty *property); + +/** + * 成员属性相关的扩展 + */ +@interface NSObject (MJProperty) +#pragma mark - 遍历 +/** + * 遍历所有的成员 + */ ++ (void)mj_enumerateProperties:(MJPropertiesEnumeration)enumeration; + +#pragma mark - 新值配置 +/** + * 用于过滤字典中的值 + * + * @param newValueFormOldValue 用于过滤字典中的值 + */ ++ (void)mj_setupNewValueFromOldValue:(MJNewValueFromOldValue)newValueFormOldValue; ++ (id)mj_getNewValueFromObject:(__unsafe_unretained id)object oldValue:(__unsafe_unretained id)oldValue property:(__unsafe_unretained MJProperty *)property; + +#pragma mark - key配置 +/** + * 将属性名换为其他key去字典中取值 + * + * @param replacedKeyFromPropertyName 将属性名换为其他key去字典中取值 + */ ++ (void)mj_setupReplacedKeyFromPropertyName:(MJReplacedKeyFromPropertyName)replacedKeyFromPropertyName; +/** + * 将属性名换为其他key去字典中取值 + * + * @param replacedKeyFromPropertyName121 将属性名换为其他key去字典中取值 + */ ++ (void)mj_setupReplacedKeyFromPropertyName121:(MJReplacedKeyFromPropertyName121)replacedKeyFromPropertyName121; + +#pragma mark - array model class配置 +/** + * 数组中需要转换的模型类 + * + * @param objectClassInArray 数组中需要转换的模型类 + */ ++ (void)mj_setupObjectClassInArray:(MJObjectClassInArray)objectClassInArray; +@end diff --git a/Pods/MJExtension/MJExtension/NSObject+MJProperty.m b/Pods/MJExtension/MJExtension/NSObject+MJProperty.m new file mode 100644 index 0000000..71b08f4 --- /dev/null +++ b/Pods/MJExtension/MJExtension/NSObject+MJProperty.m @@ -0,0 +1,240 @@ +// +// NSObject+MJProperty.m +// MJExtensionExample +// +// Created by MJ Lee on 15/4/17. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "NSObject+MJProperty.h" +#import "NSObject+MJKeyValue.h" +#import "NSObject+MJCoding.h" +#import "NSObject+MJClass.h" +#import "MJProperty.h" +#import "MJFoundation.h" +#import + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wundeclared-selector" +#pragma clang diagnostic ignored "-Warc-performSelector-leaks" + +static const char MJReplacedKeyFromPropertyNameKey = '\0'; +static const char MJReplacedKeyFromPropertyName121Key = '\0'; +static const char MJNewValueFromOldValueKey = '\0'; +static const char MJObjectClassInArrayKey = '\0'; + +static const char MJCachedPropertiesKey = '\0'; + +dispatch_semaphore_t mje_signalSemaphore; +dispatch_once_t mje_onceTokenSemaphore; + +@implementation NSObject (Property) + ++ (NSMutableDictionary *)mj_propertyDictForKey:(const void *)key +{ + static NSMutableDictionary *replacedKeyFromPropertyNameDict; + static NSMutableDictionary *replacedKeyFromPropertyName121Dict; + static NSMutableDictionary *newValueFromOldValueDict; + static NSMutableDictionary *objectClassInArrayDict; + static NSMutableDictionary *cachedPropertiesDict; + + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + replacedKeyFromPropertyNameDict = [NSMutableDictionary dictionary]; + replacedKeyFromPropertyName121Dict = [NSMutableDictionary dictionary]; + newValueFromOldValueDict = [NSMutableDictionary dictionary]; + objectClassInArrayDict = [NSMutableDictionary dictionary]; + cachedPropertiesDict = [NSMutableDictionary dictionary]; + }); + + if (key == &MJReplacedKeyFromPropertyNameKey) return replacedKeyFromPropertyNameDict; + if (key == &MJReplacedKeyFromPropertyName121Key) return replacedKeyFromPropertyName121Dict; + if (key == &MJNewValueFromOldValueKey) return newValueFromOldValueDict; + if (key == &MJObjectClassInArrayKey) return objectClassInArrayDict; + if (key == &MJCachedPropertiesKey) return cachedPropertiesDict; + return nil; +} + +#pragma mark - --私有方法-- ++ (id)mj_propertyKey:(NSString *)propertyName +{ + MJExtensionAssertParamNotNil2(propertyName, nil); + + __block id key = nil; + // 查看有没有需要替换的key + if ([self respondsToSelector:@selector(mj_replacedKeyFromPropertyName121:)]) { + key = [self mj_replacedKeyFromPropertyName121:propertyName]; + } + + // 调用block + if (!key) { + [self mj_enumerateAllClasses:^(__unsafe_unretained Class c, BOOL *stop) { + MJReplacedKeyFromPropertyName121 block = objc_getAssociatedObject(c, &MJReplacedKeyFromPropertyName121Key); + if (block) { + key = block(propertyName); + } + if (key) *stop = YES; + }]; + } + + // 查看有没有需要替换的key + if ((!key || [key isEqual:propertyName]) && [self respondsToSelector:@selector(mj_replacedKeyFromPropertyName)]) { + key = [self mj_replacedKeyFromPropertyName][propertyName]; + } + + if (!key || [key isEqual:propertyName]) { + [self mj_enumerateAllClasses:^(__unsafe_unretained Class c, BOOL *stop) { + NSDictionary *dict = objc_getAssociatedObject(c, &MJReplacedKeyFromPropertyNameKey); + if (dict) { + key = dict[propertyName]; + } + if (key && ![key isEqual:propertyName]) *stop = YES; + }]; + } + + // 2.用属性名作为key + if (!key) key = propertyName; + + return key; +} + ++ (Class)mj_propertyObjectClassInArray:(NSString *)propertyName +{ + __block id clazz = nil; + if ([self respondsToSelector:@selector(mj_objectClassInArray)]) { + clazz = [self mj_objectClassInArray][propertyName]; + } + + if (!clazz) { + [self mj_enumerateAllClasses:^(__unsafe_unretained Class c, BOOL *stop) { + NSDictionary *dict = objc_getAssociatedObject(c, &MJObjectClassInArrayKey); + if (dict) { + clazz = dict[propertyName]; + } + if (clazz) *stop = YES; + }]; + } + + // 如果是NSString类型 + if ([clazz isKindOfClass:[NSString class]]) { + clazz = NSClassFromString(clazz); + } + return clazz; +} + +#pragma mark - --公共方法-- ++ (void)mj_enumerateProperties:(MJPropertiesEnumeration)enumeration +{ + // 获得成员变量 + NSArray *cachedProperties = [self mj_properties]; + // 遍历成员变量 + BOOL stop = NO; + for (MJProperty *property in cachedProperties) { + enumeration(property, &stop); + if (stop) break; + } +} + +#pragma mark - 公共方法 ++ (NSArray *)mj_properties +{ + MJExtensionSemaphoreCreate + MJ_LOCK(mje_signalSemaphore); + NSMutableDictionary *cachedInfo = [self mj_propertyDictForKey:&MJCachedPropertiesKey]; + NSMutableArray *cachedProperties = cachedInfo[NSStringFromClass(self)]; + if (cachedProperties == nil) { + cachedProperties = [NSMutableArray array]; + + [self mj_enumerateClasses:^(__unsafe_unretained Class c, BOOL *stop) { + // 1.获得所有的成员变量 + unsigned int outCount = 0; + objc_property_t *properties = class_copyPropertyList(c, &outCount); + + // 2.遍历每一个成员变量 + for (unsigned int i = 0; i +#import "MJExtensionConst.h" + +@interface NSString (MJExtension) +/** + * 驼峰转下划线(loveYou -> love_you) + */ +- (NSString *)mj_underlineFromCamel; +/** + * 下划线转驼峰(love_you -> loveYou) + */ +- (NSString *)mj_camelFromUnderline; +/** + * 首字母变大写 + */ +- (NSString *)mj_firstCharUpper; +/** + * 首字母变小写 + */ +- (NSString *)mj_firstCharLower; + +- (BOOL)mj_isPureInt; + +- (NSURL *)mj_url; +@end diff --git a/Pods/MJExtension/MJExtension/NSString+MJExtension.m b/Pods/MJExtension/MJExtension/NSString+MJExtension.m new file mode 100644 index 0000000..20533c5 --- /dev/null +++ b/Pods/MJExtension/MJExtension/NSString+MJExtension.m @@ -0,0 +1,80 @@ +// +// NSString+MJExtension.m +// MJExtensionExample +// +// Created by MJ Lee on 15/6/7. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "NSString+MJExtension.h" + +@implementation NSString (MJExtension) +- (NSString *)mj_underlineFromCamel +{ + if (self.length == 0) return self; + NSMutableString *string = [NSMutableString string]; + for (NSUInteger i = 0; i= 2) [string appendString:[cmp substringFromIndex:1]]; + } else { + [string appendString:cmp]; + } + } + return string; +} + +- (NSString *)mj_firstCharLower +{ + if (self.length == 0) return self; + NSMutableString *string = [NSMutableString string]; + [string appendString:[NSString stringWithFormat:@"%c", [self characterAtIndex:0]].lowercaseString]; + if (self.length >= 2) [string appendString:[self substringFromIndex:1]]; + return string; +} + +- (NSString *)mj_firstCharUpper +{ + if (self.length == 0) return self; + NSMutableString *string = [NSMutableString string]; + [string appendString:[NSString stringWithFormat:@"%c", [self characterAtIndex:0]].uppercaseString]; + if (self.length >= 2) [string appendString:[self substringFromIndex:1]]; + return string; +} + +- (BOOL)mj_isPureInt +{ + NSScanner *scan = [NSScanner scannerWithString:self]; + int val; + return [scan scanInt:&val] && [scan isAtEnd]; +} + +- (NSURL *)mj_url +{ +// [self stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"!$&'()*+,-./:;=?@_~%#[]"]]; +#pragma clang diagnostic push +#pragma clang diagnostic ignored"-Wdeprecated-declarations" + return [NSURL URLWithString:(NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)self, (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]", NULL,kCFStringEncodingUTF8))]; +#pragma clang diagnostic pop +} +@end diff --git a/Pods/MJExtension/MJExtension/PrivacyInfo.xcprivacy b/Pods/MJExtension/MJExtension/PrivacyInfo.xcprivacy new file mode 100644 index 0000000..0c89028 --- /dev/null +++ b/Pods/MJExtension/MJExtension/PrivacyInfo.xcprivacy @@ -0,0 +1,14 @@ + + + + + NSPrivacyTracking + + NSPrivacyTrackingDomains + + NSPrivacyAccessedAPITypes + + NSPrivacyCollectedDataTypes + + + diff --git a/Pods/MJExtension/README.md b/Pods/MJExtension/README.md new file mode 100644 index 0000000..b638414 --- /dev/null +++ b/Pods/MJExtension/README.md @@ -0,0 +1,637 @@ +MJExtension +=== +[![SPM supported](https://img.shields.io/badge/SPM-supported-4BC51D.svg?style=flat)](https://github.com/apple/swift-package-manager) +[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) +[![podversion](https://img.shields.io/cocoapods/v/MJExtension.svg)](https://cocoapods.org/pods/MJExtension) +![Platform](https://img.shields.io/cocoapods/p/MJExtension.svg?style=flat) + +- A fast, convenient and nonintrusive conversion framework between JSON and model. +- 转换速度快、使用简单方便的字典转模型框架 + +[📜✍🏻**Release Notes**: more details](https://github.com/CoderMJLee/MJExtension/releases) + +## Contents + +* [Getting Started 【开始使用】](#Getting_Started) + * [Features 【能做什么】](#Features) + * [Installation 【安装】](#Installation) +* [Examples 【示例】](#Examples) + * [Usage in Swift](#usage_in_swift) + * [JSON -> Model](#JSON_Model) + * [JSONString -> Model](#JSONString_Model) + * [Model contains model](#Model_contains_model) + * [Model contains model-array](#Model_contains_model_array) + * [Model name - JSON key mapping](#Model_name_JSON_key_mapping) + * [JSON array -> model array](#JSON_array_model_array) + * [Model -> JSON](#Model_JSON) + * [Model array -> JSON array](#Model_array_JSON_array) + * [Core Data](#Core_Data) + * [Coding](#Coding) + * [Secure Coding](#SecureCoding) + * [Camel -> underline](#Camel_underline) + * [NSString -> NSDate, nil -> @""](#NSString_NSDate) + * [NSDate -> NSString](#NSDate_NSString) + * [More use cases](#More_use_cases) + +--- + +## Getting Started【开始使用】 + +### Features【能做什么】 +- MJExtension是一套字典和模型之间互相转换的超轻量级框架 +* `JSON` --> `Model`、`Core Data Model` +* `JSONString` --> `Model`、`Core Data Model` +* `Model`、`Core Data Model` --> `JSON` +* `JSON Array` --> `Model Array`、`Core Data Model Array` +* `JSONString` --> `Model Array`、`Core Data Model Array` +* `Model Array`、`Core Data Model Array` --> `JSON Array` +* Coding all properties of a model with only one line of code. + * 只需要一行代码,就能实现模型的所有属性进行Coding / SecureCoding(归档和解档) + +### Installation【安装】 + +#### CocoaPods【使用CocoaPods】 + +```ruby +pod 'MJExtension' +``` + +#### Carthage + +```ruby +github "CoderMJLee/MJExtension" +``` + +#### Swift Package Manager + +Released from [`3.4.0`](https://github.com/CoderMJLee/MJExtension/releases/) + +#### Manually【手动导入】 + +- Drag all source files under folder `MJExtension` to your project.【将`MJExtension`文件夹中的所有源代码拽入项目中】 +- Import the main header file:`#import "MJExtension.h"`【导入主头文件:`#import "MJExtension.h"`】 + +## Examples【示例】 + +**Add `MJKeyValue` protocol to your model if needed【如果有需要, 请在模型中加入 `MJKeyValue` 协议】** + +### Usage in Swift [关于在Swift中使用MJExtension] ‼️ + +> Example: +> +> - [Model - MJTester.swift](MJExtensionTests/SwiftModel/MJTester.swift) +> +> - [Usage - SwiftModelTests.swift](MJExtensionTests/SwiftModelTests.swift) + +```swift +@objc(MJTester) +@objcMembers +class MJTester: NSObject { + // make sure to use `dynamic` attribute for basic type & must use as Non-Optional & must set initial value + dynamic var isSpecialAgent: Bool = false + dynamic var age: Int = 0 + + var name: String? + var identifier: String? +} +``` + +1. `@objc` or `@objcMembers` attributes should be added to class or property for declaration of Objc accessibility [在 Swift4 之后, 请在属性前加 `@objc` 修饰或在类前增加 `@objcMembers`. 以保证 Swift 的属性能够暴露给 Objc 使用. ] +2. If you let `Bool` & `Int` as property type, make sure that using `dynamic` to attribute it. It must be `Non-Optional` type and assign `a default value`.[如果要使用 `Bool` 和 `Int` 等 Swfit 专用基本类型, 请使用 `dynamic` 关键字修饰, 类型为 `Non-Optional`, 並且给定初始值.] + +> 纯Swift版的JSON与Model转换框架已经开源上架 +> +> - [KakaJSON](https://github.com/kakaopensource/KakaJSON) +> - [中文教程](https://www.cnblogs.com/mjios/p/11352776.html) +> - 如果你的项目是用Swift写的Model,墙裂推荐使用[KakaJSON](https://github.com/kakaopensource/KakaJSON) +> - 已经对各种常用的数据场景进行了大量的单元测试 +> - 简单易用、功能丰富、转换快速 + +### The most simple JSON -> Model【最简单的字典转模型】 + +```objc +typedef enum { + SexMale, + SexFemale +} Sex; + +@interface User : NSObject +@property (copy, nonatomic) NSString *name; +@property (copy, nonatomic) NSString *icon; +@property (assign, nonatomic) unsigned int age; +@property (copy, nonatomic) NSString *height; +@property (strong, nonatomic) NSNumber *money; +@property (assign, nonatomic) Sex sex; +@property (assign, nonatomic, getter=isGay) BOOL gay; +@end + +/***********************************************/ + +NSDictionary *dict = @{ + @"name" : @"Jack", + @"icon" : @"lufy.png", + @"age" : @20, + @"height" : @"1.55", + @"money" : @100.9, + @"sex" : @(SexFemale), + @"gay" : @"true" +// @"gay" : @"1" +// @"gay" : @"NO" +}; + +// JSON -> User +User *user = [User mj_objectWithKeyValues:dict]; + +NSLog(@"name=%@, icon=%@, age=%zd, height=%@, money=%@, sex=%d, gay=%d", user.name, user.icon, user.age, user.height, user.money, user.sex, user.gay); +// name=Jack, icon=lufy.png, age=20, height=1.550000, money=100.9, sex=1 +``` + +### JSONString -> Model【JSON字符串转模型】 + +```objc +// 1.Define a JSONString +NSString *jsonString = @"{\"name\":\"Jack\", \"icon\":\"lufy.png\", \"age\":20}"; + +// 2.JSONString -> User +User *user = [User mj_objectWithKeyValues:jsonString]; + +// 3.Print user's properties +NSLog(@"name=%@, icon=%@, age=%d", user.name, user.icon, user.age); +// name=Jack, icon=lufy.png, age=20 +``` + +### Model contains model【模型中嵌套模型】 + +```objc +@interface Status : NSObject +@property (copy, nonatomic) NSString *text; +@property (strong, nonatomic) User *user; +@property (strong, nonatomic) Status *retweetedStatus; +@end + +/***********************************************/ + +NSDictionary *dict = @{ + @"text" : @"Agree!Nice weather!", + @"user" : @{ + @"name" : @"Jack", + @"icon" : @"lufy.png" + }, + @"retweetedStatus" : @{ + @"text" : @"Nice weather!", + @"user" : @{ + @"name" : @"Rose", + @"icon" : @"nami.png" + } + } +}; + +// JSON -> Status +Status *status = [Status mj_objectWithKeyValues:dict]; + +NSString *text = status.text; +NSString *name = status.user.name; +NSString *icon = status.user.icon; +NSLog(@"text=%@, name=%@, icon=%@", text, name, icon); +// text=Agree!Nice weather!, name=Jack, icon=lufy.png + +NSString *text2 = status.retweetedStatus.text; +NSString *name2 = status.retweetedStatus.user.name; +NSString *icon2 = status.retweetedStatus.user.icon; +NSLog(@"text2=%@, name2=%@, icon2=%@", text2, name2, icon2); +// text2=Nice weather!, name2=Rose, icon2=nami.png +``` + +### Model contains model-array【模型中有个数组属性,数组里面又要装着其他模型】 + +```objc +@interface Ad : NSObject +@property (copy, nonatomic) NSString *image; +@property (copy, nonatomic) NSString *url; +@end + +@interface StatusResult : NSObject +/** Contatins status model */ +@property (strong, nonatomic) NSMutableArray *statuses; +/** Contatins ad model */ +@property (strong, nonatomic) NSArray *ads; +@property (strong, nonatomic) NSNumber *totalNumber; +@end + +/***********************************************/ + +// Tell MJExtension what type of model will be contained in statuses and ads. +[StatusResult mj_setupObjectClassInArray:^NSDictionary *{ + return @{ + @"statuses" : @"Status", + // @"statuses" : [Status class], + @"ads" : @"Ad" + // @"ads" : [Ad class] + }; +}]; +// Equals: StatusResult.m implements +mj_objectClassInArray method. + +NSDictionary *dict = @{ + @"statuses" : @[ + @{ + @"text" : @"Nice weather!", + @"user" : @{ + @"name" : @"Rose", + @"icon" : @"nami.png" + } + }, + @{ + @"text" : @"Go camping tomorrow!", + @"user" : @{ + @"name" : @"Jack", + @"icon" : @"lufy.png" + } + } + ], + @"ads" : @[ + @{ + @"image" : @"ad01.png", + @"url" : @"http://www.ad01.com" + }, + @{ + @"image" : @"ad02.png", + @"url" : @"http://www.ad02.com" + } + ], + @"totalNumber" : @"2014" +}; + +// JSON -> StatusResult +StatusResult *result = [StatusResult mj_objectWithKeyValues:dict]; + +NSLog(@"totalNumber=%@", result.totalNumber); +// totalNumber=2014 + +// Printing +for (Status *status in result.statuses) { + NSString *text = status.text; + NSString *name = status.user.name; + NSString *icon = status.user.icon; + NSLog(@"text=%@, name=%@, icon=%@", text, name, icon); +} +// text=Nice weather!, name=Rose, icon=nami.png +// text=Go camping tomorrow!, name=Jack, icon=lufy.png + +// Printing +for (Ad *ad in result.ads) { + NSLog(@"image=%@, url=%@", ad.image, ad.url); +} +// image=ad01.png, url=http://www.ad01.com +// image=ad02.png, url=http://www.ad02.com +``` + +### Model name - JSON key mapping【模型中的属性名和字典中的key不相同(或者需要多级映射)】 + +```objc +@interface Bag : NSObject +@property (copy, nonatomic) NSString *name; +@property (assign, nonatomic) double price; +@end + +@interface Student : NSObject +@property (copy, nonatomic) NSString *ID; +@property (copy, nonatomic) NSString *desc; +@property (copy, nonatomic) NSString *nowName; +@property (copy, nonatomic) NSString *oldName; +@property (copy, nonatomic) NSString *nameChangedTime; +@property (strong, nonatomic) Bag *bag; +@end + +/***********************************************/ + +// How to map +[Student mj_setupReplacedKeyFromPropertyName:^NSDictionary *{ + return @{ + @"ID" : @"id", + @"desc" : @"description", + @"oldName" : @"name.oldName", + @"nowName" : @"name.newName", + @"nameChangedTime" : @"name.info[1].nameChangedTime", + @"bag" : @"other.bag" + }; +}]; +// Equals: Student.m implements +mj_replacedKeyFromPropertyName method. + +NSDictionary *dict = @{ + @"id" : @"20", + @"description" : @"kids", + @"name" : @{ + @"newName" : @"lufy", + @"oldName" : @"kitty", + @"info" : @[ + @"test-data", + @{ + @"nameChangedTime" : @"2013-08" + } + ] + }, + @"other" : @{ + @"bag" : @{ + @"name" : @"a red bag", + @"price" : @100.7 + } + } +}; + +// JSON -> Student +Student *stu = [Student mj_objectWithKeyValues:dict]; + +// Printing +NSLog(@"ID=%@, desc=%@, oldName=%@, nowName=%@, nameChangedTime=%@", + stu.ID, stu.desc, stu.oldName, stu.nowName, stu.nameChangedTime); +// ID=20, desc=kids, oldName=kitty, nowName=lufy, nameChangedTime=2013-08 +NSLog(@"bagName=%@, bagPrice=%f", stu.bag.name, stu.bag.price); +// bagName=a red bag, bagPrice=100.700000 +``` + + +### JSON array -> model array【将一个字典数组转成模型数组】 + +```objc +NSArray *dictArray = @[ + @{ + @"name" : @"Jack", + @"icon" : @"lufy.png" + }, + @{ + @"name" : @"Rose", + @"icon" : @"nami.png" + } + ]; + +// JSON array -> User array +NSArray *userArray = [User mj_objectArrayWithKeyValuesArray:dictArray]; + +// Printing +for (User *user in userArray) { + NSLog(@"name=%@, icon=%@", user.name, user.icon); +} +// name=Jack, icon=lufy.png +// name=Rose, icon=nami.png +``` + +### Model -> JSON【将一个模型转成字典】 +```objc +// New model +User *user = [[User alloc] init]; +user.name = @"Jack"; +user.icon = @"lufy.png"; + +Status *status = [[Status alloc] init]; +status.user = user; +status.text = @"Nice mood!"; + +// Status -> JSON +NSDictionary *statusDict = status.mj_keyValues; +NSLog(@"%@", statusDict); +/* + { + text = "Nice mood!"; + user = { + icon = "lufy.png"; + name = Jack; + }; + } + */ + +// More complex situation +Student *stu = [[Student alloc] init]; +stu.ID = @"123"; +stu.oldName = @"rose"; +stu.nowName = @"jack"; +stu.desc = @"handsome"; +stu.nameChangedTime = @"2018-09-08"; + +Bag *bag = [[Bag alloc] init]; +bag.name = @"a red bag"; +bag.price = 205; +stu.bag = bag; + +NSDictionary *stuDict = stu.mj_keyValues; +NSLog(@"%@", stuDict); +/* +{ + ID = 123; + bag = { + name = "\U5c0f\U4e66\U5305"; + price = 205; + }; + desc = handsome; + nameChangedTime = "2018-09-08"; + nowName = jack; + oldName = rose; +} + */ +``` + +### Model array -> JSON array【将一个模型数组转成字典数组】 + +```objc +// New model array +User *user1 = [[User alloc] init]; +user1.name = @"Jack"; +user1.icon = @"lufy.png"; + +User *user2 = [[User alloc] init]; +user2.name = @"Rose"; +user2.icon = @"nami.png"; + +NSArray *userArray = @[user1, user2]; + +// Model array -> JSON array +NSArray *dictArray = [User mj_keyValuesArrayWithObjectArray:userArray]; +NSLog(@"%@", dictArray); +/* + ( + { + icon = "lufy.png"; + name = Jack; + }, + { + icon = "nami.png"; + name = Rose; + } + ) + */ +``` + +### Core Data + +```swift +func json2CoreDataObject() { + context.performAndWait { + let object = MJCoreDataTester.mj_object(withKeyValues: Values.testJSONObject, context: context) + // use the object + } +} + +func coreDataObject2JSON() { + context.performAndWait { + let dict = coreDataObject.mj_keyValues() + // use dict + } +} +``` + +### Coding (Archive & Unarchive methods are deprecated in iOS 12) + +```objc +#import "MJExtension.h" + +@implementation MJBag +// NSCoding Implementation +MJCodingImplementation +@end + +/***********************************************/ + +// what properties not to be coded +[MJBag mj_setupIgnoredCodingPropertyNames:^NSArray *{ + return @[@"name"]; +}]; +// Equals: MJBag.m implements +mj_ignoredCodingPropertyNames method. + +// Create model +MJBag *bag = [[MJBag alloc] init]; +bag.name = @"Red bag"; +bag.price = 200.8; + +NSString *file = [NSHomeDirectory() stringByAppendingPathComponent:@"Desktop/bag.data"]; +// Encoding by archiving +[NSKeyedArchiver archiveRootObject:bag toFile:file]; + +// Decoding by unarchiving +MJBag *decodedBag = [NSKeyedUnarchiver unarchiveObjectWithFile:file]; +NSLog(@"name=%@, price=%f", decodedBag.name, decodedBag.price); +// name=(null), price=200.800000 +``` + +### Secure Coding + +Using `MJSecureCodingImplementation(class, isSupport)` macro. + +```objc +@import MJExtension; + +// NSSecureCoding Implementation +MJSecureCodingImplementation(MJBag, YES) + +@implementation MJBag +@end + + /***********************************************/ + +// what properties not to be coded +[MJBag mj_setupIgnoredCodingPropertyNames:^NSArray *{ + return @[@"name"]; +}]; +// Equals: MJBag.m implements +mj_ignoredCodingPropertyNames method. + +// Create model +MJBag *bag = [[MJBag alloc] init]; +bag.name = @"Red bag"; +bag.price = 200.8; +bag.isBig = YES; +bag.weight = 200; + +NSString *file = [NSTemporaryDirectory() stringByAppendingPathComponent:@"bag.data"]; + +NSError *error = nil; +// Encoding by archiving +NSData *data = [NSKeyedArchiver archivedDataWithRootObject:bag requiringSecureCoding:YES error:&error]; +[data writeToFile:file atomically:true]; + +// Decoding by unarchiving +NSData *readData = [NSFileManager.defaultManager contentsAtPath:file]; +error = nil; +MJBag *decodedBag = [NSKeyedUnarchiver unarchivedObjectOfClass:MJBag.class fromData:readData error:&error]; +MJExtensionLog(@"name=%@, price=%f", decodedBag.name, decodedBag.price); +``` + +### Camel -> underline【统一转换属性名(比如驼峰转下划线)】 + +```objc +// Dog +#import "MJExtension.h" + +@implementation Dog ++ (NSString *)mj_replacedKeyFromPropertyName121:(NSString *)propertyName +{ + // nickName -> nick_name + return [propertyName mj_underlineFromCamel]; +} +@end + +// NSDictionary +NSDictionary *dict = @{ + @"nick_name" : @"旺财", + @"sale_price" : @"10.5", + @"run_speed" : @"100.9" + }; +// NSDictionary -> Dog +Dog *dog = [Dog mj_objectWithKeyValues:dict]; + +// printing +NSLog(@"nickName=%@, scalePrice=%f runSpeed=%f", dog.nickName, dog.salePrice, dog.runSpeed); +``` + +### NSString -> NSDate, nil -> @""【过滤字典的值(比如字符串日期处理为NSDate、字符串nil处理为@"")】 +```objc +// Book +#import "MJExtension.h" + +@implementation Book +- (id)mj_newValueFromOldValue:(id)oldValue property:(MJProperty *)property +{ + if ([property.name isEqualToString:@"publisher"]) { + if (oldValue == nil) return @""; + } else if (property.type.typeClass == [NSDate class]) { + NSDateFormatter *fmt = [[NSDateFormatter alloc] init]; + fmt.dateFormat = @"yyyy-MM-dd"; + return [fmt dateFromString:oldValue]; + } + + return oldValue; +} +@end + +// NSDictionary +NSDictionary *dict = @{ + @"name" : @"5分钟突破iOS开发", + @"publishedTime" : @"2011-09-10" + }; +// NSDictionary -> Book +Book *book = [Book mj_objectWithKeyValues:dict]; + +// printing +NSLog(@"name=%@, publisher=%@, publishedTime=%@", book.name, book.publisher, book.publishedTime); +``` + +### NSDate -> NSString【模型转字典时, 修改 Date 类型至 String】 + +```objc +- (void)mj_objectDidConvertToKeyValues:(NSMutableDictionary *)keyValues { + // NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; + // formatter.dateFormat = @"yyy-MM-dd"; + // should use sharedFormatter for better performance + keyValues[@"publishedTime"] = [sharedFormatter stringFromDate:self.publishedTime]; +} +``` + + + +### More use cases【更多用法】 + +- Please reference to `NSObject+MJKeyValue.h` and `NSObject+MJCoding.h` + + +## 期待 +* 如果在使用过程中遇到BUG,希望你能Issues我,谢谢(或者尝试下载最新的框架代码看看BUG修复没有) +* 如果在使用过程中发现功能不够用,希望你能Issues我,我非常想为这个框架增加更多好用的功能,谢谢 +* 如果你想为MJExtension输出代码,请拼命Pull Requests我 + diff --git a/Pods/MJRefresh/LICENSE b/Pods/MJRefresh/LICENSE new file mode 100644 index 0000000..11bf234 --- /dev/null +++ b/Pods/MJRefresh/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2013-2015 MJRefresh (https://github.com/CoderMJLee/MJRefresh) + +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. diff --git a/Pods/MJRefresh/MJRefresh/Base/MJRefreshAutoFooter.h b/Pods/MJRefresh/MJRefresh/Base/MJRefreshAutoFooter.h new file mode 100644 index 0000000..e4eb872 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Base/MJRefreshAutoFooter.h @@ -0,0 +1,34 @@ +// +// MJRefreshAutoFooter.h +// MJRefresh +// +// Created by MJ Lee on 15/4/24. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#if __has_include() +#import +#else +#import "MJRefreshFooter.h" +#endif + +NS_ASSUME_NONNULL_BEGIN + +@interface MJRefreshAutoFooter : MJRefreshFooter +/** 是否自动刷新(默认为YES) */ +@property (assign, nonatomic, getter=isAutomaticallyRefresh) BOOL automaticallyRefresh; + +/** 当底部控件出现多少时就自动刷新(默认为1.0,也就是底部控件完全出现时,才会自动刷新) */ +@property (assign, nonatomic) CGFloat appearencePercentTriggerAutoRefresh MJRefreshDeprecated("请使用triggerAutomaticallyRefreshPercent属性"); + +/** 当底部控件出现多少时就自动刷新(默认为1.0,也就是底部控件完全出现时,才会自动刷新) */ +@property (assign, nonatomic) CGFloat triggerAutomaticallyRefreshPercent; + +/** 自动触发次数, 默认为 1, 仅在拖拽 ScrollView 时才生效, + + 如果为 -1, 则为无限触发 + */ +@property (nonatomic) NSInteger autoTriggerTimes; +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/MJRefresh/MJRefresh/Base/MJRefreshAutoFooter.m b/Pods/MJRefresh/MJRefresh/Base/MJRefreshAutoFooter.m new file mode 100644 index 0000000..66616e1 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Base/MJRefreshAutoFooter.m @@ -0,0 +1,216 @@ +// +// MJRefreshAutoFooter.m +// MJRefresh +// +// Created by MJ Lee on 15/4/24. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "MJRefreshAutoFooter.h" +#import "NSBundle+MJRefresh.h" +#import "UIView+MJExtension.h" +#import "UIScrollView+MJExtension.h" +#import "UIScrollView+MJRefresh.h" + +@interface MJRefreshAutoFooter() +/** 一个新的拖拽 */ +@property (nonatomic) BOOL triggerByDrag; +@property (nonatomic) NSInteger leftTriggerTimes; +@end + +@implementation MJRefreshAutoFooter + +#pragma mark - 初始化 +- (void)willMoveToSuperview:(UIView *)newSuperview +{ + [super willMoveToSuperview:newSuperview]; + + if (newSuperview) { // 新的父控件 + if (self.hidden == NO) { + self.scrollView.mj_insetB += self.mj_h; + } + + // 设置位置 + self.mj_y = _scrollView.mj_contentH + self.ignoredScrollViewContentInsetBottom; + } else { // 被移除了 + if (self.hidden == NO) { + self.scrollView.mj_insetB -= self.mj_h; + } + } +} + +#pragma mark - 过期方法 +- (void)setAppearencePercentTriggerAutoRefresh:(CGFloat)appearencePercentTriggerAutoRefresh +{ + self.triggerAutomaticallyRefreshPercent = appearencePercentTriggerAutoRefresh; +} + +- (CGFloat)appearencePercentTriggerAutoRefresh +{ + return self.triggerAutomaticallyRefreshPercent; +} + +#pragma mark - 实现父类的方法 +- (void)prepare +{ + [super prepare]; + + // 默认底部控件100%出现时才会自动刷新 + self.triggerAutomaticallyRefreshPercent = 1.0; + + // 设置为默认状态 + self.automaticallyRefresh = YES; + + self.autoTriggerTimes = 1; +} + +- (void)scrollViewContentSizeDidChange:(NSDictionary *)change +{ + [super scrollViewContentSizeDidChange:change]; + + CGSize size = [change[NSKeyValueChangeNewKey] CGSizeValue]; + CGFloat contentHeight = size.height == 0 ? self.scrollView.mj_contentH : size.height; + // 设置位置 + CGFloat y = contentHeight + self.ignoredScrollViewContentInsetBottom; + if (self.mj_y != y) { + self.mj_y = y; + } +} + +- (void)scrollViewContentOffsetDidChange:(NSDictionary *)change +{ + [super scrollViewContentOffsetDidChange:change]; + + if (self.state != MJRefreshStateIdle || !self.automaticallyRefresh || self.mj_y == 0) return; + + if (_scrollView.mj_insetT + _scrollView.mj_contentH > _scrollView.mj_h) { // 内容超过一个屏幕 + // 这里的_scrollView.mj_contentH替换掉self.mj_y更为合理 + if (_scrollView.mj_offsetY >= _scrollView.mj_contentH - _scrollView.mj_h + self.mj_h * self.triggerAutomaticallyRefreshPercent + _scrollView.mj_insetB - self.mj_h) { + // 防止手松开时连续调用 + CGPoint old = [change[@"old"] CGPointValue]; + CGPoint new = [change[@"new"] CGPointValue]; + if (new.y <= old.y) return; + + if (_scrollView.isDragging) { + self.triggerByDrag = YES; + } + // 当底部刷新控件完全出现时,才刷新 + [self beginRefreshing]; + } + } +} + +- (void)scrollViewPanStateDidChange:(NSDictionary *)change +{ + [super scrollViewPanStateDidChange:change]; + + if (self.state != MJRefreshStateIdle) return; + + UIGestureRecognizerState panState = _scrollView.panGestureRecognizer.state; + + switch (panState) { + // 手松开 + case UIGestureRecognizerStateEnded: { + if (_scrollView.mj_insetT + _scrollView.mj_contentH <= _scrollView.mj_h) { // 不够一个屏幕 + if (_scrollView.mj_offsetY >= - _scrollView.mj_insetT) { // 向上拽 + self.triggerByDrag = YES; + [self beginRefreshing]; + } + } else { // 超出一个屏幕 + if (_scrollView.mj_offsetY >= _scrollView.mj_contentH + _scrollView.mj_insetB - _scrollView.mj_h) { + self.triggerByDrag = YES; + [self beginRefreshing]; + } + } + } + break; + + case UIGestureRecognizerStateBegan: { + [self resetTriggerTimes]; + } + break; + + default: + break; + } +} + +- (BOOL)unlimitedTrigger { + return self.leftTriggerTimes == -1; +} + +- (void)beginRefreshing +{ + if (self.triggerByDrag && self.leftTriggerTimes <= 0 && !self.unlimitedTrigger) { + return; + } + + [super beginRefreshing]; +} + +- (void)setState:(MJRefreshState)state +{ + MJRefreshCheckState + + if (state == MJRefreshStateRefreshing) { + [self executeRefreshingCallback]; + } else if (state == MJRefreshStateNoMoreData || state == MJRefreshStateIdle) { + if (self.triggerByDrag) { + if (!self.unlimitedTrigger) { + self.leftTriggerTimes -= 1; + } + self.triggerByDrag = NO; + } + + if (MJRefreshStateRefreshing == oldState) { + if (self.scrollView.pagingEnabled) { + CGPoint offset = self.scrollView.contentOffset; + offset.y -= self.scrollView.mj_insetB; + [UIView animateWithDuration:self.slowAnimationDuration animations:^{ + self.scrollView.contentOffset = offset; + + if (self.endRefreshingAnimationBeginAction) { + self.endRefreshingAnimationBeginAction(); + } + } completion:^(BOOL finished) { + if (self.endRefreshingCompletionBlock) { + self.endRefreshingCompletionBlock(); + } + }]; + return; + } + + if (self.endRefreshingCompletionBlock) { + self.endRefreshingCompletionBlock(); + } + } + } +} + +- (void)resetTriggerTimes { + self.leftTriggerTimes = self.autoTriggerTimes; +} + +- (void)setHidden:(BOOL)hidden +{ + BOOL lastHidden = self.isHidden; + + [super setHidden:hidden]; + + if (!lastHidden && hidden) { + self.state = MJRefreshStateIdle; + + self.scrollView.mj_insetB -= self.mj_h; + } else if (lastHidden && !hidden) { + self.scrollView.mj_insetB += self.mj_h; + + // 设置位置 + self.mj_y = _scrollView.mj_contentH + self.ignoredScrollViewContentInsetBottom; + } +} + +- (void)setAutoTriggerTimes:(NSInteger)autoTriggerTimes { + _autoTriggerTimes = autoTriggerTimes; + self.leftTriggerTimes = autoTriggerTimes; +} +@end diff --git a/Pods/MJRefresh/MJRefresh/Base/MJRefreshBackFooter.h b/Pods/MJRefresh/MJRefresh/Base/MJRefreshBackFooter.h new file mode 100644 index 0000000..8484372 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Base/MJRefreshBackFooter.h @@ -0,0 +1,21 @@ +// +// MJRefreshBackFooter.h +// MJRefresh +// +// Created by MJ Lee on 15/4/24. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#if __has_include() +#import +#else +#import "MJRefreshFooter.h" +#endif + +NS_ASSUME_NONNULL_BEGIN + +@interface MJRefreshBackFooter : MJRefreshFooter + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/MJRefresh/MJRefresh/Base/MJRefreshBackFooter.m b/Pods/MJRefresh/MJRefresh/Base/MJRefreshBackFooter.m new file mode 100644 index 0000000..4990ca5 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Base/MJRefreshBackFooter.m @@ -0,0 +1,158 @@ +// +// MJRefreshBackFooter.m +// MJRefresh +// +// Created by MJ Lee on 15/4/24. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "MJRefreshBackFooter.h" +#import "NSBundle+MJRefresh.h" +#import "UIView+MJExtension.h" +#import "UIScrollView+MJExtension.h" +#import "UIScrollView+MJRefresh.h" + +@interface MJRefreshBackFooter() +@property (assign, nonatomic) NSInteger lastRefreshCount; +@property (assign, nonatomic) CGFloat lastBottomDelta; +@end + +@implementation MJRefreshBackFooter + +#pragma mark - 初始化 +- (void)willMoveToSuperview:(UIView *)newSuperview +{ + [super willMoveToSuperview:newSuperview]; + + [self scrollViewContentSizeDidChange:nil]; +} + +#pragma mark - 实现父类的方法 +- (void)scrollViewContentOffsetDidChange:(NSDictionary *)change +{ + [super scrollViewContentOffsetDidChange:change]; + + // 如果正在刷新,直接返回 + if (self.state == MJRefreshStateRefreshing) return; + + _scrollViewOriginalInset = self.scrollView.mj_inset; + + // 当前的contentOffset + CGFloat currentOffsetY = self.scrollView.mj_offsetY; + // 尾部控件刚好出现的offsetY + CGFloat happenOffsetY = [self happenOffsetY]; + // 如果是向下滚动到看不见尾部控件,直接返回 + if (currentOffsetY <= happenOffsetY) return; + + CGFloat pullingPercent = (currentOffsetY - happenOffsetY) / self.mj_h; + + // 如果已全部加载,仅设置pullingPercent,然后返回 + if (self.state == MJRefreshStateNoMoreData) { + self.pullingPercent = pullingPercent; + return; + } + + if (self.scrollView.isDragging) { + self.pullingPercent = pullingPercent; + // 普通 和 即将刷新 的临界点 + CGFloat normal2pullingOffsetY = happenOffsetY + self.mj_h; + + if (self.state == MJRefreshStateIdle && currentOffsetY > normal2pullingOffsetY) { + // 转为即将刷新状态 + self.state = MJRefreshStatePulling; + } else if (self.state == MJRefreshStatePulling && currentOffsetY <= normal2pullingOffsetY) { + // 转为普通状态 + self.state = MJRefreshStateIdle; + } + } else if (self.state == MJRefreshStatePulling) {// 即将刷新 && 手松开 + // 开始刷新 + [self beginRefreshing]; + } else if (pullingPercent < 1) { + self.pullingPercent = pullingPercent; + } +} + +- (void)scrollViewContentSizeDidChange:(NSDictionary *)change +{ + [super scrollViewContentSizeDidChange:change]; + + CGSize size = [change[NSKeyValueChangeNewKey] CGSizeValue]; + CGFloat contentHeight = size.height == 0 ? self.scrollView.mj_contentH : size.height; + // 内容的高度 + contentHeight += self.ignoredScrollViewContentInsetBottom; + // 表格的高度 + CGFloat scrollHeight = self.scrollView.mj_h - self.scrollViewOriginalInset.top - self.scrollViewOriginalInset.bottom + self.ignoredScrollViewContentInsetBottom; + // 设置位置 + CGFloat y = MAX(contentHeight, scrollHeight); + if (self.mj_y != y) { + self.mj_y = y; + } +} + +- (void)setState:(MJRefreshState)state +{ + MJRefreshCheckState + + // 根据状态来设置属性 + if (state == MJRefreshStateNoMoreData || state == MJRefreshStateIdle) { + // 刷新完毕 + if (MJRefreshStateRefreshing == oldState) { + [UIView animateWithDuration:self.slowAnimationDuration animations:^{ + if (self.endRefreshingAnimationBeginAction) { + self.endRefreshingAnimationBeginAction(); + } + + self.scrollView.mj_insetB -= self.lastBottomDelta; + // 自动调整透明度 + if (self.isAutomaticallyChangeAlpha) self.alpha = 0.0; + } completion:^(BOOL finished) { + self.pullingPercent = 0.0; + + if (self.endRefreshingCompletionBlock) { + self.endRefreshingCompletionBlock(); + } + }]; + } + + CGFloat deltaH = [self heightForContentBreakView]; + // 刚刷新完毕 + if (MJRefreshStateRefreshing == oldState && deltaH > 0 && self.scrollView.mj_totalDataCount != self.lastRefreshCount) { + self.scrollView.mj_offsetY = self.scrollView.mj_offsetY; + } + } else if (state == MJRefreshStateRefreshing) { + // 记录刷新前的数量 + self.lastRefreshCount = self.scrollView.mj_totalDataCount; + + [UIView animateWithDuration:self.fastAnimationDuration animations:^{ + CGFloat bottom = self.mj_h + self.scrollViewOriginalInset.bottom; + CGFloat deltaH = [self heightForContentBreakView]; + if (deltaH < 0) { // 如果内容高度小于view的高度 + bottom -= deltaH; + } + self.lastBottomDelta = bottom - self.scrollView.mj_insetB; + self.scrollView.mj_insetB = bottom; + self.scrollView.mj_offsetY = [self happenOffsetY] + self.mj_h; + } completion:^(BOOL finished) { + [self executeRefreshingCallback]; + }]; + } +} +#pragma mark - 私有方法 +#pragma mark 获得scrollView的内容 超出 view 的高度 +- (CGFloat)heightForContentBreakView +{ + CGFloat h = self.scrollView.frame.size.height - self.scrollViewOriginalInset.bottom - self.scrollViewOriginalInset.top; + return self.scrollView.contentSize.height - h; +} + +#pragma mark 刚好看到上拉刷新控件时的contentOffset.y +- (CGFloat)happenOffsetY +{ + CGFloat deltaH = [self heightForContentBreakView]; + if (deltaH > 0) { + return deltaH - self.scrollViewOriginalInset.top; + } else { + return - self.scrollViewOriginalInset.top; + } +} +@end diff --git a/Pods/MJRefresh/MJRefresh/Base/MJRefreshComponent.h b/Pods/MJRefresh/MJRefresh/Base/MJRefreshComponent.h new file mode 100644 index 0000000..f098101 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Base/MJRefreshComponent.h @@ -0,0 +1,151 @@ +// 代码地址: https://github.com/CoderMJLee/MJRefresh +// MJRefreshComponent.h +// MJRefresh +// +// Created by MJ Lee on 15/3/4. +// Copyright (c) 2015年 小码哥. All rights reserved. +// 刷新控件的基类 + +#import +#if __has_include() +#import +#else +#import "MJRefreshConst.h" +#endif + +NS_ASSUME_NONNULL_BEGIN + +/** 刷新控件的状态 */ +typedef NS_ENUM(NSInteger, MJRefreshState) { + /** 普通闲置状态 */ + MJRefreshStateIdle = 1, + /** 松开就可以进行刷新的状态 */ + MJRefreshStatePulling, + /** 正在刷新中的状态 */ + MJRefreshStateRefreshing, + /** 即将刷新的状态 */ + MJRefreshStateWillRefresh, + /** 所有数据加载完毕,没有更多的数据了 */ + MJRefreshStateNoMoreData +}; + +/** 进入刷新状态的回调 */ +typedef void (^MJRefreshComponentRefreshingBlock)(void) MJRefreshDeprecated("first deprecated in 3.3.0 - Use `MJRefreshComponentAction` instead"); +/** 开始刷新后的回调(进入刷新状态后的回调) */ +typedef void (^MJRefreshComponentBeginRefreshingCompletionBlock)(void) MJRefreshDeprecated("first deprecated in 3.3.0 - Use `MJRefreshComponentAction` instead"); +/** 结束刷新后的回调 */ +typedef void (^MJRefreshComponentEndRefreshingCompletionBlock)(void) MJRefreshDeprecated("first deprecated in 3.3.0 - Use `MJRefreshComponentAction` instead"); + +/** 刷新用到的回调类型 */ +typedef void (^MJRefreshComponentAction)(void); + +/** 刷新控件的基类 */ +@interface MJRefreshComponent : UIView +{ + /** 记录scrollView刚开始的inset */ + UIEdgeInsets _scrollViewOriginalInset; + /** 父控件 */ + __weak UIScrollView *_scrollView; +} + +#pragma mark - 刷新动画时间控制 +/** 快速动画时间(一般用在刷新开始的回弹动画), 默认 0.25 */ +@property (nonatomic) NSTimeInterval fastAnimationDuration; +/** 慢速动画时间(一般用在刷新结束后的回弹动画), 默认 0.4*/ +@property (nonatomic) NSTimeInterval slowAnimationDuration; +/** 关闭全部默认动画效果, 可以简单粗暴地解决 CollectionView 的回弹动画 bug */ +- (instancetype)setAnimationDisabled; + +#pragma mark - 刷新回调 +/** 正在刷新的回调 */ +@property (copy, nonatomic, nullable) MJRefreshComponentAction refreshingBlock; +/** 设置回调对象和回调方法 */ +- (void)setRefreshingTarget:(id)target refreshingAction:(SEL)action; + +/** 回调对象 */ +@property (weak, nonatomic) id refreshingTarget; +/** 回调方法 */ +@property (assign, nonatomic) SEL refreshingAction; +/** 触发回调(交给子类去调用) */ +- (void)executeRefreshingCallback; + +#pragma mark - 刷新状态控制 +/** 进入刷新状态 */ +- (void)beginRefreshing; +- (void)beginRefreshingWithCompletionBlock:(void (^)(void))completionBlock; +/** 开始刷新后的回调(进入刷新状态后的回调) */ +@property (copy, nonatomic, nullable) MJRefreshComponentAction beginRefreshingCompletionBlock; +/** 带动画的结束刷新的回调 */ +@property (copy, nonatomic, nullable) MJRefreshComponentAction endRefreshingAnimateCompletionBlock MJRefreshDeprecated("first deprecated in 3.3.0 - Use `endRefreshingAnimationBeginAction` instead"); +@property (copy, nonatomic, nullable) MJRefreshComponentAction endRefreshingAnimationBeginAction; +/** 结束刷新的回调 */ +@property (copy, nonatomic, nullable) MJRefreshComponentAction endRefreshingCompletionBlock; +/** 结束刷新状态 */ +- (void)endRefreshing; +- (void)endRefreshingWithCompletionBlock:(void (^)(void))completionBlock; +/** 是否正在刷新 */ +@property (assign, nonatomic, readonly, getter=isRefreshing) BOOL refreshing; + +/** 刷新状态 一般交给子类内部实现 */ +@property (assign, nonatomic) MJRefreshState state; + +#pragma mark - 交给子类去访问 +/** 记录scrollView刚开始的inset */ +@property (assign, nonatomic, readonly) UIEdgeInsets scrollViewOriginalInset; +/** 父控件 */ +@property (weak, nonatomic, readonly) UIScrollView *scrollView; + +#pragma mark - 交给子类们去实现 +/** 初始化 */ +- (void)prepare NS_REQUIRES_SUPER; +/** 摆放子控件frame */ +- (void)placeSubviews NS_REQUIRES_SUPER; +/** 当scrollView的contentOffset发生改变的时候调用 */ +- (void)scrollViewContentOffsetDidChange:(nullable NSDictionary *)change NS_REQUIRES_SUPER; +/** 当scrollView的contentSize发生改变的时候调用 */ +- (void)scrollViewContentSizeDidChange:(nullable NSDictionary *)change NS_REQUIRES_SUPER; +/** 当scrollView的拖拽状态发生改变的时候调用 */ +- (void)scrollViewPanStateDidChange:(nullable NSDictionary *)change NS_REQUIRES_SUPER; + +/** 多语言配置 language 发生变化时调用 + + `MJRefreshConfig.defaultConfig.language` 发生改变时调用. + + ⚠️ 父类会调用 `placeSubviews` 方法, 请勿在 placeSubviews 中调用本方法, 造成死循环. 子类在需要重新布局时, 在配置完修改后, 最后再调用 super 方法, 否则可能导致配置修改后, 定位先于修改执行. + */ +- (void)i18nDidChange NS_REQUIRES_SUPER; + +#pragma mark - 其他 +/** 拉拽的百分比(交给子类重写) */ +@property (assign, nonatomic) CGFloat pullingPercent; +/** 根据拖拽比例自动切换透明度 */ +@property (assign, nonatomic, getter=isAutoChangeAlpha) BOOL autoChangeAlpha MJRefreshDeprecated("请使用automaticallyChangeAlpha属性"); +/** 根据拖拽比例自动切换透明度 */ +@property (assign, nonatomic, getter=isAutomaticallyChangeAlpha) BOOL automaticallyChangeAlpha; +@end + +@interface UILabel(MJRefresh) ++ (instancetype)mj_label; +- (CGFloat)mj_textWidth; +@end + +@interface MJRefreshComponent (ChainingGrammar) + +#pragma mark - <<< 为 Swift 扩展链式语法 >>> - +/// 自动变化透明度 +- (instancetype)autoChangeTransparency:(BOOL)isAutoChange; +/// 刷新开始后立即调用的回调 +- (instancetype)afterBeginningAction:(MJRefreshComponentAction)action; +/// 刷新动画开始后立即调用的回调 +- (instancetype)endingAnimationBeginningAction:(MJRefreshComponentAction)action; +/// 刷新结束后立即调用的回调 +- (instancetype)afterEndingAction:(MJRefreshComponentAction)action; + + +/// 需要子类必须实现 +/// @param scrollView 赋值给的 ScrollView 的 Header/Footer/Trailer +- (instancetype)linkTo:(UIScrollView *)scrollView; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/MJRefresh/MJRefresh/Base/MJRefreshComponent.m b/Pods/MJRefresh/MJRefresh/Base/MJRefreshComponent.m new file mode 100644 index 0000000..785df18 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Base/MJRefreshComponent.m @@ -0,0 +1,323 @@ +// 代码地址: https://github.com/CoderMJLee/MJRefresh +// MJRefreshComponent.m +// MJRefresh +// +// Created by MJ Lee on 15/3/4. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "MJRefreshComponent.h" +#import "MJRefreshConst.h" +#import "MJRefreshConfig.h" +#import "UIView+MJExtension.h" +#import "UIScrollView+MJExtension.h" +#import "UIScrollView+MJRefresh.h" +#import "NSBundle+MJRefresh.h" + +@interface MJRefreshComponent() +@property (strong, nonatomic) UIPanGestureRecognizer *pan; +@end + +@implementation MJRefreshComponent +#pragma mark - 初始化 +- (instancetype)initWithFrame:(CGRect)frame +{ + if (self = [super initWithFrame:frame]) { + // 准备工作 + [self prepare]; + + // 默认是普通状态 + self.state = MJRefreshStateIdle; + self.fastAnimationDuration = 0.25; + self.slowAnimationDuration = 0.4; + } + return self; +} + +- (void)prepare +{ + // 基本属性 + self.autoresizingMask = UIViewAutoresizingFlexibleWidth; + self.backgroundColor = [UIColor clearColor]; +} + +- (void)layoutSubviews +{ + [self placeSubviews]; + + [super layoutSubviews]; +} + +- (void)placeSubviews{} + +- (void)willMoveToSuperview:(UIView *)newSuperview +{ + [super willMoveToSuperview:newSuperview]; + + // 如果不是UIScrollView,不做任何事情 + if (newSuperview && ![newSuperview isKindOfClass:[UIScrollView class]]) return; + + // 旧的父控件移除监听 + [self removeObservers]; + + if (newSuperview) { // 新的父控件 + // 记录UIScrollView + _scrollView = (UIScrollView *)newSuperview; + + // 设置宽度 + self.mj_w = _scrollView.mj_w; + // 设置位置 + self.mj_x = -_scrollView.mj_insetL; + + // 设置永远支持垂直弹簧效果 + _scrollView.alwaysBounceVertical = YES; + // 记录UIScrollView最开始的contentInset + _scrollViewOriginalInset = _scrollView.mj_inset; + + // 添加监听 + [self addObservers]; + } +} + +- (void)drawRect:(CGRect)rect +{ + [super drawRect:rect]; + + if (self.state == MJRefreshStateWillRefresh) { + // 预防view还没显示出来就调用了beginRefreshing + self.state = MJRefreshStateRefreshing; + } +} + +#pragma mark - KVO监听 +- (void)addObservers +{ + NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld; + [self.scrollView addObserver:self forKeyPath:MJRefreshKeyPathContentOffset options:options context:nil]; + [self.scrollView addObserver:self forKeyPath:MJRefreshKeyPathContentSize options:options context:nil]; + self.pan = self.scrollView.panGestureRecognizer; + [self.pan addObserver:self forKeyPath:MJRefreshKeyPathPanState options:options context:nil]; + + [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(i18nDidChange) name:MJRefreshDidChangeLanguageNotification object:MJRefreshConfig.defaultConfig]; +} + +- (void)removeObservers +{ + [self.superview removeObserver:self forKeyPath:MJRefreshKeyPathContentOffset]; + [self.superview removeObserver:self forKeyPath:MJRefreshKeyPathContentSize]; + [self.pan removeObserver:self forKeyPath:MJRefreshKeyPathPanState]; + self.pan = nil; +} + +- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context +{ + // 遇到这些情况就直接返回 + if (!self.userInteractionEnabled) return; + + // 这个就算看不见也需要处理 + if ([keyPath isEqualToString:MJRefreshKeyPathContentSize]) { + [self scrollViewContentSizeDidChange:change]; + } + + // 看不见 + if (self.hidden) return; + if ([keyPath isEqualToString:MJRefreshKeyPathContentOffset]) { + [self scrollViewContentOffsetDidChange:change]; + } else if ([keyPath isEqualToString:MJRefreshKeyPathPanState]) { + [self scrollViewPanStateDidChange:change]; + } +} + +- (void)scrollViewContentOffsetDidChange:(NSDictionary *)change{} +- (void)scrollViewContentSizeDidChange:(NSDictionary *)change{} +- (void)scrollViewPanStateDidChange:(NSDictionary *)change{} + +- (void)i18nDidChange { + [self placeSubviews]; +} + +#pragma mark - 公共方法 +#pragma mark 设置回调对象和回调方法 +- (void)setRefreshingTarget:(id)target refreshingAction:(SEL)action +{ + self.refreshingTarget = target; + self.refreshingAction = action; +} + +- (void)setState:(MJRefreshState)state +{ + _state = state; + + // 加入主队列的目的是等setState:方法调用完毕、设置完文字后再去布局子控件 + MJRefreshDispatchAsyncOnMainQueue([self setNeedsLayout];) +} + +#pragma mark 进入刷新状态 +- (void)beginRefreshing +{ + [UIView animateWithDuration:self.fastAnimationDuration animations:^{ + self.alpha = 1.0; + }]; + self.pullingPercent = 1.0; + // 只要正在刷新,就完全显示 + if (self.window) { + self.state = MJRefreshStateRefreshing; + } else { + // 预防正在刷新中时,调用本方法使得header inset回置失败 + if (self.state != MJRefreshStateRefreshing) { + self.state = MJRefreshStateWillRefresh; + // 刷新(预防从另一个控制器回到这个控制器的情况,回来要重新刷新一下) + [self setNeedsDisplay]; + } + } +} + +- (void)beginRefreshingWithCompletionBlock:(void (^)(void))completionBlock +{ + self.beginRefreshingCompletionBlock = completionBlock; + + [self beginRefreshing]; +} + +#pragma mark 结束刷新状态 +- (void)endRefreshing +{ + MJRefreshDispatchAsyncOnMainQueue(self.state = MJRefreshStateIdle;) +} + +- (void)endRefreshingWithCompletionBlock:(void (^)(void))completionBlock +{ + self.endRefreshingCompletionBlock = completionBlock; + + [self endRefreshing]; +} + +#pragma mark 是否正在刷新 +- (BOOL)isRefreshing +{ + return self.state == MJRefreshStateRefreshing || self.state == MJRefreshStateWillRefresh; +} + +#pragma mark 自动切换透明度 +- (void)setAutoChangeAlpha:(BOOL)autoChangeAlpha +{ + self.automaticallyChangeAlpha = autoChangeAlpha; +} + +- (BOOL)isAutoChangeAlpha +{ + return self.isAutomaticallyChangeAlpha; +} + +- (void)setAutomaticallyChangeAlpha:(BOOL)automaticallyChangeAlpha +{ + _automaticallyChangeAlpha = automaticallyChangeAlpha; + + if (self.isRefreshing) return; + + if (automaticallyChangeAlpha) { + self.alpha = self.pullingPercent; + } else { + self.alpha = 1.0; + } +} + +#pragma mark 根据拖拽进度设置透明度 +- (void)setPullingPercent:(CGFloat)pullingPercent +{ + _pullingPercent = pullingPercent; + + if (self.isRefreshing) return; + + if (self.isAutomaticallyChangeAlpha) { + self.alpha = pullingPercent; + } +} + +#pragma mark - 内部方法 +- (void)executeRefreshingCallback +{ + if (self.refreshingBlock) { + self.refreshingBlock(); + } + if ([self.refreshingTarget respondsToSelector:self.refreshingAction]) { + MJRefreshMsgSend(MJRefreshMsgTarget(self.refreshingTarget), self.refreshingAction, self); + } + if (self.beginRefreshingCompletionBlock) { + self.beginRefreshingCompletionBlock(); + } +} + +#pragma mark - 刷新动画时间控制 +- (instancetype)setAnimationDisabled { + self.fastAnimationDuration = 0; + self.slowAnimationDuration = 0; + + return self; +} + +#pragma mark - <<< Deprecation compatible function >>> - +- (void)setEndRefreshingAnimateCompletionBlock:(MJRefreshComponentEndRefreshingCompletionBlock)endRefreshingAnimateCompletionBlock { + _endRefreshingAnimationBeginAction = endRefreshingAnimateCompletionBlock; +} +@end + +@implementation UILabel(MJRefresh) ++ (instancetype)mj_label +{ + UILabel *label = [[self alloc] init]; + label.font = MJRefreshLabelFont; + label.textColor = MJRefreshLabelTextColor; + label.autoresizingMask = UIViewAutoresizingFlexibleWidth; + label.textAlignment = NSTextAlignmentCenter; + label.backgroundColor = [UIColor clearColor]; + return label; +} + +- (CGFloat)mj_textWidth { + CGFloat stringWidth = 0; + CGSize size = CGSizeMake(MAXFLOAT, MAXFLOAT); + + if (self.attributedText) { + if (self.attributedText.length == 0) { return 0; } + stringWidth = [self.attributedText boundingRectWithSize:size + options:NSStringDrawingUsesLineFragmentOrigin + context:nil].size.width; + } else { + if (self.text.length == 0) { return 0; } + NSAssert(self.font != nil, @"请检查 mj_label's `font` 是否设置正确"); + stringWidth = [self.text boundingRectWithSize:size + options:NSStringDrawingUsesLineFragmentOrigin + attributes:@{NSFontAttributeName:self.font} + context:nil].size.width; + } + return stringWidth; +} +@end + + +#pragma mark - <<< 为 Swift 扩展链式语法 >>> - +@implementation MJRefreshComponent (ChainingGrammar) + +- (instancetype)autoChangeTransparency:(BOOL)isAutoChange { + self.automaticallyChangeAlpha = isAutoChange; + return self; +} +- (instancetype)afterBeginningAction:(MJRefreshComponentAction)action { + self.beginRefreshingCompletionBlock = action; + return self; +} +- (instancetype)endingAnimationBeginningAction:(MJRefreshComponentAction)action { + self.endRefreshingAnimationBeginAction = action; + return self; +} +- (instancetype)afterEndingAction:(MJRefreshComponentAction)action { + self.endRefreshingCompletionBlock = action; + return self; +} + +- (instancetype)linkTo:(UIScrollView *)scrollView { + return self; +} + +@end diff --git a/Pods/MJRefresh/MJRefresh/Base/MJRefreshFooter.h b/Pods/MJRefresh/MJRefresh/Base/MJRefreshFooter.h new file mode 100644 index 0000000..7b7c7b6 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Base/MJRefreshFooter.h @@ -0,0 +1,37 @@ +// 代码地址: https://github.com/CoderMJLee/MJRefresh +// MJRefreshFooter.h +// MJRefresh +// +// Created by MJ Lee on 15/3/5. +// Copyright (c) 2015年 小码哥. All rights reserved. +// 上拉刷新控件 + +#if __has_include() +#import +#else +#import "MJRefreshComponent.h" +#endif + +NS_ASSUME_NONNULL_BEGIN + +@interface MJRefreshFooter : MJRefreshComponent +/** 创建footer */ ++ (instancetype)footerWithRefreshingBlock:(MJRefreshComponentAction)refreshingBlock; +/** 创建footer */ ++ (instancetype)footerWithRefreshingTarget:(id)target refreshingAction:(SEL)action; + +/** 提示没有更多的数据 */ +- (void)endRefreshingWithNoMoreData; +- (void)noticeNoMoreData MJRefreshDeprecated("使用endRefreshingWithNoMoreData"); + +/** 重置没有更多的数据(消除没有更多数据的状态) */ +- (void)resetNoMoreData; + +/** 忽略多少scrollView的contentInset的bottom */ +@property (assign, nonatomic) CGFloat ignoredScrollViewContentInsetBottom; + +/** 自动根据有无数据来显示和隐藏(有数据就显示,没有数据隐藏。默认是NO) */ +@property (assign, nonatomic, getter=isAutomaticallyHidden) BOOL automaticallyHidden MJRefreshDeprecated("已废弃此属性,开发者请自行控制footer的显示和隐藏"); +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/MJRefresh/MJRefresh/Base/MJRefreshFooter.m b/Pods/MJRefresh/MJRefresh/Base/MJRefreshFooter.m new file mode 100644 index 0000000..8096fdb --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Base/MJRefreshFooter.m @@ -0,0 +1,71 @@ +// 代码地址: https://github.com/CoderMJLee/MJRefresh +// MJRefreshFooter.m +// MJRefresh +// +// Created by MJ Lee on 15/3/5. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "MJRefreshFooter.h" +#import "UIScrollView+MJRefresh.h" +#import "UIView+MJExtension.h" + +@interface MJRefreshFooter() + +@end + +@implementation MJRefreshFooter +#pragma mark - 构造方法 ++ (instancetype)footerWithRefreshingBlock:(MJRefreshComponentAction)refreshingBlock +{ + MJRefreshFooter *cmp = [[self alloc] init]; + cmp.refreshingBlock = refreshingBlock; + return cmp; +} ++ (instancetype)footerWithRefreshingTarget:(id)target refreshingAction:(SEL)action +{ + MJRefreshFooter *cmp = [[self alloc] init]; + [cmp setRefreshingTarget:target refreshingAction:action]; + return cmp; +} + +#pragma mark - 重写父类的方法 +- (void)prepare +{ + [super prepare]; + + // 设置自己的高度 + self.mj_h = MJRefreshFooterHeight; + + // 默认不会自动隐藏 +// self.automaticallyHidden = NO; +} + +#pragma mark . 链式语法部分 . + +- (instancetype)linkTo:(UIScrollView *)scrollView { + scrollView.mj_footer = self; + return self; +} + +#pragma mark - 公共方法 +- (void)endRefreshingWithNoMoreData +{ + MJRefreshDispatchAsyncOnMainQueue(self.state = MJRefreshStateNoMoreData;) +} + +- (void)noticeNoMoreData +{ + [self endRefreshingWithNoMoreData]; +} + +- (void)resetNoMoreData +{ + MJRefreshDispatchAsyncOnMainQueue(self.state = MJRefreshStateIdle;) +} + +- (void)setAutomaticallyHidden:(BOOL)automaticallyHidden +{ + _automaticallyHidden = automaticallyHidden; +} +@end diff --git a/Pods/MJRefresh/MJRefresh/Base/MJRefreshHeader.h b/Pods/MJRefresh/MJRefresh/Base/MJRefreshHeader.h new file mode 100644 index 0000000..95d8cb2 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Base/MJRefreshHeader.h @@ -0,0 +1,35 @@ +// 代码地址: https://github.com/CoderMJLee/MJRefresh +// MJRefreshHeader.h +// MJRefresh +// +// Created by MJ Lee on 15/3/4. +// Copyright (c) 2015年 小码哥. All rights reserved. +// 下拉刷新控件:负责监控用户下拉的状态 + +#if __has_include() +#import +#else +#import "MJRefreshComponent.h" +#endif + +NS_ASSUME_NONNULL_BEGIN + +@interface MJRefreshHeader : MJRefreshComponent +/** 创建header */ ++ (instancetype)headerWithRefreshingBlock:(MJRefreshComponentAction)refreshingBlock; +/** 创建header */ ++ (instancetype)headerWithRefreshingTarget:(id)target refreshingAction:(SEL)action; + +/** 这个key用来存储上一次下拉刷新成功的时间 */ +@property (copy, nonatomic) NSString *lastUpdatedTimeKey; +/** 上一次下拉刷新成功的时间 */ +@property (strong, nonatomic, readonly, nullable) NSDate *lastUpdatedTime; + +/** 忽略多少scrollView的contentInset的top */ +@property (assign, nonatomic) CGFloat ignoredScrollViewContentInsetTop; + +/** 默认是关闭状态, 如果遇到 CollectionView 的动画异常问题可以尝试打开 */ +@property (nonatomic) BOOL isCollectionViewAnimationBug; +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/MJRefresh/MJRefresh/Base/MJRefreshHeader.m b/Pods/MJRefresh/MJRefresh/Base/MJRefreshHeader.m new file mode 100644 index 0000000..b276412 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Base/MJRefreshHeader.m @@ -0,0 +1,297 @@ +// 代码地址: https://github.com/CoderMJLee/MJRefresh +// MJRefreshHeader.m +// MJRefresh +// +// Created by MJ Lee on 15/3/4. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "MJRefreshHeader.h" +#import "UIView+MJExtension.h" +#import "UIScrollView+MJExtension.h" +#import "UIScrollView+MJRefresh.h" + +NSString * const MJRefreshHeaderRefreshing2IdleBoundsKey = @"MJRefreshHeaderRefreshing2IdleBounds"; +NSString * const MJRefreshHeaderRefreshingBoundsKey = @"MJRefreshHeaderRefreshingBounds"; + +@interface MJRefreshHeader() +@property (assign, nonatomic) CGFloat insetTDelta; +@end + +@implementation MJRefreshHeader +#pragma mark - 构造方法 ++ (instancetype)headerWithRefreshingBlock:(MJRefreshComponentAction)refreshingBlock +{ + MJRefreshHeader *cmp = [[self alloc] init]; + cmp.refreshingBlock = refreshingBlock; + return cmp; +} ++ (instancetype)headerWithRefreshingTarget:(id)target refreshingAction:(SEL)action +{ + MJRefreshHeader *cmp = [[self alloc] init]; + [cmp setRefreshingTarget:target refreshingAction:action]; + return cmp; +} + +#pragma mark - 覆盖父类的方法 +- (void)prepare +{ + [super prepare]; + + // 设置key + self.lastUpdatedTimeKey = MJRefreshHeaderLastUpdatedTimeKey; + + // 设置高度 + self.mj_h = MJRefreshHeaderHeight; +} + +- (void)placeSubviews +{ + [super placeSubviews]; + + // 设置y值(当自己的高度发生改变了,肯定要重新调整Y值,所以放到placeSubviews方法中设置y值) + self.mj_y = - self.mj_h - self.ignoredScrollViewContentInsetTop; +} + +- (void)resetInset { + if (@available(iOS 11.0, *)) { + } else { + // 如果 iOS 10 及以下系统在刷新时, push 新的 VC, 等待刷新完成后回来, 会导致顶部 Insets.top 异常, 不能 resetInset, 检查一下这种特殊情况 + if (!self.window) { return; } + } + + // sectionheader停留解决 + CGFloat insetT = - self.scrollView.mj_offsetY > _scrollViewOriginalInset.top ? - self.scrollView.mj_offsetY : _scrollViewOriginalInset.top; + insetT = insetT > self.mj_h + _scrollViewOriginalInset.top ? self.mj_h + _scrollViewOriginalInset.top : insetT; + self.insetTDelta = _scrollViewOriginalInset.top - insetT; + // 避免 CollectionView 在使用根据 Autolayout 和 内容自动伸缩 Cell, 刷新时导致的 Layout 异常渲染问题 + if (fabs(self.scrollView.mj_insetT - insetT) > FLT_EPSILON) { + self.scrollView.mj_insetT = insetT; + } +} + +- (void)scrollViewContentOffsetDidChange:(NSDictionary *)change +{ + [super scrollViewContentOffsetDidChange:change]; + + // 在刷新的refreshing状态 + if (self.state == MJRefreshStateRefreshing) { + [self resetInset]; + return; + } + + // 跳转到下一个控制器时,contentInset可能会变 + _scrollViewOriginalInset = self.scrollView.mj_inset; + + // 当前的contentOffset + CGFloat offsetY = self.scrollView.mj_offsetY; + // 头部控件刚好出现的offsetY + CGFloat happenOffsetY = - self.scrollViewOriginalInset.top; + + // 如果是向上滚动到看不见头部控件,直接返回 + // >= -> > + if (offsetY > happenOffsetY) return; + + // 普通 和 即将刷新 的临界点 + CGFloat normal2pullingOffsetY = happenOffsetY - self.mj_h; + CGFloat pullingPercent = (happenOffsetY - offsetY) / self.mj_h; + + if (self.scrollView.isDragging) { // 如果正在拖拽 + self.pullingPercent = pullingPercent; + if (self.state == MJRefreshStateIdle && offsetY < normal2pullingOffsetY) { + // 转为即将刷新状态 + self.state = MJRefreshStatePulling; + } else if (self.state == MJRefreshStatePulling && offsetY >= normal2pullingOffsetY) { + // 转为普通状态 + self.state = MJRefreshStateIdle; + } + } else if (self.state == MJRefreshStatePulling) {// 即将刷新 && 手松开 + // 开始刷新 + [self beginRefreshing]; + } else if (pullingPercent < 1) { + self.pullingPercent = pullingPercent; + } +} + +- (void)setState:(MJRefreshState)state +{ + MJRefreshCheckState + + // 根据状态做事情 + if (state == MJRefreshStateIdle) { + if (oldState != MJRefreshStateRefreshing) return; + + [self headerEndingAction]; + } else if (state == MJRefreshStateRefreshing) { + [self headerRefreshingAction]; + } +} + +- (void)headerEndingAction { + // 保存刷新时间 + [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:self.lastUpdatedTimeKey]; + [[NSUserDefaults standardUserDefaults] synchronize]; + + // 默认使用 UIViewAnimation 动画 + if (!self.isCollectionViewAnimationBug) { + // 恢复inset和offset + [UIView animateWithDuration:self.slowAnimationDuration animations:^{ + self.scrollView.mj_insetT += self.insetTDelta; + + if (self.endRefreshingAnimationBeginAction) { + self.endRefreshingAnimationBeginAction(); + } + // 自动调整透明度 + if (self.isAutomaticallyChangeAlpha) self.alpha = 0.0; + } completion:^(BOOL finished) { + self.pullingPercent = 0.0; + + if (self.endRefreshingCompletionBlock) { + self.endRefreshingCompletionBlock(); + } + }]; + + return; + } + + /** + 这个解决方法的思路出自 https://github.com/CoderMJLee/MJRefresh/pull/844 + 修改了用+ [UIView animateWithDuration: animations:]实现的修改contentInset的动画 + fix issue#225 https://github.com/CoderMJLee/MJRefresh/issues/225 + 另一种解法 pull#737 https://github.com/CoderMJLee/MJRefresh/pull/737 + + 同时, 处理了 Refreshing 中的动画替换. + */ + + // 由于修改 Inset 会导致 self.pullingPercent 联动设置 self.alpha, 故提前获取 alpha 值, 后续用于还原 alpha 动画 + CGFloat viewAlpha = self.alpha; + + self.scrollView.mj_insetT += self.insetTDelta; + // 禁用交互, 如果不禁用可能会引起渲染问题. + self.scrollView.userInteractionEnabled = NO; + + //CAAnimation keyPath 不支持 contentInset 用Bounds的动画代替 + CABasicAnimation *boundsAnimation = [CABasicAnimation animationWithKeyPath:@"bounds"]; + boundsAnimation.fromValue = [NSValue valueWithCGRect:CGRectOffset(self.scrollView.bounds, 0, self.insetTDelta)]; + boundsAnimation.duration = self.slowAnimationDuration; + //在delegate里移除 + boundsAnimation.removedOnCompletion = NO; + boundsAnimation.fillMode = kCAFillModeBoth; + boundsAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; + boundsAnimation.delegate = self; + [boundsAnimation setValue:MJRefreshHeaderRefreshing2IdleBoundsKey forKey:@"identity"]; + + [self.scrollView.layer addAnimation:boundsAnimation forKey:MJRefreshHeaderRefreshing2IdleBoundsKey]; + + if (self.endRefreshingAnimationBeginAction) { + self.endRefreshingAnimationBeginAction(); + } + // 自动调整透明度的动画 + if (self.isAutomaticallyChangeAlpha) { + CABasicAnimation *opacityAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"]; + opacityAnimation.fromValue = @(viewAlpha); + opacityAnimation.toValue = @(0.0); + opacityAnimation.duration = self.slowAnimationDuration; + opacityAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; + [self.layer addAnimation:opacityAnimation forKey:@"MJRefreshHeaderRefreshing2IdleOpacity"]; + + // 由于修改了 inset 导致, pullingPercent 被设置值, alpha 已经被提前修改为 0 了. 所以这里不用置 0, 但为了代码的严谨性, 不依赖其他的特殊实现方式, 这里还是置 0. + self.alpha = 0; + } +} + +- (void)headerRefreshingAction { + // 默认使用 UIViewAnimation 动画 + if (!self.isCollectionViewAnimationBug) { + [UIView animateWithDuration:self.fastAnimationDuration animations:^{ + if (self.scrollView.panGestureRecognizer.state != UIGestureRecognizerStateCancelled) { + CGFloat top = self.scrollViewOriginalInset.top + self.mj_h; + // 增加滚动区域top + self.scrollView.mj_insetT = top; + // 设置滚动位置 + CGPoint offset = self.scrollView.contentOffset; + offset.y = -top; + [self.scrollView setContentOffset:offset animated:NO]; + } + } completion:^(BOOL finished) { + [self executeRefreshingCallback]; + }]; + return; + } + + if (self.scrollView.panGestureRecognizer.state != UIGestureRecognizerStateCancelled) { + CGFloat top = self.scrollViewOriginalInset.top + self.mj_h; + // 禁用交互, 如果不禁用可能会引起渲染问题. + self.scrollView.userInteractionEnabled = NO; + + // CAAnimation keyPath不支持 contentOffset 用Bounds的动画代替 + CABasicAnimation *boundsAnimation = [CABasicAnimation animationWithKeyPath:@"bounds"]; + CGRect bounds = self.scrollView.bounds; + bounds.origin.y = -top; + boundsAnimation.fromValue = [NSValue valueWithCGRect:self.scrollView.bounds]; + boundsAnimation.toValue = [NSValue valueWithCGRect:bounds]; + boundsAnimation.duration = self.fastAnimationDuration; + //在delegate里移除 + boundsAnimation.removedOnCompletion = NO; + boundsAnimation.fillMode = kCAFillModeBoth; + boundsAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; + boundsAnimation.delegate = self; + [boundsAnimation setValue:MJRefreshHeaderRefreshingBoundsKey forKey:@"identity"]; + [self.scrollView.layer addAnimation:boundsAnimation forKey:MJRefreshHeaderRefreshingBoundsKey]; + } else { + [self executeRefreshingCallback]; + } +} + +#pragma mark . 链式语法部分 . + +- (instancetype)linkTo:(UIScrollView *)scrollView { + scrollView.mj_header = self; + return self; +} + +#pragma mark - CAAnimationDelegate +- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag { + NSString *identity = [anim valueForKey:@"identity"]; + if ([identity isEqualToString:MJRefreshHeaderRefreshing2IdleBoundsKey]) { + self.pullingPercent = 0.0; + self.scrollView.userInteractionEnabled = YES; + if (self.endRefreshingCompletionBlock) { + self.endRefreshingCompletionBlock(); + } + } else if ([identity isEqualToString:MJRefreshHeaderRefreshingBoundsKey]) { + // 避免出现 end 先于 Refreshing 状态 + if (self.state != MJRefreshStateIdle) { + CGFloat top = self.scrollViewOriginalInset.top + self.mj_h; + self.scrollView.mj_insetT = top; + // 设置最终滚动位置 + CGPoint offset = self.scrollView.contentOffset; + offset.y = -top; + [self.scrollView setContentOffset:offset animated:NO]; + } + self.scrollView.userInteractionEnabled = YES; + [self executeRefreshingCallback]; + } + + if ([self.scrollView.layer animationForKey:MJRefreshHeaderRefreshing2IdleBoundsKey]) { + [self.scrollView.layer removeAnimationForKey:MJRefreshHeaderRefreshing2IdleBoundsKey]; + } + + if ([self.scrollView.layer animationForKey:MJRefreshHeaderRefreshingBoundsKey]) { + [self.scrollView.layer removeAnimationForKey:MJRefreshHeaderRefreshingBoundsKey]; + } +} + +#pragma mark - 公共方法 +- (NSDate *)lastUpdatedTime +{ + return [[NSUserDefaults standardUserDefaults] objectForKey:self.lastUpdatedTimeKey]; +} + +- (void)setIgnoredScrollViewContentInsetTop:(CGFloat)ignoredScrollViewContentInsetTop { + _ignoredScrollViewContentInsetTop = ignoredScrollViewContentInsetTop; + + self.mj_y = - self.mj_h - _ignoredScrollViewContentInsetTop; +} + +@end diff --git a/Pods/MJRefresh/MJRefresh/Base/MJRefreshTrailer.h b/Pods/MJRefresh/MJRefresh/Base/MJRefreshTrailer.h new file mode 100644 index 0000000..ca4c7ea --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Base/MJRefreshTrailer.h @@ -0,0 +1,30 @@ +// +// MJRefreshTrailer.h +// MJRefresh +// +// Created by kinarobin on 2020/5/3. +// Copyright © 2020 小码哥. All rights reserved. +// + +#if __has_include() +#import +#else +#import "MJRefreshComponent.h" +#endif + +NS_ASSUME_NONNULL_BEGIN + +@interface MJRefreshTrailer : MJRefreshComponent + +/** 创建trailer*/ ++ (instancetype)trailerWithRefreshingBlock:(MJRefreshComponentAction)refreshingBlock; +/** 创建trailer */ ++ (instancetype)trailerWithRefreshingTarget:(id)target refreshingAction:(SEL)action; + +/** 忽略多少scrollView的contentInset的right */ +@property (assign, nonatomic) CGFloat ignoredScrollViewContentInsetRight; + + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/MJRefresh/MJRefresh/Base/MJRefreshTrailer.m b/Pods/MJRefresh/MJRefresh/Base/MJRefreshTrailer.m new file mode 100644 index 0000000..da66f20 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Base/MJRefreshTrailer.m @@ -0,0 +1,179 @@ +// +// MJRefreshTrailer.m +// MJRefresh +// +// Created by kinarobin on 2020/5/3. +// Copyright © 2020 小码哥. All rights reserved. +// + +#import "MJRefreshTrailer.h" +#import "UIView+MJExtension.h" +#import "UIScrollView+MJRefresh.h" +#import "UIScrollView+MJExtension.h" + +@interface MJRefreshTrailer() +@property (assign, nonatomic) NSInteger lastRefreshCount; +@property (assign, nonatomic) CGFloat lastRightDelta; +@end + +@implementation MJRefreshTrailer + +#pragma mark - 构造方法 ++ (instancetype)trailerWithRefreshingBlock:(MJRefreshComponentAction)refreshingBlock { + MJRefreshTrailer *cmp = [[self alloc] init]; + cmp.refreshingBlock = refreshingBlock; + return cmp; +} + ++ (instancetype)trailerWithRefreshingTarget:(id)target refreshingAction:(SEL)action { + MJRefreshTrailer *cmp = [[self alloc] init]; + [cmp setRefreshingTarget:target refreshingAction:action]; + return cmp; +} + +- (void)scrollViewContentOffsetDidChange:(NSDictionary *)change { + [super scrollViewContentOffsetDidChange:change]; + + // 如果正在刷新,直接返回 + if (self.state == MJRefreshStateRefreshing) return; + + _scrollViewOriginalInset = self.scrollView.mj_inset; + + // 当前的contentOffset + CGFloat currentOffsetX = self.scrollView.mj_offsetX; + // 尾部控件刚好出现的offsetX + CGFloat happenOffsetX = [self happenOffsetX]; + // 如果是向右滚动到看不见右边控件,直接返回 + if (currentOffsetX <= happenOffsetX) return; + + CGFloat pullingPercent = (currentOffsetX - happenOffsetX) / self.mj_w; + + // 如果已全部加载,仅设置pullingPercent,然后返回 + if (self.state == MJRefreshStateNoMoreData) { + self.pullingPercent = pullingPercent; + return; + } + + if (self.scrollView.isDragging) { + self.pullingPercent = pullingPercent; + // 普通 和 即将刷新 的临界点 + CGFloat normal2pullingOffsetX = happenOffsetX + self.mj_w; + + if (self.state == MJRefreshStateIdle && currentOffsetX > normal2pullingOffsetX) { + self.state = MJRefreshStatePulling; + } else if (self.state == MJRefreshStatePulling && currentOffsetX <= normal2pullingOffsetX) { + // 转为普通状态 + self.state = MJRefreshStateIdle; + } + } else if (self.state == MJRefreshStatePulling) {// 即将刷新 && 手松开 + // 开始刷新 + [self beginRefreshing]; + } else if (pullingPercent < 1) { + self.pullingPercent = pullingPercent; + } +} + +- (void)setState:(MJRefreshState)state { + MJRefreshCheckState + // 根据状态来设置属性 + if (state == MJRefreshStateNoMoreData || state == MJRefreshStateIdle) { + // 刷新完毕 + if (MJRefreshStateRefreshing == oldState) { + [UIView animateWithDuration:self.slowAnimationDuration animations:^{ + if (self.endRefreshingAnimationBeginAction) { + self.endRefreshingAnimationBeginAction(); + } + + self.scrollView.mj_insetR -= self.lastRightDelta; + // 自动调整透明度 + if (self.isAutomaticallyChangeAlpha) self.alpha = 0.0; + } completion:^(BOOL finished) { + self.pullingPercent = 0.0; + + if (self.endRefreshingCompletionBlock) { + self.endRefreshingCompletionBlock(); + } + }]; + } + + CGFloat deltaW = [self widthForContentBreakView]; + // 刚刷新完毕 + if (MJRefreshStateRefreshing == oldState && deltaW > 0 && self.scrollView.mj_totalDataCount != self.lastRefreshCount) { + self.scrollView.mj_offsetX = self.scrollView.mj_offsetX; + } + } else if (state == MJRefreshStateRefreshing) { + // 记录刷新前的数量 + self.lastRefreshCount = self.scrollView.mj_totalDataCount; + + [UIView animateWithDuration:self.fastAnimationDuration animations:^{ + CGFloat right = self.mj_w + self.scrollViewOriginalInset.right; + CGFloat deltaW = [self widthForContentBreakView]; + if (deltaW < 0) { // 如果内容宽度小于view的宽度 + right -= deltaW; + } + self.lastRightDelta = right - self.scrollView.mj_insetR; + self.scrollView.mj_insetR = right; + + // 设置滚动位置 + CGPoint offset = self.scrollView.contentOffset; + offset.x = [self happenOffsetX] + self.mj_w; + [self.scrollView setContentOffset:offset animated:NO]; + } completion:^(BOOL finished) { + [self executeRefreshingCallback]; + }]; + } +} + +- (void)scrollViewContentSizeDidChange:(NSDictionary *)change { + [super scrollViewContentSizeDidChange:change]; + + // 内容的宽度 + CGFloat contentWidth = self.scrollView.mj_contentW + self.ignoredScrollViewContentInsetRight; + // 表格的宽度 + CGFloat scrollWidth = self.scrollView.mj_w - self.scrollViewOriginalInset.left - self.scrollViewOriginalInset.right + self.ignoredScrollViewContentInsetRight; + // 设置位置和尺寸 + self.mj_x = MAX(contentWidth, scrollWidth); +} + +- (void)placeSubviews { + [super placeSubviews]; + + self.mj_h = _scrollView.mj_h; + // 设置自己的宽度 + self.mj_w = MJRefreshTrailWidth; +} + +- (void)willMoveToSuperview:(UIView *)newSuperview { + [super willMoveToSuperview:newSuperview]; + + if (newSuperview) { + // 设置支持水平弹簧效果 + _scrollView.alwaysBounceHorizontal = YES; + _scrollView.alwaysBounceVertical = NO; + } +} + +#pragma mark . 链式语法部分 . + +- (instancetype)linkTo:(UIScrollView *)scrollView { + scrollView.mj_trailer = self; + return self; +} + +#pragma mark - 刚好看到上拉刷新控件时的contentOffset.x +- (CGFloat)happenOffsetX { + CGFloat deltaW = [self widthForContentBreakView]; + if (deltaW > 0) { + return deltaW - self.scrollViewOriginalInset.left; + } else { + return - self.scrollViewOriginalInset.left; + } +} + +#pragma mark 获得scrollView的内容 超出 view 的宽度 +- (CGFloat)widthForContentBreakView { + CGFloat w = self.scrollView.frame.size.width - self.scrollViewOriginalInset.right - self.scrollViewOriginalInset.left; + return self.scrollView.contentSize.width - w; +} + +@end diff --git a/Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoGifFooter.h b/Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoGifFooter.h new file mode 100644 index 0000000..f346157 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoGifFooter.h @@ -0,0 +1,25 @@ +// +// MJRefreshAutoGifFooter.h +// MJRefresh +// +// Created by MJ Lee on 15/4/24. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#if __has_include() +#import +#else +#import "MJRefreshAutoStateFooter.h" +#endif + +NS_ASSUME_NONNULL_BEGIN + +@interface MJRefreshAutoGifFooter : MJRefreshAutoStateFooter +@property (weak, nonatomic, readonly) UIImageView *gifView; + +/** 设置state状态下的动画图片images 动画持续时间duration*/ +- (instancetype)setImages:(NSArray *)images duration:(NSTimeInterval)duration forState:(MJRefreshState)state; +- (instancetype)setImages:(NSArray *)images forState:(MJRefreshState)state; +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoGifFooter.m b/Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoGifFooter.m new file mode 100644 index 0000000..213f69f --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoGifFooter.m @@ -0,0 +1,121 @@ +// +// MJRefreshAutoGifFooter.m +// MJRefresh +// +// Created by MJ Lee on 15/4/24. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "MJRefreshAutoGifFooter.h" +#import "NSBundle+MJRefresh.h" +#import "UIView+MJExtension.h" +#import "UIScrollView+MJExtension.h" +#import "UIScrollView+MJRefresh.h" + +@interface MJRefreshAutoGifFooter() +{ + __unsafe_unretained UIImageView *_gifView; +} +/** 所有状态对应的动画图片 */ +@property (strong, nonatomic) NSMutableDictionary *stateImages; +/** 所有状态对应的动画时间 */ +@property (strong, nonatomic) NSMutableDictionary *stateDurations; +@end + +@implementation MJRefreshAutoGifFooter +#pragma mark - 懒加载 +- (UIImageView *)gifView +{ + if (!_gifView) { + UIImageView *gifView = [[UIImageView alloc] init]; + [self addSubview:_gifView = gifView]; + } + return _gifView; +} + +- (NSMutableDictionary *)stateImages +{ + if (!_stateImages) { + self.stateImages = [NSMutableDictionary dictionary]; + } + return _stateImages; +} + +- (NSMutableDictionary *)stateDurations +{ + if (!_stateDurations) { + self.stateDurations = [NSMutableDictionary dictionary]; + } + return _stateDurations; +} + +#pragma mark - 公共方法 +- (instancetype)setImages:(NSArray *)images duration:(NSTimeInterval)duration forState:(MJRefreshState)state +{ + if (images == nil) return self; + + self.stateImages[@(state)] = images; + self.stateDurations[@(state)] = @(duration); + + /* 根据图片设置控件的高度 */ + UIImage *image = [images firstObject]; + if (image.size.height > self.mj_h) { + self.mj_h = image.size.height; + } + return self; +} + +- (instancetype)setImages:(NSArray *)images forState:(MJRefreshState)state +{ + return [self setImages:images duration:images.count * 0.1 forState:state]; +} + +#pragma mark - 实现父类的方法 +- (void)prepare +{ + [super prepare]; + + // 初始化间距 + self.labelLeftInset = 20; +} + +- (void)placeSubviews +{ + [super placeSubviews]; + + if (self.gifView.constraints.count) return; + + self.gifView.frame = self.bounds; + if (self.isRefreshingTitleHidden) { + self.gifView.contentMode = UIViewContentModeCenter; + } else { + self.gifView.contentMode = UIViewContentModeRight; + self.gifView.mj_w = self.mj_w * 0.5 - self.labelLeftInset - self.stateLabel.mj_textWidth * 0.5; + } +} + +- (void)setState:(MJRefreshState)state +{ + MJRefreshCheckState + + // 根据状态做事情 + if (state == MJRefreshStateRefreshing) { + NSArray *images = self.stateImages[@(state)]; + if (images.count == 0) return; + [self.gifView stopAnimating]; + + self.gifView.hidden = NO; + if (images.count == 1) { // 单张图片 + self.gifView.image = [images lastObject]; + } else { // 多张图片 + self.gifView.animationImages = images; + self.gifView.animationDuration = [self.stateDurations[@(state)] doubleValue]; + [self.gifView startAnimating]; + } + } else if (state == MJRefreshStateNoMoreData || state == MJRefreshStateIdle) { + [self.gifView stopAnimating]; + self.gifView.hidden = YES; + } +} +@end + diff --git a/Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoNormalFooter.h b/Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoNormalFooter.h new file mode 100644 index 0000000..f8d1e04 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoNormalFooter.h @@ -0,0 +1,25 @@ +// +// MJRefreshAutoNormalFooter.h +// MJRefresh +// +// Created by MJ Lee on 15/4/24. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#if __has_include() +#import +#else +#import "MJRefreshAutoStateFooter.h" +#endif + +NS_ASSUME_NONNULL_BEGIN + +@interface MJRefreshAutoNormalFooter : MJRefreshAutoStateFooter +@property (weak, nonatomic, readonly) UIActivityIndicatorView *loadingView; + +/** 菊花的样式 */ +@property (assign, nonatomic) UIActivityIndicatorViewStyle activityIndicatorViewStyle MJRefreshDeprecated("first deprecated in 3.2.2 - Use `loadingView` property"); +@end + + +NS_ASSUME_NONNULL_END diff --git a/Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoNormalFooter.m b/Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoNormalFooter.m new file mode 100644 index 0000000..9e6a03d --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoNormalFooter.m @@ -0,0 +1,81 @@ +// +// MJRefreshAutoNormalFooter.m +// MJRefresh +// +// Created by MJ Lee on 15/4/24. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "MJRefreshAutoNormalFooter.h" +#import "NSBundle+MJRefresh.h" +#import "UIView+MJExtension.h" +#import "UIScrollView+MJExtension.h" +#import "UIScrollView+MJRefresh.h" + +@interface MJRefreshAutoNormalFooter() +@property (weak, nonatomic) UIActivityIndicatorView *loadingView; +@end + +@implementation MJRefreshAutoNormalFooter +#pragma mark - 懒加载子控件 +- (UIActivityIndicatorView *)loadingView +{ + if (!_loadingView) { + UIActivityIndicatorView *loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:_activityIndicatorViewStyle]; + loadingView.hidesWhenStopped = YES; + [self addSubview:_loadingView = loadingView]; + } + return _loadingView; +} + +- (void)setActivityIndicatorViewStyle:(UIActivityIndicatorViewStyle)activityIndicatorViewStyle +{ + _activityIndicatorViewStyle = activityIndicatorViewStyle; + + [self.loadingView removeFromSuperview]; + self.loadingView = nil; + [self setNeedsLayout]; +} +#pragma mark - 重写父类的方法 +- (void)prepare +{ + [super prepare]; + +#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000 + if (@available(iOS 13.0, *)) { + _activityIndicatorViewStyle = UIActivityIndicatorViewStyleMedium; + return; + } +#endif + + _activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray; +} + +- (void)placeSubviews +{ + [super placeSubviews]; + + if (self.loadingView.constraints.count) return; + + // 圈圈 + CGFloat loadingCenterX = self.mj_w * 0.5; + if (!self.isRefreshingTitleHidden) { + loadingCenterX -= self.stateLabel.mj_textWidth * 0.5 + self.labelLeftInset; + } + CGFloat loadingCenterY = self.mj_h * 0.5; + self.loadingView.center = CGPointMake(loadingCenterX, loadingCenterY); +} + +- (void)setState:(MJRefreshState)state +{ + MJRefreshCheckState + + // 根据状态做事情 + if (state == MJRefreshStateNoMoreData || state == MJRefreshStateIdle) { + [self.loadingView stopAnimating]; + } else if (state == MJRefreshStateRefreshing) { + [self.loadingView startAnimating]; + } +} + +@end diff --git a/Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoStateFooter.h b/Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoStateFooter.h new file mode 100644 index 0000000..c83622d --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoStateFooter.h @@ -0,0 +1,30 @@ +// +// MJRefreshAutoStateFooter.h +// MJRefresh +// +// Created by MJ Lee on 15/6/13. +// Copyright © 2015年 小码哥. All rights reserved. +// + +#if __has_include() +#import +#else +#import "MJRefreshAutoFooter.h" +#endif + +NS_ASSUME_NONNULL_BEGIN + +@interface MJRefreshAutoStateFooter : MJRefreshAutoFooter +/** 文字距离圈圈、箭头的距离 */ +@property (assign, nonatomic) CGFloat labelLeftInset; +/** 显示刷新状态的label */ +@property (weak, nonatomic, readonly) UILabel *stateLabel; + +/** 设置state状态下的文字 */ +- (instancetype)setTitle:(NSString *)title forState:(MJRefreshState)state; + +/** 隐藏刷新状态的文字 */ +@property (assign, nonatomic, getter=isRefreshingTitleHidden) BOOL refreshingTitleHidden; +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoStateFooter.m b/Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoStateFooter.m new file mode 100644 index 0000000..e5ff652 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoStateFooter.m @@ -0,0 +1,119 @@ +// +// MJRefreshAutoStateFooter.m +// MJRefresh +// +// Created by MJ Lee on 15/6/13. +// Copyright © 2015年 小码哥. All rights reserved. +// + +#import "MJRefreshAutoStateFooter.h" +#import "NSBundle+MJRefresh.h" + +@interface MJRefreshAutoFooter (TapTriggerFix) + +- (void)beginRefreshingWithoutValidation; +@end + + +@implementation MJRefreshAutoFooter (TapTriggerFix) + +- (void)beginRefreshingWithoutValidation { + [super beginRefreshing]; +} + +@end + +@interface MJRefreshAutoStateFooter() +{ + /** 显示刷新状态的label */ + __unsafe_unretained UILabel *_stateLabel; +} +/** 所有状态对应的文字 */ +@property (strong, nonatomic) NSMutableDictionary *stateTitles; +@end + +@implementation MJRefreshAutoStateFooter +#pragma mark - 懒加载 +- (NSMutableDictionary *)stateTitles +{ + if (!_stateTitles) { + self.stateTitles = [NSMutableDictionary dictionary]; + } + return _stateTitles; +} + +- (UILabel *)stateLabel +{ + if (!_stateLabel) { + [self addSubview:_stateLabel = [UILabel mj_label]]; + } + return _stateLabel; +} + +#pragma mark - 公共方法 +- (instancetype)setTitle:(NSString *)title forState:(MJRefreshState)state +{ + if (title == nil) return self; + self.stateTitles[@(state)] = title; + self.stateLabel.text = self.stateTitles[@(self.state)]; + return self; +} + +#pragma mark - 私有方法 +- (void)stateLabelClick +{ + if (self.state == MJRefreshStateIdle) { + [super beginRefreshingWithoutValidation]; + } +} + +- (void)textConfiguration { + // 初始化文字 + [self setTitle:[NSBundle mj_localizedStringForKey:MJRefreshAutoFooterIdleText] forState:MJRefreshStateIdle]; + [self setTitle:[NSBundle mj_localizedStringForKey:MJRefreshAutoFooterRefreshingText] forState:MJRefreshStateRefreshing]; + [self setTitle:[NSBundle mj_localizedStringForKey:MJRefreshAutoFooterNoMoreDataText] forState:MJRefreshStateNoMoreData]; +} + +#pragma mark - 重写父类的方法 +- (void)prepare +{ + [super prepare]; + + // 初始化间距 + self.labelLeftInset = MJRefreshLabelLeftInset; + + [self textConfiguration]; + + // 监听label + self.stateLabel.userInteractionEnabled = YES; + [self.stateLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(stateLabelClick)]]; +} + +- (void)i18nDidChange { + [self textConfiguration]; + + [super i18nDidChange]; +} + + +- (void)placeSubviews +{ + [super placeSubviews]; + + if (self.stateLabel.constraints.count) return; + + // 状态标签 + self.stateLabel.frame = self.bounds; +} + +- (void)setState:(MJRefreshState)state +{ + MJRefreshCheckState + + if (self.isRefreshingTitleHidden && state == MJRefreshStateRefreshing) { + self.stateLabel.text = nil; + } else { + self.stateLabel.text = self.stateTitles[@(state)]; + } +} +@end diff --git a/Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackGifFooter.h b/Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackGifFooter.h new file mode 100644 index 0000000..a7ba065 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackGifFooter.h @@ -0,0 +1,25 @@ +// +// MJRefreshBackGifFooter.h +// MJRefresh +// +// Created by MJ Lee on 15/4/24. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#if __has_include() +#import +#else +#import "MJRefreshBackStateFooter.h" +#endif + +NS_ASSUME_NONNULL_BEGIN + +@interface MJRefreshBackGifFooter : MJRefreshBackStateFooter +@property (weak, nonatomic, readonly) UIImageView *gifView; + +/** 设置state状态下的动画图片images 动画持续时间duration*/ +- (instancetype)setImages:(NSArray *)images duration:(NSTimeInterval)duration forState:(MJRefreshState)state; +- (instancetype)setImages:(NSArray *)images forState:(MJRefreshState)state; +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackGifFooter.m b/Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackGifFooter.m new file mode 100644 index 0000000..23c626c --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackGifFooter.m @@ -0,0 +1,132 @@ +// +// MJRefreshBackGifFooter.m +// MJRefresh +// +// Created by MJ Lee on 15/4/24. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "MJRefreshBackGifFooter.h" +#import "NSBundle+MJRefresh.h" +#import "UIView+MJExtension.h" +#import "UIScrollView+MJExtension.h" +#import "UIScrollView+MJRefresh.h" + +@interface MJRefreshBackGifFooter() +{ + __unsafe_unretained UIImageView *_gifView; +} +/** 所有状态对应的动画图片 */ +@property (strong, nonatomic) NSMutableDictionary *stateImages; +/** 所有状态对应的动画时间 */ +@property (strong, nonatomic) NSMutableDictionary *stateDurations; +@end + +@implementation MJRefreshBackGifFooter +#pragma mark - 懒加载 +- (UIImageView *)gifView +{ + if (!_gifView) { + UIImageView *gifView = [[UIImageView alloc] init]; + [self addSubview:_gifView = gifView]; + } + return _gifView; +} + +- (NSMutableDictionary *)stateImages +{ + if (!_stateImages) { + self.stateImages = [NSMutableDictionary dictionary]; + } + return _stateImages; +} + +- (NSMutableDictionary *)stateDurations +{ + if (!_stateDurations) { + self.stateDurations = [NSMutableDictionary dictionary]; + } + return _stateDurations; +} + +#pragma mark - 公共方法 +- (instancetype)setImages:(NSArray *)images duration:(NSTimeInterval)duration forState:(MJRefreshState)state +{ + if (images == nil) return self; + + self.stateImages[@(state)] = images; + self.stateDurations[@(state)] = @(duration); + + /* 根据图片设置控件的高度 */ + UIImage *image = [images firstObject]; + if (image.size.height > self.mj_h) { + self.mj_h = image.size.height; + } + return self; +} + +- (instancetype)setImages:(NSArray *)images forState:(MJRefreshState)state +{ + return [self setImages:images duration:images.count * 0.1 forState:state]; +} + +#pragma mark - 实现父类的方法 +- (void)prepare +{ + [super prepare]; + + // 初始化间距 + self.labelLeftInset = 20; +} + +- (void)setPullingPercent:(CGFloat)pullingPercent +{ + [super setPullingPercent:pullingPercent]; + NSArray *images = self.stateImages[@(MJRefreshStateIdle)]; + if (self.state != MJRefreshStateIdle || images.count == 0) return; + [self.gifView stopAnimating]; + NSUInteger index = images.count * pullingPercent; + if (index >= images.count) index = images.count - 1; + self.gifView.image = images[index]; +} + +- (void)placeSubviews +{ + [super placeSubviews]; + + if (self.gifView.constraints.count) return; + + self.gifView.frame = self.bounds; + if (self.stateLabel.hidden) { + self.gifView.contentMode = UIViewContentModeCenter; + } else { + self.gifView.contentMode = UIViewContentModeRight; + self.gifView.mj_w = self.mj_w * 0.5 - self.labelLeftInset - self.stateLabel.mj_textWidth * 0.5; + } +} + +- (void)setState:(MJRefreshState)state +{ + MJRefreshCheckState + + // 根据状态做事情 + if (state == MJRefreshStatePulling || state == MJRefreshStateRefreshing) { + NSArray *images = self.stateImages[@(state)]; + if (images.count == 0) return; + + self.gifView.hidden = NO; + [self.gifView stopAnimating]; + if (images.count == 1) { // 单张图片 + self.gifView.image = [images lastObject]; + } else { // 多张图片 + self.gifView.animationImages = images; + self.gifView.animationDuration = [self.stateDurations[@(state)] doubleValue]; + [self.gifView startAnimating]; + } + } else if (state == MJRefreshStateIdle) { + self.gifView.hidden = NO; + } else if (state == MJRefreshStateNoMoreData) { + self.gifView.hidden = YES; + } +} +@end diff --git a/Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackNormalFooter.h b/Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackNormalFooter.h new file mode 100644 index 0000000..d255807 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackNormalFooter.h @@ -0,0 +1,25 @@ +// +// MJRefreshBackNormalFooter.h +// MJRefresh +// +// Created by MJ Lee on 15/4/24. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#if __has_include() +#import +#else +#import "MJRefreshBackStateFooter.h" +#endif + +NS_ASSUME_NONNULL_BEGIN + +@interface MJRefreshBackNormalFooter : MJRefreshBackStateFooter +@property (weak, nonatomic, readonly) UIImageView *arrowView; +@property (weak, nonatomic, readonly) UIActivityIndicatorView *loadingView; + +/** 菊花的样式 */ +@property (assign, nonatomic) UIActivityIndicatorViewStyle activityIndicatorViewStyle MJRefreshDeprecated("first deprecated in 3.2.2 - Use `loadingView` property"); +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackNormalFooter.m b/Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackNormalFooter.m new file mode 100644 index 0000000..932af76 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackNormalFooter.m @@ -0,0 +1,132 @@ +// +// MJRefreshBackNormalFooter.m +// MJRefresh +// +// Created by MJ Lee on 15/4/24. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "MJRefreshBackNormalFooter.h" +#import "NSBundle+MJRefresh.h" +#import "UIView+MJExtension.h" + +@interface MJRefreshBackNormalFooter() +{ + __unsafe_unretained UIImageView *_arrowView; +} +@property (weak, nonatomic) UIActivityIndicatorView *loadingView; +@end + +@implementation MJRefreshBackNormalFooter +#pragma mark - 懒加载子控件 +- (UIImageView *)arrowView +{ + if (!_arrowView) { + UIImageView *arrowView = [[UIImageView alloc] initWithImage:[NSBundle mj_arrowImage]]; + [self addSubview:_arrowView = arrowView]; + } + return _arrowView; +} + + +- (UIActivityIndicatorView *)loadingView +{ + if (!_loadingView) { + UIActivityIndicatorView *loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:_activityIndicatorViewStyle]; + loadingView.hidesWhenStopped = YES; + [self addSubview:_loadingView = loadingView]; + } + return _loadingView; +} + +- (void)setActivityIndicatorViewStyle:(UIActivityIndicatorViewStyle)activityIndicatorViewStyle +{ + _activityIndicatorViewStyle = activityIndicatorViewStyle; + + [self.loadingView removeFromSuperview]; + self.loadingView = nil; + [self setNeedsLayout]; +} +#pragma mark - 重写父类的方法 +- (void)prepare +{ + [super prepare]; + +#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000 + if (@available(iOS 13.0, *)) { + _activityIndicatorViewStyle = UIActivityIndicatorViewStyleMedium; + return; + } +#endif + + _activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray; +} + +- (void)placeSubviews +{ + [super placeSubviews]; + + // 箭头的中心点 + CGFloat arrowCenterX = self.mj_w * 0.5; + if (!self.stateLabel.hidden) { + arrowCenterX -= self.labelLeftInset + self.stateLabel.mj_textWidth * 0.5; + } + CGFloat arrowCenterY = self.mj_h * 0.5; + CGPoint arrowCenter = CGPointMake(arrowCenterX, arrowCenterY); + + // 箭头 + if (self.arrowView.constraints.count == 0) { + self.arrowView.mj_size = self.arrowView.image.size; + self.arrowView.center = arrowCenter; + } + + // 圈圈 + if (self.loadingView.constraints.count == 0) { + self.loadingView.center = arrowCenter; + } + + self.arrowView.tintColor = self.stateLabel.textColor; +} + +- (void)setState:(MJRefreshState)state +{ + MJRefreshCheckState + + // 根据状态做事情 + if (state == MJRefreshStateIdle) { + if (oldState == MJRefreshStateRefreshing) { + self.arrowView.transform = CGAffineTransformMakeRotation(0.000001 - M_PI); + [UIView animateWithDuration:self.slowAnimationDuration animations:^{ + self.loadingView.alpha = 0.0; + } completion:^(BOOL finished) { + // 防止动画结束后,状态已经不是MJRefreshStateIdle + if (self.state != MJRefreshStateIdle) return; + + self.loadingView.alpha = 1.0; + [self.loadingView stopAnimating]; + + self.arrowView.hidden = NO; + }]; + } else { + self.arrowView.hidden = NO; + [self.loadingView stopAnimating]; + [UIView animateWithDuration:self.fastAnimationDuration animations:^{ + self.arrowView.transform = CGAffineTransformMakeRotation(0.000001 - M_PI); + }]; + } + } else if (state == MJRefreshStatePulling) { + self.arrowView.hidden = NO; + [self.loadingView stopAnimating]; + [UIView animateWithDuration:self.fastAnimationDuration animations:^{ + self.arrowView.transform = CGAffineTransformIdentity; + }]; + } else if (state == MJRefreshStateRefreshing) { + self.arrowView.hidden = YES; + [self.loadingView startAnimating]; + } else if (state == MJRefreshStateNoMoreData) { + self.arrowView.hidden = YES; + [self.loadingView stopAnimating]; + } +} + +@end diff --git a/Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackStateFooter.h b/Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackStateFooter.h new file mode 100644 index 0000000..c6897f4 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackStateFooter.h @@ -0,0 +1,29 @@ +// +// MJRefreshBackStateFooter.h +// MJRefresh +// +// Created by MJ Lee on 15/6/13. +// Copyright © 2015年 小码哥. All rights reserved. +// + +#if __has_include() +#import +#else +#import "MJRefreshBackFooter.h" +#endif + +NS_ASSUME_NONNULL_BEGIN + +@interface MJRefreshBackStateFooter : MJRefreshBackFooter +/** 文字距离圈圈、箭头的距离 */ +@property (assign, nonatomic) CGFloat labelLeftInset; +/** 显示刷新状态的label */ +@property (weak, nonatomic, readonly) UILabel *stateLabel; +/** 设置state状态下的文字 */ +- (instancetype)setTitle:(NSString *)title forState:(MJRefreshState)state; + +/** 获取state状态下的title */ +- (NSString *)titleForState:(MJRefreshState)state; +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackStateFooter.m b/Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackStateFooter.m new file mode 100644 index 0000000..70f4024 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackStateFooter.m @@ -0,0 +1,93 @@ +// +// MJRefreshBackStateFooter.m +// MJRefresh +// +// Created by MJ Lee on 15/6/13. +// Copyright © 2015年 小码哥. All rights reserved. +// + +#import "MJRefreshBackStateFooter.h" +#import "NSBundle+MJRefresh.h" + +@interface MJRefreshBackStateFooter() +{ + /** 显示刷新状态的label */ + __unsafe_unretained UILabel *_stateLabel; +} +/** 所有状态对应的文字 */ +@property (strong, nonatomic) NSMutableDictionary *stateTitles; +@end + +@implementation MJRefreshBackStateFooter +#pragma mark - 懒加载 +- (NSMutableDictionary *)stateTitles +{ + if (!_stateTitles) { + self.stateTitles = [NSMutableDictionary dictionary]; + } + return _stateTitles; +} + +- (UILabel *)stateLabel +{ + if (!_stateLabel) { + [self addSubview:_stateLabel = [UILabel mj_label]]; + } + return _stateLabel; +} + +#pragma mark - 公共方法 +- (instancetype)setTitle:(NSString *)title forState:(MJRefreshState)state +{ + if (title == nil) return self; + self.stateTitles[@(state)] = title; + self.stateLabel.text = self.stateTitles[@(self.state)]; + return self; +} + +- (NSString *)titleForState:(MJRefreshState)state { + return self.stateTitles[@(state)]; +} + +- (void)textConfiguration { + // 初始化文字 + [self setTitle:[NSBundle mj_localizedStringForKey:MJRefreshBackFooterIdleText] forState:MJRefreshStateIdle]; + [self setTitle:[NSBundle mj_localizedStringForKey:MJRefreshBackFooterPullingText] forState:MJRefreshStatePulling]; + [self setTitle:[NSBundle mj_localizedStringForKey:MJRefreshBackFooterRefreshingText] forState:MJRefreshStateRefreshing]; + [self setTitle:[NSBundle mj_localizedStringForKey:MJRefreshBackFooterNoMoreDataText] forState:MJRefreshStateNoMoreData]; +} + +#pragma mark - 重写父类的方法 +- (void)prepare +{ + [super prepare]; + + // 初始化间距 + self.labelLeftInset = MJRefreshLabelLeftInset; + [self textConfiguration]; +} + +- (void)i18nDidChange { + [self textConfiguration]; + + [super i18nDidChange]; +} + +- (void)placeSubviews +{ + [super placeSubviews]; + + if (self.stateLabel.constraints.count) return; + + // 状态标签 + self.stateLabel.frame = self.bounds; +} + +- (void)setState:(MJRefreshState)state +{ + MJRefreshCheckState + + // 设置状态文字 + self.stateLabel.text = self.stateTitles[@(state)]; +} +@end diff --git a/Pods/MJRefresh/MJRefresh/Custom/Header/MJRefreshGifHeader.h b/Pods/MJRefresh/MJRefresh/Custom/Header/MJRefreshGifHeader.h new file mode 100644 index 0000000..afa4a13 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Header/MJRefreshGifHeader.h @@ -0,0 +1,25 @@ +// +// MJRefreshGifHeader.h +// MJRefresh +// +// Created by MJ Lee on 15/4/24. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#if __has_include() +#import +#else +#import "MJRefreshStateHeader.h" +#endif + +NS_ASSUME_NONNULL_BEGIN + +@interface MJRefreshGifHeader : MJRefreshStateHeader +@property (weak, nonatomic, readonly) UIImageView *gifView; + +/** 设置state状态下的动画图片images 动画持续时间duration*/ +- (instancetype)setImages:(NSArray *)images duration:(NSTimeInterval)duration forState:(MJRefreshState)state; +- (instancetype)setImages:(NSArray *)images forState:(MJRefreshState)state; +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/MJRefresh/MJRefresh/Custom/Header/MJRefreshGifHeader.m b/Pods/MJRefresh/MJRefresh/Custom/Header/MJRefreshGifHeader.m new file mode 100644 index 0000000..707e466 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Header/MJRefreshGifHeader.m @@ -0,0 +1,135 @@ +// +// MJRefreshGifHeader.m +// MJRefresh +// +// Created by MJ Lee on 15/4/24. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "MJRefreshGifHeader.h" +#import "UIView+MJExtension.h" +#import "UIScrollView+MJExtension.h" + +@interface MJRefreshGifHeader() +{ + __unsafe_unretained UIImageView *_gifView; +} +/** 所有状态对应的动画图片 */ +@property (strong, nonatomic) NSMutableDictionary *stateImages; +/** 所有状态对应的动画时间 */ +@property (strong, nonatomic) NSMutableDictionary *stateDurations; +@end + +@implementation MJRefreshGifHeader +#pragma mark - 懒加载 +- (UIImageView *)gifView +{ + if (!_gifView) { + UIImageView *gifView = [[UIImageView alloc] init]; + [self addSubview:_gifView = gifView]; + } + return _gifView; +} + +- (NSMutableDictionary *)stateImages +{ + if (!_stateImages) { + self.stateImages = [NSMutableDictionary dictionary]; + } + return _stateImages; +} + +- (NSMutableDictionary *)stateDurations +{ + if (!_stateDurations) { + self.stateDurations = [NSMutableDictionary dictionary]; + } + return _stateDurations; +} + +#pragma mark - 公共方法 +- (instancetype)setImages:(NSArray *)images duration:(NSTimeInterval)duration forState:(MJRefreshState)state { + if (images == nil) return self; + + self.stateImages[@(state)] = images; + self.stateDurations[@(state)] = @(duration); + + /* 根据图片设置控件的高度 */ + UIImage *image = [images firstObject]; + if (image.size.height > self.mj_h) { + self.mj_h = image.size.height; + } + return self; +} + +- (instancetype)setImages:(NSArray *)images forState:(MJRefreshState)state +{ + return [self setImages:images duration:images.count * 0.1 forState:state]; +} + +#pragma mark - 实现父类的方法 +- (void)prepare +{ + [super prepare]; + + // 初始化间距 + self.labelLeftInset = 20; +} + +- (void)setPullingPercent:(CGFloat)pullingPercent +{ + [super setPullingPercent:pullingPercent]; + NSArray *images = self.stateImages[@(MJRefreshStateIdle)]; + if (self.state != MJRefreshStateIdle || images.count == 0) return; + // 停止动画 + [self.gifView stopAnimating]; + // 设置当前需要显示的图片 + NSUInteger index = images.count * pullingPercent; + if (index >= images.count) index = images.count - 1; + self.gifView.image = images[index]; +} + +- (void)placeSubviews +{ + [super placeSubviews]; + + if (self.gifView.constraints.count) return; + + self.gifView.frame = self.bounds; + if (self.stateLabel.hidden && self.lastUpdatedTimeLabel.hidden) { + self.gifView.contentMode = UIViewContentModeCenter; + } else { + self.gifView.contentMode = UIViewContentModeRight; + + CGFloat stateWidth = self.stateLabel.mj_textWidth; + CGFloat timeWidth = 0.0; + if (!self.lastUpdatedTimeLabel.hidden) { + timeWidth = self.lastUpdatedTimeLabel.mj_textWidth; + } + CGFloat textWidth = MAX(stateWidth, timeWidth); + self.gifView.mj_w = self.mj_w * 0.5 - textWidth * 0.5 - self.labelLeftInset; + } +} + +- (void)setState:(MJRefreshState)state +{ + MJRefreshCheckState + + // 根据状态做事情 + if (state == MJRefreshStatePulling || state == MJRefreshStateRefreshing) { + NSArray *images = self.stateImages[@(state)]; + if (images.count == 0) return; + + [self.gifView stopAnimating]; + if (images.count == 1) { // 单张图片 + self.gifView.image = [images lastObject]; + } else { // 多张图片 + self.gifView.animationImages = images; + self.gifView.animationDuration = [self.stateDurations[@(state)] doubleValue]; + [self.gifView startAnimating]; + } + } else if (state == MJRefreshStateIdle) { + [self.gifView stopAnimating]; + } +} +@end diff --git a/Pods/MJRefresh/MJRefresh/Custom/Header/MJRefreshNormalHeader.h b/Pods/MJRefresh/MJRefresh/Custom/Header/MJRefreshNormalHeader.h new file mode 100644 index 0000000..2bfef39 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Header/MJRefreshNormalHeader.h @@ -0,0 +1,26 @@ +// +// MJRefreshNormalHeader.h +// MJRefresh +// +// Created by MJ Lee on 15/4/24. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#if __has_include() +#import +#else +#import "MJRefreshStateHeader.h" +#endif + +NS_ASSUME_NONNULL_BEGIN + +@interface MJRefreshNormalHeader : MJRefreshStateHeader +@property (weak, nonatomic, readonly) UIImageView *arrowView; +@property (weak, nonatomic, readonly) UIActivityIndicatorView *loadingView; + + +/** 菊花的样式 */ +@property (assign, nonatomic) UIActivityIndicatorViewStyle activityIndicatorViewStyle MJRefreshDeprecated("first deprecated in 3.2.2 - Use `loadingView` property"); +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/MJRefresh/MJRefresh/Custom/Header/MJRefreshNormalHeader.m b/Pods/MJRefresh/MJRefresh/Custom/Header/MJRefreshNormalHeader.m new file mode 100644 index 0000000..84a66cb --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Header/MJRefreshNormalHeader.m @@ -0,0 +1,137 @@ +// +// MJRefreshNormalHeader.m +// MJRefresh +// +// Created by MJ Lee on 15/4/24. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "MJRefreshNormalHeader.h" +#import "NSBundle+MJRefresh.h" +#import "UIScrollView+MJRefresh.h" +#import "UIView+MJExtension.h" + +@interface MJRefreshNormalHeader() +{ + __unsafe_unretained UIImageView *_arrowView; +} +@property (weak, nonatomic) UIActivityIndicatorView *loadingView; +@end + +@implementation MJRefreshNormalHeader +#pragma mark - 懒加载子控件 +- (UIImageView *)arrowView +{ + if (!_arrowView) { + UIImageView *arrowView = [[UIImageView alloc] initWithImage:[NSBundle mj_arrowImage]]; + [self addSubview:_arrowView = arrowView]; + } + return _arrowView; +} + +- (UIActivityIndicatorView *)loadingView +{ + if (!_loadingView) { + UIActivityIndicatorView *loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:_activityIndicatorViewStyle]; + loadingView.hidesWhenStopped = YES; + [self addSubview:_loadingView = loadingView]; + } + return _loadingView; +} + +#pragma mark - 公共方法 +- (void)setActivityIndicatorViewStyle:(UIActivityIndicatorViewStyle)activityIndicatorViewStyle +{ + _activityIndicatorViewStyle = activityIndicatorViewStyle; + + [self.loadingView removeFromSuperview]; + self.loadingView = nil; + [self setNeedsLayout]; +} + +#pragma mark - 重写父类的方法 +- (void)prepare +{ + [super prepare]; + +#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000 + if (@available(iOS 13.0, *)) { + _activityIndicatorViewStyle = UIActivityIndicatorViewStyleMedium; + return; + } +#endif + + _activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray; +} + +- (void)placeSubviews +{ + [super placeSubviews]; + + // 箭头的中心点 + CGFloat arrowCenterX = self.mj_w * 0.5; + if (!self.stateLabel.hidden) { + CGFloat stateWidth = self.stateLabel.mj_textWidth; + CGFloat timeWidth = 0.0; + if (!self.lastUpdatedTimeLabel.hidden) { + timeWidth = self.lastUpdatedTimeLabel.mj_textWidth; + } + CGFloat textWidth = MAX(stateWidth, timeWidth); + arrowCenterX -= textWidth / 2 + self.labelLeftInset; + } + CGFloat arrowCenterY = self.mj_h * 0.5; + CGPoint arrowCenter = CGPointMake(arrowCenterX, arrowCenterY); + + // 箭头 + if (self.arrowView.constraints.count == 0) { + self.arrowView.mj_size = self.arrowView.image.size; + self.arrowView.center = arrowCenter; + } + + // 圈圈 + if (self.loadingView.constraints.count == 0) { + self.loadingView.center = arrowCenter; + } + + self.arrowView.tintColor = self.stateLabel.textColor; +} + +- (void)setState:(MJRefreshState)state +{ + MJRefreshCheckState + + // 根据状态做事情 + if (state == MJRefreshStateIdle) { + if (oldState == MJRefreshStateRefreshing) { + self.arrowView.transform = CGAffineTransformIdentity; + + [UIView animateWithDuration:self.slowAnimationDuration animations:^{ + self.loadingView.alpha = 0.0; + } completion:^(BOOL finished) { + // 如果执行完动画发现不是idle状态,就直接返回,进入其他状态 + if (self.state != MJRefreshStateIdle) return; + + self.loadingView.alpha = 1.0; + [self.loadingView stopAnimating]; + self.arrowView.hidden = NO; + }]; + } else { + [self.loadingView stopAnimating]; + self.arrowView.hidden = NO; + [UIView animateWithDuration:self.fastAnimationDuration animations:^{ + self.arrowView.transform = CGAffineTransformIdentity; + }]; + } + } else if (state == MJRefreshStatePulling) { + [self.loadingView stopAnimating]; + self.arrowView.hidden = NO; + [UIView animateWithDuration:self.fastAnimationDuration animations:^{ + self.arrowView.transform = CGAffineTransformMakeRotation(0.000001 - M_PI); + }]; + } else if (state == MJRefreshStateRefreshing) { + self.loadingView.alpha = 1.0; // 防止refreshing -> idle的动画完毕动作没有被执行 + [self.loadingView startAnimating]; + self.arrowView.hidden = YES; + } +} +@end diff --git a/Pods/MJRefresh/MJRefresh/Custom/Header/MJRefreshStateHeader.h b/Pods/MJRefresh/MJRefresh/Custom/Header/MJRefreshStateHeader.h new file mode 100644 index 0000000..8e1d108 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Header/MJRefreshStateHeader.h @@ -0,0 +1,39 @@ +// +// MJRefreshStateHeader.h +// MJRefresh +// +// Created by MJ Lee on 15/4/24. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#if __has_include() +#import +#else +#import "MJRefreshHeader.h" +#endif + +NS_ASSUME_NONNULL_BEGIN + +@interface MJRefreshStateHeader : MJRefreshHeader +#pragma mark - 刷新时间相关 +/** 利用这个block来决定显示的更新时间文字 */ +@property (copy, nonatomic, nullable) NSString *(^lastUpdatedTimeText)(NSDate * _Nullable lastUpdatedTime); +/** 显示上一次刷新时间的label */ +@property (weak, nonatomic, readonly) UILabel *lastUpdatedTimeLabel; + +#pragma mark - 状态相关 +/** 文字距离圈圈、箭头的距离 */ +@property (assign, nonatomic) CGFloat labelLeftInset; +/** 显示刷新状态的label */ +@property (weak, nonatomic, readonly) UILabel *stateLabel; +/** 设置state状态下的文字 */ +- (instancetype)setTitle:(NSString *)title forState:(MJRefreshState)state; +@end + +@interface MJRefreshStateHeader (ChainingGrammar) + +- (instancetype)modifyLastUpdatedTimeText:(NSString * (^)(NSDate * _Nullable lastUpdatedTime))handler; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/MJRefresh/MJRefresh/Custom/Header/MJRefreshStateHeader.m b/Pods/MJRefresh/MJRefresh/Custom/Header/MJRefreshStateHeader.m new file mode 100644 index 0000000..62d1ddc --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Header/MJRefreshStateHeader.m @@ -0,0 +1,191 @@ +// +// MJRefreshStateHeader.m +// MJRefresh +// +// Created by MJ Lee on 15/4/24. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "MJRefreshStateHeader.h" +#import "MJRefreshConst.h" +#import "NSBundle+MJRefresh.h" +#import "UIView+MJExtension.h" +#import "UIScrollView+MJExtension.h" + +@interface MJRefreshStateHeader() +{ + /** 显示上一次刷新时间的label */ + __unsafe_unretained UILabel *_lastUpdatedTimeLabel; + /** 显示刷新状态的label */ + __unsafe_unretained UILabel *_stateLabel; +} +/** 所有状态对应的文字 */ +@property (strong, nonatomic) NSMutableDictionary *stateTitles; +@end + +@implementation MJRefreshStateHeader +#pragma mark - 懒加载 +- (NSMutableDictionary *)stateTitles +{ + if (!_stateTitles) { + self.stateTitles = [NSMutableDictionary dictionary]; + } + return _stateTitles; +} + +- (UILabel *)stateLabel +{ + if (!_stateLabel) { + [self addSubview:_stateLabel = [UILabel mj_label]]; + } + return _stateLabel; +} + +- (UILabel *)lastUpdatedTimeLabel +{ + if (!_lastUpdatedTimeLabel) { + [self addSubview:_lastUpdatedTimeLabel = [UILabel mj_label]]; + } + return _lastUpdatedTimeLabel; +} + +- (void)setLastUpdatedTimeText:(NSString * _Nonnull (^)(NSDate * _Nullable))lastUpdatedTimeText{ + _lastUpdatedTimeText = lastUpdatedTimeText; + // 重新设置key(重新显示时间) + self.lastUpdatedTimeKey = self.lastUpdatedTimeKey; +} + +#pragma mark - 公共方法 +- (instancetype)setTitle:(NSString *)title forState:(MJRefreshState)state +{ + if (title == nil) return self; + self.stateTitles[@(state)] = title; + self.stateLabel.text = self.stateTitles[@(self.state)]; + return self; +} + +#pragma mark key的处理 +- (void)setLastUpdatedTimeKey:(NSString *)lastUpdatedTimeKey +{ + [super setLastUpdatedTimeKey:lastUpdatedTimeKey]; + + // 如果label隐藏了,就不用再处理 + if (self.lastUpdatedTimeLabel.hidden) return; + + NSDate *lastUpdatedTime = [[NSUserDefaults standardUserDefaults] objectForKey:lastUpdatedTimeKey]; + + // 如果有block + if (self.lastUpdatedTimeText) { + self.lastUpdatedTimeLabel.text = self.lastUpdatedTimeText(lastUpdatedTime); + return; + } + + if (lastUpdatedTime) { + // 1.获得年月日 + NSCalendar *calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian]; + NSUInteger unitFlags = NSCalendarUnitYear| NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute; + NSDateComponents *cmp1 = [calendar components:unitFlags fromDate:lastUpdatedTime]; + NSDateComponents *cmp2 = [calendar components:unitFlags fromDate:[NSDate date]]; + + // 2.格式化日期 + NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; + BOOL isToday = NO; + if ([cmp1 day] == [cmp2 day]) { // 今天 + formatter.dateFormat = @" HH:mm"; + isToday = YES; + } else if ([cmp1 year] == [cmp2 year]) { // 今年 + formatter.dateFormat = @"MM-dd HH:mm"; + } else { + formatter.dateFormat = @"yyyy-MM-dd HH:mm"; + } + NSString *time = [formatter stringFromDate:lastUpdatedTime]; + + // 3.显示日期 + self.lastUpdatedTimeLabel.text = [NSString stringWithFormat:@"%@%@%@", + [NSBundle mj_localizedStringForKey:MJRefreshHeaderLastTimeText], + isToday ? [NSBundle mj_localizedStringForKey:MJRefreshHeaderDateTodayText] : @"", + time]; + } else { + self.lastUpdatedTimeLabel.text = [NSString stringWithFormat:@"%@%@", + [NSBundle mj_localizedStringForKey:MJRefreshHeaderLastTimeText], + [NSBundle mj_localizedStringForKey:MJRefreshHeaderNoneLastDateText]]; + } +} + + +- (void)textConfiguration { + // 初始化文字 + [self setTitle:[NSBundle mj_localizedStringForKey:MJRefreshHeaderIdleText] forState:MJRefreshStateIdle]; + [self setTitle:[NSBundle mj_localizedStringForKey:MJRefreshHeaderPullingText] forState:MJRefreshStatePulling]; + [self setTitle:[NSBundle mj_localizedStringForKey:MJRefreshHeaderRefreshingText] forState:MJRefreshStateRefreshing]; + self.lastUpdatedTimeKey = MJRefreshHeaderLastUpdatedTimeKey; +} + +#pragma mark - 覆盖父类的方法 +- (void)prepare +{ + [super prepare]; + + // 初始化间距 + self.labelLeftInset = MJRefreshLabelLeftInset; + [self textConfiguration]; +} + +- (void)i18nDidChange { + [self textConfiguration]; + + [super i18nDidChange]; +} + +- (void)placeSubviews +{ + [super placeSubviews]; + + if (self.stateLabel.hidden) return; + + BOOL noConstrainsOnStatusLabel = self.stateLabel.constraints.count == 0; + + if (self.lastUpdatedTimeLabel.hidden) { + // 状态 + if (noConstrainsOnStatusLabel) self.stateLabel.frame = self.bounds; + } else { + CGFloat stateLabelH = self.mj_h * 0.5; + // 状态 + if (noConstrainsOnStatusLabel) { + self.stateLabel.mj_x = 0; + self.stateLabel.mj_y = 0; + self.stateLabel.mj_w = self.mj_w; + self.stateLabel.mj_h = stateLabelH; + } + + // 更新时间 + if (self.lastUpdatedTimeLabel.constraints.count == 0) { + self.lastUpdatedTimeLabel.mj_x = 0; + self.lastUpdatedTimeLabel.mj_y = stateLabelH; + self.lastUpdatedTimeLabel.mj_w = self.mj_w; + self.lastUpdatedTimeLabel.mj_h = self.mj_h - self.lastUpdatedTimeLabel.mj_y; + } + } +} + +- (void)setState:(MJRefreshState)state +{ + MJRefreshCheckState + + // 设置状态文字 + self.stateLabel.text = self.stateTitles[@(state)]; + + // 重新设置key(重新显示时间) + self.lastUpdatedTimeKey = self.lastUpdatedTimeKey; +} +@end + +#pragma mark - <<< 为 Swift 扩展链式语法 >>> - +@implementation MJRefreshStateHeader (ChainingGrammar) + +- (instancetype)modifyLastUpdatedTimeText:(NSString * _Nonnull (^)(NSDate * _Nullable))handler { + self.lastUpdatedTimeText = handler; + return self; +} + +@end diff --git a/Pods/MJRefresh/MJRefresh/Custom/Trailer/MJRefreshNormalTrailer.h b/Pods/MJRefresh/MJRefresh/Custom/Trailer/MJRefreshNormalTrailer.h new file mode 100644 index 0000000..97385d7 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Trailer/MJRefreshNormalTrailer.h @@ -0,0 +1,23 @@ +// +// MJRefreshNormalTrailer.h +// MJRefresh +// +// Created by kinarobin on 2020/5/3. +// Copyright © 2020 小码哥. All rights reserved. +// + +#if __has_include() +#import +#else +#import "MJRefreshStateTrailer.h" +#endif + +NS_ASSUME_NONNULL_BEGIN + +@interface MJRefreshNormalTrailer : MJRefreshStateTrailer + +@property (weak, nonatomic, readonly) UIImageView *arrowView; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/MJRefresh/MJRefresh/Custom/Trailer/MJRefreshNormalTrailer.m b/Pods/MJRefresh/MJRefresh/Custom/Trailer/MJRefreshNormalTrailer.m new file mode 100644 index 0000000..4b269f2 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Trailer/MJRefreshNormalTrailer.m @@ -0,0 +1,80 @@ +// +// MJRefreshNormalTrailer.m +// MJRefresh +// +// Created by kinarobin on 2020/5/3. +// Copyright © 2020 小码哥. All rights reserved. +// + +#import "MJRefreshNormalTrailer.h" +#import "NSBundle+MJRefresh.h" +#import "UIView+MJExtension.h" + +@interface MJRefreshNormalTrailer() { + __unsafe_unretained UIImageView *_arrowView; +} +@end + +@implementation MJRefreshNormalTrailer +#pragma mark - 懒加载子控件 +- (UIImageView *)arrowView { + if (!_arrowView) { + UIImageView *arrowView = [[UIImageView alloc] initWithImage:[NSBundle mj_trailArrowImage]]; + [self addSubview:_arrowView = arrowView]; + } + return _arrowView; +} + +- (void)placeSubviews { + [super placeSubviews]; + + CGSize arrowSize = self.arrowView.image.size; + // 箭头的中心点 + CGPoint selfCenter = CGPointMake(self.mj_w * 0.5, self.mj_h * 0.5); + CGPoint arrowCenter = CGPointMake(arrowSize.width * 0.5 + 5, self.mj_h * 0.5); + BOOL stateHidden = self.stateLabel.isHidden; + + if (self.arrowView.constraints.count == 0) { + self.arrowView.mj_size = self.arrowView.image.size; + self.arrowView.center = stateHidden ? selfCenter : arrowCenter ; + } + self.arrowView.tintColor = self.stateLabel.textColor; + + if (stateHidden) return; + + BOOL noConstrainsOnStatusLabel = self.stateLabel.constraints.count == 0; + CGFloat stateLabelW = ceil(self.stateLabel.font.pointSize); + // 状态 + if (noConstrainsOnStatusLabel) { + BOOL arrowHidden = self.arrowView.isHidden; + CGFloat stateCenterX = (self.mj_w + arrowSize.width) * 0.5; + self.stateLabel.center = arrowHidden ? selfCenter : CGPointMake(stateCenterX, self.mj_h * 0.5); + self.stateLabel.mj_size = CGSizeMake(stateLabelW, self.mj_h) ; + } +} + +- (void)setState:(MJRefreshState)state { + MJRefreshCheckState + // 根据状态做事情 + if (state == MJRefreshStateIdle) { + if (oldState == MJRefreshStateRefreshing) { + [UIView animateWithDuration:self.fastAnimationDuration animations:^{ + self.arrowView.transform = CGAffineTransformMakeRotation(M_PI); + } completion:^(BOOL finished) { + self.arrowView.transform = CGAffineTransformIdentity; + }]; + } else { + [UIView animateWithDuration:self.fastAnimationDuration animations:^{ + self.arrowView.transform = CGAffineTransformIdentity; + }]; + } + } else if (state == MJRefreshStatePulling) { + [UIView animateWithDuration:self.fastAnimationDuration animations:^{ + self.arrowView.transform = CGAffineTransformMakeRotation(M_PI); + }]; + } +} + + + +@end diff --git a/Pods/MJRefresh/MJRefresh/Custom/Trailer/MJRefreshStateTrailer.h b/Pods/MJRefresh/MJRefresh/Custom/Trailer/MJRefreshStateTrailer.h new file mode 100644 index 0000000..92ac203 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Trailer/MJRefreshStateTrailer.h @@ -0,0 +1,28 @@ +// +// MJRefreshStateTrailer.h +// MJRefresh +// +// Created by kinarobin on 2020/5/3. +// Copyright © 2020 小码哥. All rights reserved. +// + +#if __has_include() +#import +#else +#import "MJRefreshTrailer.h" +#endif + +NS_ASSUME_NONNULL_BEGIN + + +@interface MJRefreshStateTrailer : MJRefreshTrailer + +#pragma mark - 状态相关 +/** 显示刷新状态的label */ +@property (weak, nonatomic, readonly) UILabel *stateLabel; +/** 设置state状态下的文字 */ +- (instancetype)setTitle:(NSString *)title forState:(MJRefreshState)state; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/MJRefresh/MJRefresh/Custom/Trailer/MJRefreshStateTrailer.m b/Pods/MJRefresh/MJRefresh/Custom/Trailer/MJRefreshStateTrailer.m new file mode 100644 index 0000000..3ce0ba6 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Trailer/MJRefreshStateTrailer.m @@ -0,0 +1,87 @@ +// +// MJRefreshStateTrailer.m +// MJRefresh +// +// Created by kinarobin on 2020/5/3. +// Copyright © 2020 小码哥. All rights reserved. +// + +#import "MJRefreshStateTrailer.h" +#import "NSBundle+MJRefresh.h" +#import "UIView+MJExtension.h" + +@interface MJRefreshStateTrailer() { + /** 显示刷新状态的label */ + __unsafe_unretained UILabel *_stateLabel; +} +/** 所有状态对应的文字 */ +@property (strong, nonatomic) NSMutableDictionary *stateTitles; +@end + +@implementation MJRefreshStateTrailer +#pragma mark - 懒加载 +- (NSMutableDictionary *)stateTitles { + if (!_stateTitles) { + self.stateTitles = [NSMutableDictionary dictionary]; + } + return _stateTitles; +} + +- (UILabel *)stateLabel { + if (!_stateLabel) { + UILabel *stateLabel = [UILabel mj_label]; + stateLabel.numberOfLines = 0; + [self addSubview:_stateLabel = stateLabel]; + } + return _stateLabel; +} + +#pragma mark - 公共方法 +- (instancetype)setTitle:(NSString *)title forState:(MJRefreshState)state { + if (title == nil) return self; + self.stateTitles[@(state)] = title; + self.stateLabel.text = self.stateTitles[@(self.state)]; + return self; +} + +- (void)textConfiguration { + // 初始化文字 + [self setTitle:[NSBundle mj_localizedStringForKey:MJRefreshTrailerIdleText] forState:MJRefreshStateIdle]; + [self setTitle:[NSBundle mj_localizedStringForKey:MJRefreshTrailerPullingText] forState:MJRefreshStatePulling]; + [self setTitle:[NSBundle mj_localizedStringForKey:MJRefreshTrailerPullingText] forState:MJRefreshStateRefreshing]; +} + +#pragma mark - 覆盖父类的方法 +- (void)prepare { + [super prepare]; + + [self textConfiguration]; +} + +- (void)i18nDidChange { + [self textConfiguration]; + + [super i18nDidChange]; +} + +- (void)setState:(MJRefreshState)state { + MJRefreshCheckState + // 设置状态文字 + self.stateLabel.text = self.stateTitles[@(state)]; +} + +- (void)placeSubviews { + [super placeSubviews]; + + if (self.stateLabel.hidden) return; + + BOOL noConstrainsOnStatusLabel = self.stateLabel.constraints.count == 0; + CGFloat stateLabelW = ceil(self.stateLabel.font.pointSize); + // 状态 + if (noConstrainsOnStatusLabel) { + self.stateLabel.center = CGPointMake(self.mj_w * 0.5, self.mj_h * 0.5); + self.stateLabel.mj_size = CGSizeMake(stateLabelW, self.mj_h) ; + } +} + +@end diff --git a/Pods/MJRefresh/MJRefresh/MJRefresh.bundle/arrow@2x.png b/Pods/MJRefresh/MJRefresh/MJRefresh.bundle/arrow@2x.png new file mode 100755 index 0000000..b1078de Binary files /dev/null and b/Pods/MJRefresh/MJRefresh/MJRefresh.bundle/arrow@2x.png differ diff --git a/Pods/MJRefresh/MJRefresh/MJRefresh.bundle/en.lproj/Localizable.strings b/Pods/MJRefresh/MJRefresh/MJRefresh.bundle/en.lproj/Localizable.strings new file mode 100644 index 0000000..bf56786 Binary files /dev/null and b/Pods/MJRefresh/MJRefresh/MJRefresh.bundle/en.lproj/Localizable.strings differ diff --git a/Pods/MJRefresh/MJRefresh/MJRefresh.bundle/ko.lproj/Localizable.strings b/Pods/MJRefresh/MJRefresh/MJRefresh.bundle/ko.lproj/Localizable.strings new file mode 100644 index 0000000..ac25579 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/MJRefresh.bundle/ko.lproj/Localizable.strings @@ -0,0 +1,16 @@ +"MJRefreshHeaderIdleText" = "아래로 당겨 새로고침"; +"MJRefreshHeaderPullingText" = "놓으면 새로고침"; +"MJRefreshHeaderRefreshingText" = "로딩중..."; + +"MJRefreshAutoFooterIdleText" = "탭 또는 위로 당겨 로드함"; +"MJRefreshAutoFooterRefreshingText" = "로딩중..."; +"MJRefreshAutoFooterNoMoreDataText" = "더이상 데이터 없음"; + +"MJRefreshBackFooterIdleText" = "위로 당겨 더 로드 가능"; +"MJRefreshBackFooterPullingText" = "놓으면 더 로드됨."; +"MJRefreshBackFooterRefreshingText" = "로딩중..."; +"MJRefreshBackFooterNoMoreDataText" = "더이상 데이터 없음"; + +"MJRefreshHeaderLastTimeText" = "마지막 업데이트: "; +"MJRefreshHeaderDateTodayText" = "오늘"; +"MJRefreshHeaderNoneLastDateText" = "기록 없음"; diff --git a/Pods/MJRefresh/MJRefresh/MJRefresh.bundle/ru.lproj/Localizable.strings b/Pods/MJRefresh/MJRefresh/MJRefresh.bundle/ru.lproj/Localizable.strings new file mode 100644 index 0000000..7890e7b Binary files /dev/null and b/Pods/MJRefresh/MJRefresh/MJRefresh.bundle/ru.lproj/Localizable.strings differ diff --git a/Pods/MJRefresh/MJRefresh/MJRefresh.bundle/trail_arrow@2x.png b/Pods/MJRefresh/MJRefresh/MJRefresh.bundle/trail_arrow@2x.png new file mode 100644 index 0000000..a45f933 Binary files /dev/null and b/Pods/MJRefresh/MJRefresh/MJRefresh.bundle/trail_arrow@2x.png differ diff --git a/Pods/MJRefresh/MJRefresh/MJRefresh.bundle/uk.lproj/Localizable.strings b/Pods/MJRefresh/MJRefresh/MJRefresh.bundle/uk.lproj/Localizable.strings new file mode 100644 index 0000000..3557940 Binary files /dev/null and b/Pods/MJRefresh/MJRefresh/MJRefresh.bundle/uk.lproj/Localizable.strings differ diff --git a/Pods/MJRefresh/MJRefresh/MJRefresh.bundle/zh-Hans.lproj/Localizable.strings b/Pods/MJRefresh/MJRefresh/MJRefresh.bundle/zh-Hans.lproj/Localizable.strings new file mode 100644 index 0000000..1066e3d Binary files /dev/null and b/Pods/MJRefresh/MJRefresh/MJRefresh.bundle/zh-Hans.lproj/Localizable.strings differ diff --git a/Pods/MJRefresh/MJRefresh/MJRefresh.bundle/zh-Hant.lproj/Localizable.strings b/Pods/MJRefresh/MJRefresh/MJRefresh.bundle/zh-Hant.lproj/Localizable.strings new file mode 100644 index 0000000..17417b5 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/MJRefresh.bundle/zh-Hant.lproj/Localizable.strings @@ -0,0 +1,19 @@ +"MJRefreshHeaderIdleText" = "下拉可以刷新"; +"MJRefreshHeaderPullingText" = "鬆開立即刷新"; +"MJRefreshHeaderRefreshingText" = "正在刷新數據中..."; + +"MJRefreshTrailerIdleText" = "滑動查看圖文詳情"; +"MJRefreshTrailerPullingText" = "釋放查看圖文詳情"; + +"MJRefreshAutoFooterIdleText" = "點擊或上拉加載更多"; +"MJRefreshAutoFooterRefreshingText" = "正在加載更多的數據..."; +"MJRefreshAutoFooterNoMoreDataText" = "已經全部加載完畢"; + +"MJRefreshBackFooterIdleText" = "上拉可以加載更多"; +"MJRefreshBackFooterPullingText" = "鬆開立即加載更多"; +"MJRefreshBackFooterRefreshingText" = "正在加載更多的數據..."; +"MJRefreshBackFooterNoMoreDataText" = "已經全部加載完畢"; + +"MJRefreshHeaderLastTimeText" = "最後更新:"; +"MJRefreshHeaderDateTodayText" = "今天"; +"MJRefreshHeaderNoneLastDateText" = "無記錄"; diff --git a/Pods/MJRefresh/MJRefresh/MJRefresh.h b/Pods/MJRefresh/MJRefresh/MJRefresh.h new file mode 100644 index 0000000..d878212 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/MJRefresh.h @@ -0,0 +1,42 @@ +// 代码地址: https://github.com/CoderMJLee/MJRefresh + +#import + +#if __has_include() +FOUNDATION_EXPORT double MJRefreshVersionNumber; +FOUNDATION_EXPORT const unsigned char MJRefreshVersionString[]; + +#import +#import +#import + +#import +#import + +#import +#import +#import +#import + +#import +#import +#import +#import +#else +#import "UIScrollView+MJRefresh.h" +#import "UIScrollView+MJExtension.h" +#import "UIView+MJExtension.h" + +#import "MJRefreshNormalHeader.h" +#import "MJRefreshGifHeader.h" + +#import "MJRefreshBackNormalFooter.h" +#import "MJRefreshBackGifFooter.h" +#import "MJRefreshAutoNormalFooter.h" +#import "MJRefreshAutoGifFooter.h" + +#import "MJRefreshNormalTrailer.h" +#import "MJRefreshConfig.h" +#import "NSBundle+MJRefresh.h" +#import "MJRefreshConst.h" +#endif diff --git a/Pods/MJRefresh/MJRefresh/MJRefreshConfig.h b/Pods/MJRefresh/MJRefresh/MJRefreshConfig.h new file mode 100644 index 0000000..b2c808f --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/MJRefreshConfig.h @@ -0,0 +1,36 @@ +// +// MJRefreshConfig.h +// +// Created by Frank on 2018/11/27. +// Copyright © 2018 小码哥. All rights reserved. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface MJRefreshConfig : NSObject + +/** 默认使用的语言版本, 默认为 nil. 将随系统的语言自动改变 */ +@property (copy, nonatomic, nullable) NSString *languageCode; + +/** 默认使用的语言资源文件名, 默认为 nil, 即默认的 Localizable.strings. + + - Attention: 文件名不包含后缀.strings + */ +@property (copy, nonatomic, nullable) NSString *i18nFilename; +/** i18n 多语言资源加载自定义 Bundle. + + - Attention: 默认为 nil 采用内置逻辑. 这里设置后将忽略内置逻辑的多语言模式, 采用自定义的多语言 bundle + */ +@property (nonatomic, nullable) NSBundle *i18nBundle; + +/** Singleton Config instance */ +@property (class, nonatomic, readonly) MJRefreshConfig *defaultConfig; + +- (instancetype)init NS_UNAVAILABLE; ++ (instancetype)new NS_UNAVAILABLE; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/MJRefresh/MJRefresh/MJRefreshConfig.m b/Pods/MJRefresh/MJRefresh/MJRefreshConfig.m new file mode 100644 index 0000000..680b95a --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/MJRefreshConfig.m @@ -0,0 +1,42 @@ +// +// MJRefreshConfig.m +// +// Created by Frank on 2018/11/27. +// Copyright © 2018 小码哥. All rights reserved. +// + +#import "MJRefreshConfig.h" +#import "MJRefreshConst.h" +#import "NSBundle+MJRefresh.h" + +@interface MJRefreshConfig (Bundle) + ++ (void)resetLanguageResourceCache; + +@end + +@implementation MJRefreshConfig + +static MJRefreshConfig *mj_RefreshConfig = nil; + ++ (instancetype)defaultConfig { + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + mj_RefreshConfig = [[self alloc] init]; + }); + return mj_RefreshConfig; +} + +- (void)setLanguageCode:(NSString *)languageCode { + if ([languageCode isEqualToString:_languageCode]) { + return; + } + + _languageCode = languageCode; + // 重置语言资源 + [MJRefreshConfig resetLanguageResourceCache]; + [NSNotificationCenter.defaultCenter + postNotificationName:MJRefreshDidChangeLanguageNotification object:self]; +} + +@end diff --git a/Pods/MJRefresh/MJRefresh/MJRefreshConst.h b/Pods/MJRefresh/MJRefresh/MJRefreshConst.h new file mode 100644 index 0000000..6881115 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/MJRefreshConst.h @@ -0,0 +1,115 @@ +// 代码地址: https://github.com/CoderMJLee/MJRefresh +#import +#import +#import + +// 弱引用 +#define MJWeakSelf __weak typeof(self) weakSelf = self; + +// 日志输出 +#ifdef DEBUG +#define MJRefreshLog(...) NSLog(__VA_ARGS__) +#else +#define MJRefreshLog(...) +#endif + +// 过期提醒 +#define MJRefreshDeprecated(DESCRIPTION) __attribute__((deprecated(DESCRIPTION))) + +// 运行时objc_msgSend +#define MJRefreshMsgSend(...) ((void (*)(void *, SEL, UIView *))objc_msgSend)(__VA_ARGS__) +#define MJRefreshMsgTarget(target) (__bridge void *)(target) + +// RGB颜色 +#define MJRefreshColor(r, g, b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1.0] + +// 文字颜色 +#define MJRefreshLabelTextColor MJRefreshColor(90, 90, 90) + +// 字体大小 +#define MJRefreshLabelFont [UIFont boldSystemFontOfSize:14] + +// 常量 +UIKIT_EXTERN const CGFloat MJRefreshLabelLeftInset; +UIKIT_EXTERN const CGFloat MJRefreshHeaderHeight; +UIKIT_EXTERN const CGFloat MJRefreshFooterHeight; +UIKIT_EXTERN const CGFloat MJRefreshTrailWidth; +UIKIT_EXTERN const CGFloat MJRefreshFastAnimationDuration; +UIKIT_EXTERN const CGFloat MJRefreshSlowAnimationDuration; + + +UIKIT_EXTERN NSString *const MJRefreshKeyPathContentOffset; +UIKIT_EXTERN NSString *const MJRefreshKeyPathContentSize; +UIKIT_EXTERN NSString *const MJRefreshKeyPathContentInset; +UIKIT_EXTERN NSString *const MJRefreshKeyPathPanState; + +UIKIT_EXTERN NSString *const MJRefreshHeaderLastUpdatedTimeKey; + +UIKIT_EXTERN NSString *const MJRefreshHeaderIdleText; +UIKIT_EXTERN NSString *const MJRefreshHeaderPullingText; +UIKIT_EXTERN NSString *const MJRefreshHeaderRefreshingText; + +UIKIT_EXTERN NSString *const MJRefreshTrailerIdleText; +UIKIT_EXTERN NSString *const MJRefreshTrailerPullingText; + +UIKIT_EXTERN NSString *const MJRefreshAutoFooterIdleText; +UIKIT_EXTERN NSString *const MJRefreshAutoFooterRefreshingText; +UIKIT_EXTERN NSString *const MJRefreshAutoFooterNoMoreDataText; + +UIKIT_EXTERN NSString *const MJRefreshBackFooterIdleText; +UIKIT_EXTERN NSString *const MJRefreshBackFooterPullingText; +UIKIT_EXTERN NSString *const MJRefreshBackFooterRefreshingText; +UIKIT_EXTERN NSString *const MJRefreshBackFooterNoMoreDataText; + +UIKIT_EXTERN NSString *const MJRefreshHeaderLastTimeText; +UIKIT_EXTERN NSString *const MJRefreshHeaderDateTodayText; +UIKIT_EXTERN NSString *const MJRefreshHeaderNoneLastDateText; + +UIKIT_EXTERN NSString *const MJRefreshDidChangeLanguageNotification; + +// 状态检查 +#define MJRefreshCheckState \ +MJRefreshState oldState = self.state; \ +if (state == oldState) return; \ +[super setState:state]; + +// 异步主线程执行,不强持有Self +#define MJRefreshDispatchAsyncOnMainQueue(x) \ +__weak typeof(self) weakSelf = self; \ +dispatch_async(dispatch_get_main_queue(), ^{ \ +typeof(weakSelf) self = weakSelf; \ +{x} \ +}); + +/// 替换方法实现 +/// @param _fromClass 源类 +/// @param _originSelector 源类的 Selector +/// @param _toClass 目标类 +/// @param _newSelector 目标类的 Selector +CG_INLINE BOOL MJRefreshExchangeImplementations( + Class _fromClass, SEL _originSelector, + Class _toClass, SEL _newSelector) { + if (!_fromClass || !_toClass) { + return NO; + } + + Method oriMethod = class_getInstanceMethod(_fromClass, _originSelector); + Method newMethod = class_getInstanceMethod(_toClass, _newSelector); + if (!newMethod) { + return NO; + } + + BOOL isAddedMethod = class_addMethod(_fromClass, _originSelector, + method_getImplementation(newMethod), + method_getTypeEncoding(newMethod)); + if (isAddedMethod) { + // 如果 class_addMethod 成功了,说明之前 fromClass 里并不存在 originSelector,所以要用一个空的方法代替它,以避免 class_replaceMethod 后,后续 toClass 的这个方法被调用时可能会 crash + IMP emptyIMP = imp_implementationWithBlock(^(id selfObject) {}); + IMP oriMethodIMP = method_getImplementation(oriMethod) ?: emptyIMP; + const char *oriMethodTypeEncoding = method_getTypeEncoding(oriMethod) ?: "v@:"; + class_replaceMethod(_toClass, _newSelector, oriMethodIMP, oriMethodTypeEncoding); + } else { + method_exchangeImplementations(oriMethod, newMethod); + } + return YES; +} diff --git a/Pods/MJRefresh/MJRefresh/MJRefreshConst.m b/Pods/MJRefresh/MJRefresh/MJRefreshConst.m new file mode 100644 index 0000000..704d4c7 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/MJRefreshConst.m @@ -0,0 +1,39 @@ +// 代码地址: https://github.com/CoderMJLee/MJRefresh +#import + +const CGFloat MJRefreshLabelLeftInset = 25; +const CGFloat MJRefreshHeaderHeight = 54.0; +const CGFloat MJRefreshFooterHeight = 44.0; +const CGFloat MJRefreshTrailWidth = 60.0; +const CGFloat MJRefreshFastAnimationDuration = 0.25; +const CGFloat MJRefreshSlowAnimationDuration = 0.4; + + +NSString *const MJRefreshKeyPathContentOffset = @"contentOffset"; +NSString *const MJRefreshKeyPathContentInset = @"contentInset"; +NSString *const MJRefreshKeyPathContentSize = @"contentSize"; +NSString *const MJRefreshKeyPathPanState = @"state"; + +NSString *const MJRefreshHeaderLastUpdatedTimeKey = @"MJRefreshHeaderLastUpdatedTimeKey"; + +NSString *const MJRefreshHeaderIdleText = @"MJRefreshHeaderIdleText"; +NSString *const MJRefreshHeaderPullingText = @"MJRefreshHeaderPullingText"; +NSString *const MJRefreshHeaderRefreshingText = @"MJRefreshHeaderRefreshingText"; + +NSString *const MJRefreshTrailerIdleText = @"MJRefreshTrailerIdleText"; +NSString *const MJRefreshTrailerPullingText = @"MJRefreshTrailerPullingText"; + +NSString *const MJRefreshAutoFooterIdleText = @"MJRefreshAutoFooterIdleText"; +NSString *const MJRefreshAutoFooterRefreshingText = @"MJRefreshAutoFooterRefreshingText"; +NSString *const MJRefreshAutoFooterNoMoreDataText = @"MJRefreshAutoFooterNoMoreDataText"; + +NSString *const MJRefreshBackFooterIdleText = @"MJRefreshBackFooterIdleText"; +NSString *const MJRefreshBackFooterPullingText = @"MJRefreshBackFooterPullingText"; +NSString *const MJRefreshBackFooterRefreshingText = @"MJRefreshBackFooterRefreshingText"; +NSString *const MJRefreshBackFooterNoMoreDataText = @"MJRefreshBackFooterNoMoreDataText"; + +NSString *const MJRefreshHeaderLastTimeText = @"MJRefreshHeaderLastTimeText"; +NSString *const MJRefreshHeaderDateTodayText = @"MJRefreshHeaderDateTodayText"; +NSString *const MJRefreshHeaderNoneLastDateText = @"MJRefreshHeaderNoneLastDateText"; + +NSString *const MJRefreshDidChangeLanguageNotification = @"MJRefreshDidChangeLanguageNotification"; diff --git a/Pods/MJRefresh/MJRefresh/NSBundle+MJRefresh.h b/Pods/MJRefresh/MJRefresh/NSBundle+MJRefresh.h new file mode 100644 index 0000000..a1f56f4 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/NSBundle+MJRefresh.h @@ -0,0 +1,21 @@ +// +// NSBundle+MJRefresh.h +// MJRefresh +// +// Created by MJ Lee on 16/6/13. +// Copyright © 2016年 小码哥. All rights reserved. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface NSBundle (MJRefresh) ++ (instancetype)mj_refreshBundle; ++ (UIImage *)mj_arrowImage; ++ (UIImage *)mj_trailArrowImage; ++ (NSString *)mj_localizedStringForKey:(NSString *)key value:(nullable NSString *)value; ++ (NSString *)mj_localizedStringForKey:(NSString *)key; +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/MJRefresh/MJRefresh/NSBundle+MJRefresh.m b/Pods/MJRefresh/MJRefresh/NSBundle+MJRefresh.m new file mode 100644 index 0000000..c19cbe8 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/NSBundle+MJRefresh.m @@ -0,0 +1,116 @@ +// +// NSBundle+MJRefresh.m +// MJRefresh +// +// Created by MJ Lee on 16/6/13. +// Copyright © 2016年 小码哥. All rights reserved. +// + +#import "NSBundle+MJRefresh.h" +#import "MJRefreshComponent.h" +#import "MJRefreshConfig.h" + +static NSBundle *mj_defaultI18nBundle = nil; +static NSBundle *mj_systemI18nBundle = nil; + +@implementation NSBundle (MJRefresh) ++ (instancetype)mj_refreshBundle +{ + static NSBundle *refreshBundle = nil; + if (refreshBundle == nil) { +#ifdef SWIFT_PACKAGE + NSBundle *containnerBundle = SWIFTPM_MODULE_BUNDLE; +#else + NSBundle *containnerBundle = [NSBundle bundleForClass:[MJRefreshComponent class]]; +#endif + refreshBundle = [NSBundle bundleWithPath:[containnerBundle pathForResource:@"MJRefresh" ofType:@"bundle"]]; + } + return refreshBundle; +} + ++ (UIImage *)mj_arrowImage +{ + static UIImage *arrowImage = nil; + if (arrowImage == nil) { + arrowImage = [[UIImage imageWithContentsOfFile:[[self mj_refreshBundle] pathForResource:@"arrow@2x" ofType:@"png"]] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; + } + return arrowImage; +} + ++ (UIImage *)mj_trailArrowImage { + static UIImage *arrowImage = nil; + if (arrowImage == nil) { + arrowImage = [[UIImage imageWithContentsOfFile:[[self mj_refreshBundle] pathForResource:@"trail_arrow@2x" ofType:@"png"]] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; + } + return arrowImage; +} + ++ (NSString *)mj_localizedStringForKey:(NSString *)key +{ + return [self mj_localizedStringForKey:key value:nil]; +} + ++ (NSString *)mj_localizedStringForKey:(NSString *)key value:(NSString *)value +{ + NSString *table = MJRefreshConfig.defaultConfig.i18nFilename; + + // 如果没有缓存, 则走初始化逻辑 + if (mj_defaultI18nBundle == nil) { + NSString *language = MJRefreshConfig.defaultConfig.languageCode; + // 如果配置中没有配置语言 + if (!language) { + language = [NSLocale preferredLanguages].firstObject; + } + NSBundle *bundle = MJRefreshConfig.defaultConfig.i18nBundle; + // 首先优先使用公共配置中的 i18nBundle, 如果为空则使用 mainBundle + bundle = bundle ? bundle : NSBundle.mainBundle; + // 按语言选取语言包 + NSString *i18nFolderPath = [bundle pathForResource:language ofType:@"lproj"]; + mj_defaultI18nBundle = [NSBundle bundleWithPath:i18nFolderPath]; + // 检查语言包, 如果没有查找到, 则默认使用 mainBundle + mj_defaultI18nBundle = mj_defaultI18nBundle ? mj_defaultI18nBundle : NSBundle.mainBundle; + + // 获取 MJRefresh 自有的语言包 + if (mj_systemI18nBundle == nil) { + mj_systemI18nBundle = [self mj_defaultI18nBundleWithLanguage:language]; + } + } + // 首先在 MJRefresh 内置语言文件中寻找 + value = [mj_systemI18nBundle localizedStringForKey:key value:value table:nil]; + // 然后在 MainBundle 对应语言文件中寻找 + value = [mj_defaultI18nBundle localizedStringForKey:key value:value table:table]; + return value; +} + ++ (NSBundle *)mj_defaultI18nBundleWithLanguage:(NSString *)language { + if ([language hasPrefix:@"en"]) { + language = @"en"; + } else if ([language hasPrefix:@"zh"]) { + if ([language rangeOfString:@"Hans"].location != NSNotFound) { + language = @"zh-Hans"; // 简体中文 + } else { // zh-Hant\zh-HK\zh-TW + language = @"zh-Hant"; // 繁體中文 + } + } else if ([language hasPrefix:@"ko"]) { + language = @"ko"; + } else if ([language hasPrefix:@"ru"]) { + language = @"ru"; + } else if ([language hasPrefix:@"uk"]) { + language = @"uk"; + } else { + language = @"en"; + } + + // 从MJRefresh.bundle中查找资源 + return [NSBundle bundleWithPath:[[NSBundle mj_refreshBundle] pathForResource:language ofType:@"lproj"]]; +} +@end + +@implementation MJRefreshConfig (Bundle) + ++ (void)resetLanguageResourceCache { + mj_defaultI18nBundle = nil; + mj_systemI18nBundle = nil; +} + +@end diff --git a/Pods/MJRefresh/MJRefresh/PrivacyInfo.xcprivacy b/Pods/MJRefresh/MJRefresh/PrivacyInfo.xcprivacy new file mode 100644 index 0000000..2d55cfe --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/PrivacyInfo.xcprivacy @@ -0,0 +1,23 @@ + + + + + NSPrivacyTracking + + NSPrivacyTrackingDomains + + NSPrivacyAccessedAPITypes + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategoryUserDefaults + NSPrivacyAccessedAPITypeReasons + + CA92.1 + + + + NSPrivacyCollectedDataTypes + + + diff --git a/Pods/MJRefresh/MJRefresh/UICollectionViewLayout+MJRefresh.h b/Pods/MJRefresh/MJRefresh/UICollectionViewLayout+MJRefresh.h new file mode 100644 index 0000000..df0423d --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/UICollectionViewLayout+MJRefresh.h @@ -0,0 +1,20 @@ +// +// UICollectionViewLayout+MJRefresh.h +// +// 该类是用来解决 Footer 在底端加载完成后, 仍停留在原处的 bug. +// 此问题出现在 iOS 14 及以下系统上. +// Reference: https://github.com/CoderMJLee/MJRefresh/issues/1552 +// +// Created by jiasong on 2021/11/15. +// Copyright © 2021 小码哥. All rights reserved. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface UICollectionViewLayout (MJRefresh) + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/MJRefresh/MJRefresh/UICollectionViewLayout+MJRefresh.m b/Pods/MJRefresh/MJRefresh/UICollectionViewLayout+MJRefresh.m new file mode 100644 index 0000000..00d030e --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/UICollectionViewLayout+MJRefresh.m @@ -0,0 +1,45 @@ +// +// UICollectionViewLayout+MJRefresh.m +// +// 该类是用来解决 Footer 在底端加载完成后, 仍停留在原处的 bug. +// 此问题出现在 iOS 14 及以下系统上. +// Reference: https://github.com/CoderMJLee/MJRefresh/issues/1552 +// +// Created by jiasong on 2021/11/15. +// Copyright © 2021 小码哥. All rights reserved. +// + +#import "UICollectionViewLayout+MJRefresh.h" +#import "MJRefreshConst.h" +#import "MJRefreshFooter.h" +#import "UIScrollView+MJRefresh.h" + +@implementation UICollectionViewLayout (MJRefresh) + ++ (void)load { + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + MJRefreshExchangeImplementations(self.class, @selector(finalizeCollectionViewUpdates), + self.class, @selector(mj_finalizeCollectionViewUpdates)); + }); +} + +- (void)mj_finalizeCollectionViewUpdates { + [self mj_finalizeCollectionViewUpdates]; + + __kindof MJRefreshFooter *footer = self.collectionView.mj_footer; + CGSize newSize = self.collectionViewContentSize; + CGSize oldSize = self.collectionView.contentSize; + if (footer != nil && !CGSizeEqualToSize(newSize, oldSize)) { + NSDictionary *changed = @{ + NSKeyValueChangeNewKey: [NSValue valueWithCGSize:newSize], + NSKeyValueChangeOldKey: [NSValue valueWithCGSize:oldSize], + }; + [CATransaction begin]; + [CATransaction setDisableActions:YES]; + [footer scrollViewContentSizeDidChange:changed]; + [CATransaction commit]; + } +} + +@end diff --git a/Pods/MJRefresh/MJRefresh/UIScrollView+MJExtension.h b/Pods/MJRefresh/MJRefresh/UIScrollView+MJExtension.h new file mode 100644 index 0000000..1b46d59 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/UIScrollView+MJExtension.h @@ -0,0 +1,28 @@ +// 代码地址: https://github.com/CoderMJLee/MJRefresh +// UIScrollView+Extension.h +// MJRefresh +// +// Created by MJ Lee on 14-5-28. +// Copyright (c) 2014年 小码哥. All rights reserved. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface UIScrollView (MJExtension) +@property (readonly, nonatomic) UIEdgeInsets mj_inset; + +@property (assign, nonatomic) CGFloat mj_insetT; +@property (assign, nonatomic) CGFloat mj_insetB; +@property (assign, nonatomic) CGFloat mj_insetL; +@property (assign, nonatomic) CGFloat mj_insetR; + +@property (assign, nonatomic) CGFloat mj_offsetX; +@property (assign, nonatomic) CGFloat mj_offsetY; + +@property (assign, nonatomic) CGFloat mj_contentW; +@property (assign, nonatomic) CGFloat mj_contentH; +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/MJRefresh/MJRefresh/UIScrollView+MJExtension.m b/Pods/MJRefresh/MJRefresh/UIScrollView+MJExtension.m new file mode 100644 index 0000000..1c43721 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/UIScrollView+MJExtension.m @@ -0,0 +1,153 @@ +// 代码地址: https://github.com/CoderMJLee/MJRefresh +// UIScrollView+Extension.m +// MJRefresh +// +// Created by MJ Lee on 14-5-28. +// Copyright (c) 2014年 小码哥. All rights reserved. +// + +#import "UIScrollView+MJExtension.h" +#import + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability-new" + +@implementation UIScrollView (MJExtension) + +static BOOL respondsToAdjustedContentInset_; + ++ (void)load +{ + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + respondsToAdjustedContentInset_ = [self instancesRespondToSelector:@selector(adjustedContentInset)]; + }); +} + +- (UIEdgeInsets)mj_inset +{ +#ifdef __IPHONE_11_0 + if (respondsToAdjustedContentInset_) { + return self.adjustedContentInset; + } +#endif + return self.contentInset; +} + +- (void)setMj_insetT:(CGFloat)mj_insetT +{ + UIEdgeInsets inset = self.contentInset; + inset.top = mj_insetT; +#ifdef __IPHONE_11_0 + if (respondsToAdjustedContentInset_) { + inset.top -= (self.adjustedContentInset.top - self.contentInset.top); + } +#endif + self.contentInset = inset; +} + +- (CGFloat)mj_insetT +{ + return self.mj_inset.top; +} + +- (void)setMj_insetB:(CGFloat)mj_insetB +{ + UIEdgeInsets inset = self.contentInset; + inset.bottom = mj_insetB; +#ifdef __IPHONE_11_0 + if (respondsToAdjustedContentInset_) { + inset.bottom -= (self.adjustedContentInset.bottom - self.contentInset.bottom); + } +#endif + self.contentInset = inset; +} + +- (CGFloat)mj_insetB +{ + return self.mj_inset.bottom; +} + +- (void)setMj_insetL:(CGFloat)mj_insetL +{ + UIEdgeInsets inset = self.contentInset; + inset.left = mj_insetL; +#ifdef __IPHONE_11_0 + if (respondsToAdjustedContentInset_) { + inset.left -= (self.adjustedContentInset.left - self.contentInset.left); + } +#endif + self.contentInset = inset; +} + +- (CGFloat)mj_insetL +{ + return self.mj_inset.left; +} + +- (void)setMj_insetR:(CGFloat)mj_insetR +{ + UIEdgeInsets inset = self.contentInset; + inset.right = mj_insetR; +#ifdef __IPHONE_11_0 + if (respondsToAdjustedContentInset_) { + inset.right -= (self.adjustedContentInset.right - self.contentInset.right); + } +#endif + self.contentInset = inset; +} + +- (CGFloat)mj_insetR +{ + return self.mj_inset.right; +} + +- (void)setMj_offsetX:(CGFloat)mj_offsetX +{ + CGPoint offset = self.contentOffset; + offset.x = mj_offsetX; + self.contentOffset = offset; +} + +- (CGFloat)mj_offsetX +{ + return self.contentOffset.x; +} + +- (void)setMj_offsetY:(CGFloat)mj_offsetY +{ + CGPoint offset = self.contentOffset; + offset.y = mj_offsetY; + self.contentOffset = offset; +} + +- (CGFloat)mj_offsetY +{ + return self.contentOffset.y; +} + +- (void)setMj_contentW:(CGFloat)mj_contentW +{ + CGSize size = self.contentSize; + size.width = mj_contentW; + self.contentSize = size; +} + +- (CGFloat)mj_contentW +{ + return self.contentSize.width; +} + +- (void)setMj_contentH:(CGFloat)mj_contentH +{ + CGSize size = self.contentSize; + size.height = mj_contentH; + self.contentSize = size; +} + +- (CGFloat)mj_contentH +{ + return self.contentSize.height; +} +@end +#pragma clang diagnostic pop diff --git a/Pods/MJRefresh/MJRefresh/UIScrollView+MJRefresh.h b/Pods/MJRefresh/MJRefresh/UIScrollView+MJRefresh.h new file mode 100644 index 0000000..8ce3282 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/UIScrollView+MJRefresh.h @@ -0,0 +1,36 @@ +// 代码地址: https://github.com/CoderMJLee/MJRefresh +// UIScrollView+MJRefresh.h +// MJRefresh +// +// Created by MJ Lee on 15/3/4. +// Copyright (c) 2015年 小码哥. All rights reserved. +// 给ScrollView增加下拉刷新、上拉刷新、 左滑刷新的功能 + +#import +#if __has_include() +#import +#else +#import "MJRefreshConst.h" +#endif + +@class MJRefreshHeader, MJRefreshFooter, MJRefreshTrailer; + +NS_ASSUME_NONNULL_BEGIN + +@interface UIScrollView (MJRefresh) +/** 下拉刷新控件 */ +@property (strong, nonatomic, nullable) MJRefreshHeader *mj_header; +@property (strong, nonatomic, nullable) MJRefreshHeader *header MJRefreshDeprecated("使用mj_header"); +/** 上拉刷新控件 */ +@property (strong, nonatomic, nullable) MJRefreshFooter *mj_footer; +@property (strong, nonatomic, nullable) MJRefreshFooter *footer MJRefreshDeprecated("使用mj_footer"); + +/** 左滑刷新控件 */ +@property (strong, nonatomic, nullable) MJRefreshTrailer *mj_trailer; + +#pragma mark - other +- (NSInteger)mj_totalDataCount; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/MJRefresh/MJRefresh/UIScrollView+MJRefresh.m b/Pods/MJRefresh/MJRefresh/UIScrollView+MJRefresh.m new file mode 100644 index 0000000..3bb85da --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/UIScrollView+MJRefresh.m @@ -0,0 +1,120 @@ +// 代码地址: https://github.com/CoderMJLee/MJRefresh +// UIScrollView+MJRefresh.m +// MJRefresh +// +// Created by MJ Lee on 15/3/4. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "UIScrollView+MJRefresh.h" +#import "MJRefreshHeader.h" +#import "MJRefreshFooter.h" +#import "MJRefreshTrailer.h" +#import + +@implementation UIScrollView (MJRefresh) + +#pragma mark - header +static const char MJRefreshHeaderKey = '\0'; +- (void)setMj_header:(MJRefreshHeader *)mj_header +{ + if (mj_header != self.mj_header) { + // 删除旧的,添加新的 + [self.mj_header removeFromSuperview]; + + if (mj_header) { + [self insertSubview:mj_header atIndex:0]; + } + // 存储新的 + objc_setAssociatedObject(self, &MJRefreshHeaderKey, + mj_header, OBJC_ASSOCIATION_RETAIN); + } +} + +- (MJRefreshHeader *)mj_header +{ + return objc_getAssociatedObject(self, &MJRefreshHeaderKey); +} + +#pragma mark - footer +static const char MJRefreshFooterKey = '\0'; +- (void)setMj_footer:(MJRefreshFooter *)mj_footer +{ + if (mj_footer != self.mj_footer) { + // 删除旧的,添加新的 + [self.mj_footer removeFromSuperview]; + if (mj_footer) { + [self insertSubview:mj_footer atIndex:0]; + } + // 存储新的 + objc_setAssociatedObject(self, &MJRefreshFooterKey, + mj_footer, OBJC_ASSOCIATION_RETAIN); + } +} + +- (MJRefreshFooter *)mj_footer +{ + return objc_getAssociatedObject(self, &MJRefreshFooterKey); +} + +#pragma mark - footer +static const char MJRefreshTrailerKey = '\0'; +- (void)setMj_trailer:(MJRefreshTrailer *)mj_trailer { + if (mj_trailer != self.mj_trailer) { + // 删除旧的,添加新的 + [self.mj_trailer removeFromSuperview]; + if (mj_trailer) { + [self insertSubview:mj_trailer atIndex:0]; + } + // 存储新的 + objc_setAssociatedObject(self, &MJRefreshTrailerKey, + mj_trailer, OBJC_ASSOCIATION_RETAIN); + } +} + +- (MJRefreshTrailer *)mj_trailer { + return objc_getAssociatedObject(self, &MJRefreshTrailerKey); +} + +#pragma mark - 过期 +- (void)setFooter:(MJRefreshFooter *)footer +{ + self.mj_footer = footer; +} + +- (MJRefreshFooter *)footer +{ + return self.mj_footer; +} + +- (void)setHeader:(MJRefreshHeader *)header +{ + self.mj_header = header; +} + +- (MJRefreshHeader *)header +{ + return self.mj_header; +} + +#pragma mark - other +- (NSInteger)mj_totalDataCount +{ + NSInteger totalCount = 0; + if ([self isKindOfClass:[UITableView class]]) { + UITableView *tableView = (UITableView *)self; + + for (NSInteger section = 0; section < tableView.numberOfSections; section++) { + totalCount += [tableView numberOfRowsInSection:section]; + } + } else if ([self isKindOfClass:[UICollectionView class]]) { + UICollectionView *collectionView = (UICollectionView *)self; + + for (NSInteger section = 0; section < collectionView.numberOfSections; section++) { + totalCount += [collectionView numberOfItemsInSection:section]; + } + } + return totalCount; +} + +@end diff --git a/Pods/MJRefresh/MJRefresh/UIView+MJExtension.h b/Pods/MJRefresh/MJRefresh/UIView+MJExtension.h new file mode 100644 index 0000000..0ac0968 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/UIView+MJExtension.h @@ -0,0 +1,22 @@ +// 代码地址: https://github.com/CoderMJLee/MJRefresh +// UIView+Extension.h +// MJRefresh +// +// Created by MJ Lee on 14-5-28. +// Copyright (c) 2014年 小码哥. All rights reserved. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface UIView (MJExtension) +@property (assign, nonatomic) CGFloat mj_x; +@property (assign, nonatomic) CGFloat mj_y; +@property (assign, nonatomic) CGFloat mj_w; +@property (assign, nonatomic) CGFloat mj_h; +@property (assign, nonatomic) CGSize mj_size; +@property (assign, nonatomic) CGPoint mj_origin; +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/MJRefresh/MJRefresh/UIView+MJExtension.m b/Pods/MJRefresh/MJRefresh/UIView+MJExtension.m new file mode 100644 index 0000000..f4dcf44 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/UIView+MJExtension.m @@ -0,0 +1,83 @@ +// 代码地址: https://github.com/CoderMJLee/MJRefresh +// UIView+Extension.m +// MJRefresh +// +// Created by MJ Lee on 14-5-28. +// Copyright (c) 2014年 小码哥. All rights reserved. +// + +#import "UIView+MJExtension.h" + +@implementation UIView (MJExtension) +- (void)setMj_x:(CGFloat)mj_x +{ + CGRect frame = self.frame; + frame.origin.x = mj_x; + self.frame = frame; +} + +- (CGFloat)mj_x +{ + return self.frame.origin.x; +} + +- (void)setMj_y:(CGFloat)mj_y +{ + CGRect frame = self.frame; + frame.origin.y = mj_y; + self.frame = frame; +} + +- (CGFloat)mj_y +{ + return self.frame.origin.y; +} + +- (void)setMj_w:(CGFloat)mj_w +{ + CGRect frame = self.frame; + frame.size.width = mj_w; + self.frame = frame; +} + +- (CGFloat)mj_w +{ + return self.frame.size.width; +} + +- (void)setMj_h:(CGFloat)mj_h +{ + CGRect frame = self.frame; + frame.size.height = mj_h; + self.frame = frame; +} + +- (CGFloat)mj_h +{ + return self.frame.size.height; +} + +- (void)setMj_size:(CGSize)mj_size +{ + CGRect frame = self.frame; + frame.size = mj_size; + self.frame = frame; +} + +- (CGSize)mj_size +{ + return self.frame.size; +} + +- (void)setMj_origin:(CGPoint)mj_origin +{ + CGRect frame = self.frame; + frame.origin = mj_origin; + self.frame = frame; +} + +- (CGPoint)mj_origin +{ + return self.frame.origin; +} +@end diff --git a/Pods/MJRefresh/README.md b/Pods/MJRefresh/README.md new file mode 100644 index 0000000..0746fbe --- /dev/null +++ b/Pods/MJRefresh/README.md @@ -0,0 +1,457 @@ +## MJRefresh +[![SPM supported](https://img.shields.io/badge/SPM-supported-4BC51D.svg?style=flat)](https://github.com/apple/swift-package-manager) +[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) +[![podversion](https://img.shields.io/cocoapods/v/MJRefresh.svg)](https://cocoapods.org/pods/MJRefresh) + +* An easy way to use pull-to-refresh + +[📜✍🏻**Release Notes**: more details](https://github.com/CoderMJLee/MJRefresh/releases) + +## Contents + +- New Features + - [Dynamic i18n Switching](#dynamic_i18n_switching) + - [SPM Supported](#spm_supported) + - [Swift Chaining Grammar Supported](#swift_chaining_grammar_supported) + +* Getting Started + * [Features【Support what kinds of controls to refresh】](#Support_what_kinds_of_controls_to_refresh) + * [Installation【How to use MJRefresh】](#How_to_use_MJRefresh) + * [Who's using【More than hundreds of Apps are using MJRefresh】](#More_than_hundreds_of_Apps_are_using_MJRefresh) + * [Classes【The Class Structure Chart of MJRefresh】](#The_Class_Structure_Chart_of_MJRefresh) +* Comment API + * [MJRefreshComponent.h](#MJRefreshComponent.h) + * [MJRefreshHeader.h](#MJRefreshHeader.h) + * [MJRefreshFooter.h](#MJRefreshFooter.h) + * [MJRefreshAutoFooter.h](#MJRefreshAutoFooter.h) + * [MJRefreshTrailer.h](#MJRefreshTrailer.h) +* Examples + * [Reference](#Reference) + * [The drop-down refresh 01-Default](#The_drop-down_refresh_01-Default) + * [The drop-down refresh 02-Animation image](#The_drop-down_refresh_02-Animation_image) + * [The drop-down refresh 03-Hide the time](#The_drop-down_refresh_03-Hide_the_time) + * [The drop-down refresh 04-Hide status and time](#The_drop-down_refresh_04-Hide_status_and_time) + * [The drop-down refresh 05-DIY title](#The_drop-down_refresh_05-DIY_title) + * [The drop-down refresh 06-DIY the control of refresh](#The_drop-down_refresh_06-DIY_the_control_of_refresh) + * [The pull to refresh 01-Default](#The_pull_to_refresh_01-Default) + * [The pull to refresh 02-Animation image](#The_pull_to_refresh_02-Animation_image) + * [The pull to refresh 03-Hide the title of refresh status](#The_pull_to_refresh_03-Hide_the_title_of_refresh_status) + * [The pull to refresh 04-All loaded](#The_pull_to_refresh_04-All_loaded) + * [The pull to refresh 05-DIY title](#The_pull_to_refresh_05-DIY_title) + * [The pull to refresh 06-Hidden After loaded](#The_pull_to_refresh_06-Hidden_After_loaded) + * [The pull to refresh 07-Automatic back of the pull01](#The_pull_to_refresh_07-Automatic_back_of_the_pull01) + * [The pull to refresh 08-Automatic back of the pull02](#The_pull_to_refresh_08-Automatic_back_of_the_pull02) + * [The pull to refresh 09-DIY the control of refresh(Automatic refresh)](#The_pull_to_refresh_09-DIY_the_control_of_refresh(Automatic_refresh)) + * [The pull to refresh 10-DIY the control of refresh(Automatic back)](#The_pull_to_refresh_10-DIY_the_control_of_refresh(Automatic_back)) + * [UICollectionView01-The pull and drop-down refresh](#UICollectionView01-The_pull_and_drop-down_refresh) + * [UICollectionView02-The trailer refresh](#UICollectionView02-The_trailer_refresh) + * [WKWebView01-The drop-down refresh](#WKWebView01-The_drop-down_refresh) +* [Hope](#Hope) + +## New Features +### Dynamic i18n Switching + +Now `MJRefresh components` will be rerendered automatically with `MJRefreshConfig.default.language` setting. + +#### Example + +Go `i18n` folder and see lots of cases. Simulator example is behind `i18n tab` in right-top corner. + +#### Setting language + +```swift +MJRefreshConfig.default.language = "zh-hans" +``` + +#### Setting i18n file name + +```swift +MJRefreshConfig.default.i18nFilename = "i18n File Name(not include type<.strings>)" +``` + +#### Setting i18n language bundle + +```swift +MJRefreshConfig.default.i18nBundle = +``` + +#### Adopting the feature in your DIY component + +1. Just override `i18nDidChange` function and reset texts. + +```swift +// must use this localization methods +Bundle.mj_localizedString(forKey: "") +// or +Bundle.mj_localizedString(forKey: "", value:"") + +override func i18nDidChange() { + // Reset texts function + setupTexts() + // Make sure to call super after resetting texts. It will call placeSubViews for applying new layout. + super.i18nDidChange() +} +``` + +2. Receiving `MJRefreshDidChangeLanguageNotification` notification. + +### SPM Supported + +Released from [`3.7.1`](https://github.com/CoderMJLee/MJRefresh/releases/tag/3.7.1) + +### Swift Chaining Grammar Supported + +```swift + // Example as MJRefreshNormalHeader + func addRefreshHeader() { + MJRefreshNormalHeader { [weak self] in + // load some data + }.autoChangeTransparency(true) + .link(to: tableView) + } +``` + +## Support what kinds of controls to refresh + +* `UIScrollView`、`UITableView`、`UICollectionView`、`WKWebView` + +## How to use MJRefresh +* Installation with CocoaPods:`pod 'MJRefresh'` +* Installation with [Carthage](https://github.com/Carthage/Carthage):`github "CoderMJLee/MJRefresh"` +* Manual import: + * Drag All files in the `MJRefresh` folder to project + * Import the main file:`#import "MJRefresh.h"` + +```objc +Base Custom +MJRefresh.bundle MJRefresh.h +MJRefreshConst.h MJRefreshConst.m +UIScrollView+MJExtension.h UIScrollView+MJExtension.m +UIScrollView+MJRefresh.h UIScrollView+MJRefresh.m +UIView+MJExtension.h UIView+MJExtension.m +``` + +## More than hundreds of Apps are using MJRefresh + +* More information of App can focus on:[M了个J-博客园](http://www.cnblogs.com/mjios/p/4409853.html) + +## The Class Structure Chart of MJRefresh +![](http://images0.cnblogs.com/blog2015/497279/201506/132232456139177.png) +- `The class of red text` in the chart:You can use them directly + - The drop-down refresh control types + - Normal:`MJRefreshNormalHeader` + - Gif:`MJRefreshGifHeader` + - The pull to refresh control types + - Auto refresh + - Normal:`MJRefreshAutoNormalFooter` + - Gif:`MJRefreshAutoGifFooter` + - Auto Back + - Normal:`MJRefreshBackNormalFooter` + - Gif:`MJRefreshBackGifFooter` + +- `The class of non-red text` in the chart:For inheritance,to use DIY the control of refresh + +- About how to DIY the control of refresh,You can refer the Class in below Chart
+ + + +## MJRefreshComponent.h +```objc +/** The Base Class of refresh control */ +@interface MJRefreshComponent : UIView +#pragma mark - Control the state of Refresh + +/** BeginRefreshing */ +- (void)beginRefreshing; +/** EndRefreshing */ +- (void)endRefreshing; +/** IsRefreshing */ +- (BOOL)isRefreshing; + +#pragma mark - Other +/** According to the drag ratio to change alpha automatically */ +@property (assign, nonatomic, getter=isAutomaticallyChangeAlpha) BOOL automaticallyChangeAlpha; +@end +``` + +## MJRefreshHeader.h +```objc +@interface MJRefreshHeader : MJRefreshComponent +/** Creat header */ ++ (instancetype)headerWithRefreshingBlock:(MJRefreshComponentRefreshingBlock)refreshingBlock; +/** Creat header */ ++ (instancetype)headerWithRefreshingTarget:(id)target refreshingAction:(SEL)action; + +/** This key is used to storage the time that the last time of drown-down successfully */ +@property (copy, nonatomic) NSString *lastUpdatedTimeKey; +/** The last time of drown-down successfully */ +@property (strong, nonatomic, readonly) NSDate *lastUpdatedTime; + +/** Ignored scrollView contentInset top */ +@property (assign, nonatomic) CGFloat ignoredScrollViewContentInsetTop; +@end +``` + +## MJRefreshFooter.h +```objc +@interface MJRefreshFooter : MJRefreshComponent +/** Creat footer */ ++ (instancetype)footerWithRefreshingBlock:(MJRefreshComponentRefreshingBlock)refreshingBlock; +/** Creat footer */ ++ (instancetype)footerWithRefreshingTarget:(id)target refreshingAction:(SEL)action; + +/** NoticeNoMoreData */ +- (void)noticeNoMoreData; +/** ResetNoMoreData(Clear the status of NoMoreData ) */ +- (void)resetNoMoreData; + +/** Ignored scrollView contentInset bottom */ +@property (assign, nonatomic) CGFloat ignoredScrollViewContentInsetBottom; +@end +``` + +## MJRefreshAutoFooter.h +```objc +@interface MJRefreshAutoFooter : MJRefreshFooter +/** Is Automatically Refresh(Default is Yes) */ +@property (assign, nonatomic, getter=isAutomaticallyRefresh) BOOL automaticallyRefresh; + +/** When there is much at the bottom of the control is automatically refresh(Default is 1.0,Is at the bottom of the control appears in full, will refresh automatically) */ +@property (assign, nonatomic) CGFloat triggerAutomaticallyRefreshPercent; +@end +``` + +## MJRefreshTrailer.h +```objc +@interface MJRefreshTrailer : MJRefreshComponent + +/** 创建trailer */ ++ (instancetype)trailerWithRefreshingBlock:(MJRefreshComponentAction)refreshingBlock; +/** 创建trailer */ ++ (instancetype)trailerWithRefreshingTarget:(id)target refreshingAction:(SEL)action; + +/** 忽略多少scrollView的contentInset的right */ +@property (assign, nonatomic) CGFloat ignoredScrollViewContentInsetRight; + +@end +``` + +## Reference +```objc +* Due to there are more functions of this framework,Don't write specific text describe its usage +* You can directly reference examples MJTableViewController、MJCollectionViewController、MJWebViewController,More intuitive and fast. +``` + + +## The drop-down refresh 01-Default + +```objc +self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{ + //Call this Block When enter the refresh status automatically +}]; +或 +// Set the callback(Once you enter the refresh status,then call the action of target,that is call [self loadNewData]) +self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)]; + +// Enter the refresh status immediately +[self.tableView.mj_header beginRefreshing]; +``` +![(下拉刷新01-普通)](http://images0.cnblogs.com/blog2015/497279/201506/141204343486151.gif) + +## The drop-down refresh 02-Animation image +```objc +// Set the callback(一Once you enter the refresh status,then call the action of target,that is call [self loadNewData]) +MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)]; +// Set the ordinary state of animated images +[header setImages:idleImages forState:MJRefreshStateIdle]; +// Set the pulling state of animated images(Enter the status of refreshing as soon as loosen) +[header setImages:pullingImages forState:MJRefreshStatePulling]; +// Set the refreshing state of animated images +[header setImages:refreshingImages forState:MJRefreshStateRefreshing]; +// Set header +self.tableView.mj_header = header; +``` +![(下拉刷新02-动画图片)](http://images0.cnblogs.com/blog2015/497279/201506/141204402238389.gif) + +## The drop-down refresh 03-Hide the time +```objc +// Hide the time +header.lastUpdatedTimeLabel.hidden = YES; +``` +![(下拉刷新03-隐藏时间)](http://images0.cnblogs.com/blog2015/497279/201506/141204456132944.gif) + +## The drop-down refresh 04-Hide status and time +```objc +// Hide the time +header.lastUpdatedTimeLabel.hidden = YES; + +// Hide the status +header.stateLabel.hidden = YES; +``` +![(下拉刷新04-隐藏状态和时间0)](http://images0.cnblogs.com/blog2015/497279/201506/141204508639539.gif) + +## The drop-down refresh 05-DIY title +```objc +// Set title +[header setTitle:@"Pull down to refresh" forState:MJRefreshStateIdle]; +[header setTitle:@"Release to refresh" forState:MJRefreshStatePulling]; +[header setTitle:@"Loading ..." forState:MJRefreshStateRefreshing]; + +// Set font +header.stateLabel.font = [UIFont systemFontOfSize:15]; +header.lastUpdatedTimeLabel.font = [UIFont systemFontOfSize:14]; + +// Set textColor +header.stateLabel.textColor = [UIColor redColor]; +header.lastUpdatedTimeLabel.textColor = [UIColor blueColor]; +``` +![(下拉刷新05-自定义文字)](http://images0.cnblogs.com/blog2015/497279/201506/141204563633593.gif) + +## The drop-down refresh 06-DIY the control of refresh +```objc +self.tableView.mj_header = [MJDIYHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)]; +// Implementation reference to MJDIYHeader.h和MJDIYHeader.m +``` +![(下拉刷新06-自定义刷新控件)](http://images0.cnblogs.com/blog2015/497279/201506/141205019261159.gif) + +## The pull to refresh 01-Default +```objc +self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{ + //Call this Block When enter the refresh status automatically +}]; +或 +// Set the callback(Once you enter the refresh status,then call the action of target,that is call [self loadMoreData]) +self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)]; +``` +![(上拉刷新01-默认)](http://images0.cnblogs.com/blog2015/497279/201506/141205090047696.gif) + +## The pull to refresh 02-Animation image +```objc +// Set the callback(Once you enter the refresh status,then call the action of target,that is call [self loadMoreData]) +MJRefreshAutoGifFooter *footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)]; + +// Set the refresh image +[footer setImages:refreshingImages forState:MJRefreshStateRefreshing]; + +// Set footer +self.tableView.mj_footer = footer; +``` +![(上拉刷新02-动画图片)](http://images0.cnblogs.com/blog2015/497279/201506/141205141445793.gif) + +## The pull to refresh 03-Hide the title of refresh status +```objc +// Hide the title of refresh status +footer.refreshingTitleHidden = YES; +// If does have not above method,then use footer.stateLabel.hidden = YES; +``` +![(上拉刷新03-隐藏刷新状态的文字)](http://images0.cnblogs.com/blog2015/497279/201506/141205200985774.gif) + +## The pull to refresh 04-All loaded +```objc +//Become the status of NoMoreData +[footer noticeNoMoreData]; +``` +![(上拉刷新04-全部加载完毕)](http://images0.cnblogs.com/blog2015/497279/201506/141205248634686.gif) + +## The pull to refresh 05-DIY title +```objc +// Set title +[footer setTitle:@"Click or drag up to refresh" forState:MJRefreshStateIdle]; +[footer setTitle:@"Loading more ..." forState:MJRefreshStateRefreshing]; +[footer setTitle:@"No more data" forState:MJRefreshStateNoMoreData]; + +// Set font +footer.stateLabel.font = [UIFont systemFontOfSize:17]; + +// Set textColor +footer.stateLabel.textColor = [UIColor blueColor]; +``` +![(上拉刷新05-自定义文字)](http://images0.cnblogs.com/blog2015/497279/201506/141205295511153.gif) + +## The pull to refresh 06-Hidden After loaded +```objc +//Hidden current control of the pull to refresh +self.tableView.mj_footer.hidden = YES; +``` +![(上拉刷新06-加载后隐藏)](http://images0.cnblogs.com/blog2015/497279/201506/141205343481821.gif) + +## The pull to refresh 07-Automatic back of the pull01 +```objc +self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)]; +``` +![(上拉刷新07-自动回弹的上拉01)](http://images0.cnblogs.com/blog2015/497279/201506/141205392239231.gif) + +## The pull to refresh 08-Automatic back of the pull02 +```objc +MJRefreshBackGifFooter *footer = [MJRefreshBackGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)]; + +// Set the normal state of the animated image +[footer setImages:idleImages forState:MJRefreshStateIdle]; +// Set the pulling state of animated images(Enter the status of refreshing as soon as loosen) +[footer setImages:pullingImages forState:MJRefreshStatePulling]; +// Set the refreshing state of animated images +[footer setImages:refreshingImages forState:MJRefreshStateRefreshing]; + +// Set footer +self.tableView.mj_footer = footer; +``` +![(上拉刷新07-自动回弹的上拉02)](http://images0.cnblogs.com/blog2015/497279/201506/141205441443628.gif) + +## The pull to refresh 09-DIY the control of refresh(Automatic refresh) +```objc +self.tableView.mj_footer = [MJDIYAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)]; +// Implementation reference to MJDIYAutoFooter.h和MJDIYAutoFooter.m +``` +![(上拉刷新09-自定义刷新控件(自动刷新))](http://images0.cnblogs.com/blog2015/497279/201506/141205500195866.gif) + +## The pull to refresh 10-DIY the control of refresh(Automatic back) +```objc +self.tableView.mj_footer = [MJDIYBackFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)]; +// Implementation reference to MJDIYBackFooter.h和MJDIYBackFooter.m +``` +![(上拉刷新10-自定义刷新控件(自动回弹))](http://images0.cnblogs.com/blog2015/497279/201506/141205560666819.gif) + +## UICollectionView01-The pull and drop-down refresh +```objc +// The drop-down refresh +self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{ + //Call this Block When enter the refresh status automatically +}]; + +// The pull to refresh +self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{ + //Call this Block When enter the refresh status automatically +}]; +``` +![(UICollectionView01-上下拉刷新)](http://images0.cnblogs.com/blog2015/497279/201506/141206021603758.gif) + +## UICollectionView02-The trailer refresh +```objc +// The trailer refresh +self.collectionView.mj_trailer = [MJRefreshNormalTrailer trailerWithRefreshingBlock:^{ + //Call this Block When enter the refresh status automatically +}]; + +``` +![(UICollectionView02-左拉刷新)](Gif/trailer_refresh.gif) + +## WKWebView01-The drop-down refresh +```objc +//Add the control of The drop-down refresh +self.webView.scrollView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{ + //Call this Block When enter the refresh status automatically +}]; +``` +![(UICollectionView01-上下拉刷新)](http://images0.cnblogs.com/blog2015/497279/201506/141206080514524.gif) + +## Remind +* ARC +* iOS>=9.0 +* iPhone \ iPad screen anyway + +## 寻求志同道合的小伙伴 + +- 因本人工作忙,没有太多时间去维护MJRefresh,在此向广大框架使用者说声:非常抱歉!😞 +- 现寻求志同道合的小伙伴一起维护此框架,有兴趣的小伙伴可以[发邮件](mailto:richermj123go@vip.qq.com)给我,非常感谢😊 +- 如果一切OK,我将开放框架维护权限(github、pod等) +- 目前已经找到3位小伙伴(^-^)V diff --git a/Pods/Manifest.lock b/Pods/Manifest.lock new file mode 100644 index 0000000..ff55f71 --- /dev/null +++ b/Pods/Manifest.lock @@ -0,0 +1,52 @@ +PODS: + - AFNetworking (4.0.1): + - AFNetworking/NSURLSession (= 4.0.1) + - AFNetworking/Reachability (= 4.0.1) + - AFNetworking/Security (= 4.0.1) + - AFNetworking/Serialization (= 4.0.1) + - AFNetworking/UIKit (= 4.0.1) + - AFNetworking/NSURLSession (4.0.1): + - AFNetworking/Reachability + - AFNetworking/Security + - AFNetworking/Serialization + - AFNetworking/Reachability (4.0.1) + - AFNetworking/Security (4.0.1) + - AFNetworking/Serialization (4.0.1) + - AFNetworking/UIKit (4.0.1): + - AFNetworking/NSURLSession + - Bugly (2.6.1) + - Masonry (1.1.0) + - MJExtension (3.4.2) + - MJRefresh (3.7.9) + - SDWebImage (5.21.1): + - SDWebImage/Core (= 5.21.1) + - SDWebImage/Core (5.21.1) + +DEPENDENCIES: + - AFNetworking (= 4.0.1) + - Bugly (= 2.6.1) + - Masonry (= 1.1.0) + - MJExtension (= 3.4.2) + - MJRefresh (= 3.7.9) + - SDWebImage (= 5.21.1) + +SPEC REPOS: + https://github.com/CocoaPods/Specs.git: + - AFNetworking + - Bugly + - Masonry + - MJExtension + - MJRefresh + - SDWebImage + +SPEC CHECKSUMS: + AFNetworking: 3bd23d814e976cd148d7d44c3ab78017b744cd58 + Bugly: 217ac2ce5f0f2626d43dbaa4f70764c953a26a31 + Masonry: 678fab65091a9290e40e2832a55e7ab731aad201 + MJExtension: e97d164cb411aa9795cf576093a1fa208b4a8dd8 + MJRefresh: ff9e531227924c84ce459338414550a05d2aea78 + SDWebImage: f29024626962457f3470184232766516dee8dfea + +PODFILE CHECKSUM: b3c72fe500149c35040cdd73c1d91fe05777bc5f + +COCOAPODS: 1.16.2 diff --git a/Pods/Masonry/LICENSE b/Pods/Masonry/LICENSE new file mode 100644 index 0000000..a843c00 --- /dev/null +++ b/Pods/Masonry/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2011-2012 Masonry Team - https://github.com/Masonry + +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. \ No newline at end of file diff --git a/Pods/Masonry/Masonry/MASCompositeConstraint.h b/Pods/Masonry/Masonry/MASCompositeConstraint.h new file mode 100644 index 0000000..934c6f1 --- /dev/null +++ b/Pods/Masonry/Masonry/MASCompositeConstraint.h @@ -0,0 +1,26 @@ +// +// MASCompositeConstraint.h +// Masonry +// +// Created by Jonas Budelmann on 21/07/13. +// Copyright (c) 2013 cloudling. All rights reserved. +// + +#import "MASConstraint.h" +#import "MASUtilities.h" + +/** + * A group of MASConstraint objects + */ +@interface MASCompositeConstraint : MASConstraint + +/** + * Creates a composite with a predefined array of children + * + * @param children child MASConstraints + * + * @return a composite constraint + */ +- (id)initWithChildren:(NSArray *)children; + +@end diff --git a/Pods/Masonry/Masonry/MASCompositeConstraint.m b/Pods/Masonry/Masonry/MASCompositeConstraint.m new file mode 100644 index 0000000..2002a40 --- /dev/null +++ b/Pods/Masonry/Masonry/MASCompositeConstraint.m @@ -0,0 +1,183 @@ +// +// MASCompositeConstraint.m +// Masonry +// +// Created by Jonas Budelmann on 21/07/13. +// Copyright (c) 2013 cloudling. All rights reserved. +// + +#import "MASCompositeConstraint.h" +#import "MASConstraint+Private.h" + +@interface MASCompositeConstraint () + +@property (nonatomic, strong) id mas_key; +@property (nonatomic, strong) NSMutableArray *childConstraints; + +@end + +@implementation MASCompositeConstraint + +- (id)initWithChildren:(NSArray *)children { + self = [super init]; + if (!self) return nil; + + _childConstraints = [children mutableCopy]; + for (MASConstraint *constraint in _childConstraints) { + constraint.delegate = self; + } + + return self; +} + +#pragma mark - MASConstraintDelegate + +- (void)constraint:(MASConstraint *)constraint shouldBeReplacedWithConstraint:(MASConstraint *)replacementConstraint { + NSUInteger index = [self.childConstraints indexOfObject:constraint]; + NSAssert(index != NSNotFound, @"Could not find constraint %@", constraint); + [self.childConstraints replaceObjectAtIndex:index withObject:replacementConstraint]; +} + +- (MASConstraint *)constraint:(MASConstraint __unused *)constraint addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute { + id strongDelegate = self.delegate; + MASConstraint *newConstraint = [strongDelegate constraint:self addConstraintWithLayoutAttribute:layoutAttribute]; + newConstraint.delegate = self; + [self.childConstraints addObject:newConstraint]; + return newConstraint; +} + +#pragma mark - NSLayoutConstraint multiplier proxies + +- (MASConstraint * (^)(CGFloat))multipliedBy { + return ^id(CGFloat multiplier) { + for (MASConstraint *constraint in self.childConstraints) { + constraint.multipliedBy(multiplier); + } + return self; + }; +} + +- (MASConstraint * (^)(CGFloat))dividedBy { + return ^id(CGFloat divider) { + for (MASConstraint *constraint in self.childConstraints) { + constraint.dividedBy(divider); + } + return self; + }; +} + +#pragma mark - MASLayoutPriority proxy + +- (MASConstraint * (^)(MASLayoutPriority))priority { + return ^id(MASLayoutPriority priority) { + for (MASConstraint *constraint in self.childConstraints) { + constraint.priority(priority); + } + return self; + }; +} + +#pragma mark - NSLayoutRelation proxy + +- (MASConstraint * (^)(id, NSLayoutRelation))equalToWithRelation { + return ^id(id attr, NSLayoutRelation relation) { + for (MASConstraint *constraint in self.childConstraints.copy) { + constraint.equalToWithRelation(attr, relation); + } + return self; + }; +} + +#pragma mark - attribute chaining + +- (MASConstraint *)addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute { + [self constraint:self addConstraintWithLayoutAttribute:layoutAttribute]; + return self; +} + +#pragma mark - Animator proxy + +#if TARGET_OS_MAC && !(TARGET_OS_IPHONE || TARGET_OS_TV) + +- (MASConstraint *)animator { + for (MASConstraint *constraint in self.childConstraints) { + [constraint animator]; + } + return self; +} + +#endif + +#pragma mark - debug helpers + +- (MASConstraint * (^)(id))key { + return ^id(id key) { + self.mas_key = key; + int i = 0; + for (MASConstraint *constraint in self.childConstraints) { + constraint.key([NSString stringWithFormat:@"%@[%d]", key, i++]); + } + return self; + }; +} + +#pragma mark - NSLayoutConstraint constant setters + +- (void)setInsets:(MASEdgeInsets)insets { + for (MASConstraint *constraint in self.childConstraints) { + constraint.insets = insets; + } +} + +- (void)setInset:(CGFloat)inset { + for (MASConstraint *constraint in self.childConstraints) { + constraint.inset = inset; + } +} + +- (void)setOffset:(CGFloat)offset { + for (MASConstraint *constraint in self.childConstraints) { + constraint.offset = offset; + } +} + +- (void)setSizeOffset:(CGSize)sizeOffset { + for (MASConstraint *constraint in self.childConstraints) { + constraint.sizeOffset = sizeOffset; + } +} + +- (void)setCenterOffset:(CGPoint)centerOffset { + for (MASConstraint *constraint in self.childConstraints) { + constraint.centerOffset = centerOffset; + } +} + +#pragma mark - MASConstraint + +- (void)activate { + for (MASConstraint *constraint in self.childConstraints) { + [constraint activate]; + } +} + +- (void)deactivate { + for (MASConstraint *constraint in self.childConstraints) { + [constraint deactivate]; + } +} + +- (void)install { + for (MASConstraint *constraint in self.childConstraints) { + constraint.updateExisting = self.updateExisting; + [constraint install]; + } +} + +- (void)uninstall { + for (MASConstraint *constraint in self.childConstraints) { + [constraint uninstall]; + } +} + +@end diff --git a/Pods/Masonry/Masonry/MASConstraint+Private.h b/Pods/Masonry/Masonry/MASConstraint+Private.h new file mode 100644 index 0000000..ee0fd96 --- /dev/null +++ b/Pods/Masonry/Masonry/MASConstraint+Private.h @@ -0,0 +1,66 @@ +// +// MASConstraint+Private.h +// Masonry +// +// Created by Nick Tymchenko on 29/04/14. +// Copyright (c) 2014 cloudling. All rights reserved. +// + +#import "MASConstraint.h" + +@protocol MASConstraintDelegate; + + +@interface MASConstraint () + +/** + * Whether or not to check for an existing constraint instead of adding constraint + */ +@property (nonatomic, assign) BOOL updateExisting; + +/** + * Usually MASConstraintMaker but could be a parent MASConstraint + */ +@property (nonatomic, weak) id delegate; + +/** + * Based on a provided value type, is equal to calling: + * NSNumber - setOffset: + * NSValue with CGPoint - setPointOffset: + * NSValue with CGSize - setSizeOffset: + * NSValue with MASEdgeInsets - setInsets: + */ +- (void)setLayoutConstantWithValue:(NSValue *)value; + +@end + + +@interface MASConstraint (Abstract) + +/** + * Sets the constraint relation to given NSLayoutRelation + * returns a block which accepts one of the following: + * MASViewAttribute, UIView, NSValue, NSArray + * see readme for more details. + */ +- (MASConstraint * (^)(id, NSLayoutRelation))equalToWithRelation; + +/** + * Override to set a custom chaining behaviour + */ +- (MASConstraint *)addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute; + +@end + + +@protocol MASConstraintDelegate + +/** + * Notifies the delegate when the constraint needs to be replaced with another constraint. For example + * A MASViewConstraint may turn into a MASCompositeConstraint when an array is passed to one of the equality blocks + */ +- (void)constraint:(MASConstraint *)constraint shouldBeReplacedWithConstraint:(MASConstraint *)replacementConstraint; + +- (MASConstraint *)constraint:(MASConstraint *)constraint addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute; + +@end diff --git a/Pods/Masonry/Masonry/MASConstraint.h b/Pods/Masonry/Masonry/MASConstraint.h new file mode 100644 index 0000000..3eaa8a1 --- /dev/null +++ b/Pods/Masonry/Masonry/MASConstraint.h @@ -0,0 +1,272 @@ +// +// MASConstraint.h +// Masonry +// +// Created by Jonas Budelmann on 22/07/13. +// Copyright (c) 2013 cloudling. All rights reserved. +// + +#import "MASUtilities.h" + +/** + * Enables Constraints to be created with chainable syntax + * Constraint can represent single NSLayoutConstraint (MASViewConstraint) + * or a group of NSLayoutConstraints (MASComposisteConstraint) + */ +@interface MASConstraint : NSObject + +// Chaining Support + +/** + * Modifies the NSLayoutConstraint constant, + * only affects MASConstraints in which the first item's NSLayoutAttribute is one of the following + * NSLayoutAttributeTop, NSLayoutAttributeLeft, NSLayoutAttributeBottom, NSLayoutAttributeRight + */ +- (MASConstraint * (^)(MASEdgeInsets insets))insets; + +/** + * Modifies the NSLayoutConstraint constant, + * only affects MASConstraints in which the first item's NSLayoutAttribute is one of the following + * NSLayoutAttributeTop, NSLayoutAttributeLeft, NSLayoutAttributeBottom, NSLayoutAttributeRight + */ +- (MASConstraint * (^)(CGFloat inset))inset; + +/** + * Modifies the NSLayoutConstraint constant, + * only affects MASConstraints in which the first item's NSLayoutAttribute is one of the following + * NSLayoutAttributeWidth, NSLayoutAttributeHeight + */ +- (MASConstraint * (^)(CGSize offset))sizeOffset; + +/** + * Modifies the NSLayoutConstraint constant, + * only affects MASConstraints in which the first item's NSLayoutAttribute is one of the following + * NSLayoutAttributeCenterX, NSLayoutAttributeCenterY + */ +- (MASConstraint * (^)(CGPoint offset))centerOffset; + +/** + * Modifies the NSLayoutConstraint constant + */ +- (MASConstraint * (^)(CGFloat offset))offset; + +/** + * Modifies the NSLayoutConstraint constant based on a value type + */ +- (MASConstraint * (^)(NSValue *value))valueOffset; + +/** + * Sets the NSLayoutConstraint multiplier property + */ +- (MASConstraint * (^)(CGFloat multiplier))multipliedBy; + +/** + * Sets the NSLayoutConstraint multiplier to 1.0/dividedBy + */ +- (MASConstraint * (^)(CGFloat divider))dividedBy; + +/** + * Sets the NSLayoutConstraint priority to a float or MASLayoutPriority + */ +- (MASConstraint * (^)(MASLayoutPriority priority))priority; + +/** + * Sets the NSLayoutConstraint priority to MASLayoutPriorityLow + */ +- (MASConstraint * (^)(void))priorityLow; + +/** + * Sets the NSLayoutConstraint priority to MASLayoutPriorityMedium + */ +- (MASConstraint * (^)(void))priorityMedium; + +/** + * Sets the NSLayoutConstraint priority to MASLayoutPriorityHigh + */ +- (MASConstraint * (^)(void))priorityHigh; + +/** + * Sets the constraint relation to NSLayoutRelationEqual + * returns a block which accepts one of the following: + * MASViewAttribute, UIView, NSValue, NSArray + * see readme for more details. + */ +- (MASConstraint * (^)(id attr))equalTo; + +/** + * Sets the constraint relation to NSLayoutRelationGreaterThanOrEqual + * returns a block which accepts one of the following: + * MASViewAttribute, UIView, NSValue, NSArray + * see readme for more details. + */ +- (MASConstraint * (^)(id attr))greaterThanOrEqualTo; + +/** + * Sets the constraint relation to NSLayoutRelationLessThanOrEqual + * returns a block which accepts one of the following: + * MASViewAttribute, UIView, NSValue, NSArray + * see readme for more details. + */ +- (MASConstraint * (^)(id attr))lessThanOrEqualTo; + +/** + * Optional semantic property which has no effect but improves the readability of constraint + */ +- (MASConstraint *)with; + +/** + * Optional semantic property which has no effect but improves the readability of constraint + */ +- (MASConstraint *)and; + +/** + * Creates a new MASCompositeConstraint with the called attribute and reciever + */ +- (MASConstraint *)left; +- (MASConstraint *)top; +- (MASConstraint *)right; +- (MASConstraint *)bottom; +- (MASConstraint *)leading; +- (MASConstraint *)trailing; +- (MASConstraint *)width; +- (MASConstraint *)height; +- (MASConstraint *)centerX; +- (MASConstraint *)centerY; +- (MASConstraint *)baseline; + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + +- (MASConstraint *)firstBaseline; +- (MASConstraint *)lastBaseline; + +#endif + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) + +- (MASConstraint *)leftMargin; +- (MASConstraint *)rightMargin; +- (MASConstraint *)topMargin; +- (MASConstraint *)bottomMargin; +- (MASConstraint *)leadingMargin; +- (MASConstraint *)trailingMargin; +- (MASConstraint *)centerXWithinMargins; +- (MASConstraint *)centerYWithinMargins; + +#endif + + +/** + * Sets the constraint debug name + */ +- (MASConstraint * (^)(id key))key; + +// NSLayoutConstraint constant Setters +// for use outside of mas_updateConstraints/mas_makeConstraints blocks + +/** + * Modifies the NSLayoutConstraint constant, + * only affects MASConstraints in which the first item's NSLayoutAttribute is one of the following + * NSLayoutAttributeTop, NSLayoutAttributeLeft, NSLayoutAttributeBottom, NSLayoutAttributeRight + */ +- (void)setInsets:(MASEdgeInsets)insets; + +/** + * Modifies the NSLayoutConstraint constant, + * only affects MASConstraints in which the first item's NSLayoutAttribute is one of the following + * NSLayoutAttributeTop, NSLayoutAttributeLeft, NSLayoutAttributeBottom, NSLayoutAttributeRight + */ +- (void)setInset:(CGFloat)inset; + +/** + * Modifies the NSLayoutConstraint constant, + * only affects MASConstraints in which the first item's NSLayoutAttribute is one of the following + * NSLayoutAttributeWidth, NSLayoutAttributeHeight + */ +- (void)setSizeOffset:(CGSize)sizeOffset; + +/** + * Modifies the NSLayoutConstraint constant, + * only affects MASConstraints in which the first item's NSLayoutAttribute is one of the following + * NSLayoutAttributeCenterX, NSLayoutAttributeCenterY + */ +- (void)setCenterOffset:(CGPoint)centerOffset; + +/** + * Modifies the NSLayoutConstraint constant + */ +- (void)setOffset:(CGFloat)offset; + + +// NSLayoutConstraint Installation support + +#if TARGET_OS_MAC && !(TARGET_OS_IPHONE || TARGET_OS_TV) +/** + * Whether or not to go through the animator proxy when modifying the constraint + */ +@property (nonatomic, copy, readonly) MASConstraint *animator; +#endif + +/** + * Activates an NSLayoutConstraint if it's supported by an OS. + * Invokes install otherwise. + */ +- (void)activate; + +/** + * Deactivates previously installed/activated NSLayoutConstraint. + */ +- (void)deactivate; + +/** + * Creates a NSLayoutConstraint and adds it to the appropriate view. + */ +- (void)install; + +/** + * Removes previously installed NSLayoutConstraint + */ +- (void)uninstall; + +@end + + +/** + * Convenience auto-boxing macros for MASConstraint methods. + * + * Defining MAS_SHORTHAND_GLOBALS will turn on auto-boxing for default syntax. + * A potential drawback of this is that the unprefixed macros will appear in global scope. + */ +#define mas_equalTo(...) equalTo(MASBoxValue((__VA_ARGS__))) +#define mas_greaterThanOrEqualTo(...) greaterThanOrEqualTo(MASBoxValue((__VA_ARGS__))) +#define mas_lessThanOrEqualTo(...) lessThanOrEqualTo(MASBoxValue((__VA_ARGS__))) + +#define mas_offset(...) valueOffset(MASBoxValue((__VA_ARGS__))) + + +#ifdef MAS_SHORTHAND_GLOBALS + +#define equalTo(...) mas_equalTo(__VA_ARGS__) +#define greaterThanOrEqualTo(...) mas_greaterThanOrEqualTo(__VA_ARGS__) +#define lessThanOrEqualTo(...) mas_lessThanOrEqualTo(__VA_ARGS__) + +#define offset(...) mas_offset(__VA_ARGS__) + +#endif + + +@interface MASConstraint (AutoboxingSupport) + +/** + * Aliases to corresponding relation methods (for shorthand macros) + * Also needed to aid autocompletion + */ +- (MASConstraint * (^)(id attr))mas_equalTo; +- (MASConstraint * (^)(id attr))mas_greaterThanOrEqualTo; +- (MASConstraint * (^)(id attr))mas_lessThanOrEqualTo; + +/** + * A dummy method to aid autocompletion + */ +- (MASConstraint * (^)(id offset))mas_offset; + +@end diff --git a/Pods/Masonry/Masonry/MASConstraint.m b/Pods/Masonry/Masonry/MASConstraint.m new file mode 100644 index 0000000..52de590 --- /dev/null +++ b/Pods/Masonry/Masonry/MASConstraint.m @@ -0,0 +1,301 @@ +// +// MASConstraint.m +// Masonry +// +// Created by Nick Tymchenko on 1/20/14. +// + +#import "MASConstraint.h" +#import "MASConstraint+Private.h" + +#define MASMethodNotImplemented() \ + @throw [NSException exceptionWithName:NSInternalInconsistencyException \ + reason:[NSString stringWithFormat:@"You must override %@ in a subclass.", NSStringFromSelector(_cmd)] \ + userInfo:nil] + +@implementation MASConstraint + +#pragma mark - Init + +- (id)init { + NSAssert(![self isMemberOfClass:[MASConstraint class]], @"MASConstraint is an abstract class, you should not instantiate it directly."); + return [super init]; +} + +#pragma mark - NSLayoutRelation proxies + +- (MASConstraint * (^)(id))equalTo { + return ^id(id attribute) { + return self.equalToWithRelation(attribute, NSLayoutRelationEqual); + }; +} + +- (MASConstraint * (^)(id))mas_equalTo { + return ^id(id attribute) { + return self.equalToWithRelation(attribute, NSLayoutRelationEqual); + }; +} + +- (MASConstraint * (^)(id))greaterThanOrEqualTo { + return ^id(id attribute) { + return self.equalToWithRelation(attribute, NSLayoutRelationGreaterThanOrEqual); + }; +} + +- (MASConstraint * (^)(id))mas_greaterThanOrEqualTo { + return ^id(id attribute) { + return self.equalToWithRelation(attribute, NSLayoutRelationGreaterThanOrEqual); + }; +} + +- (MASConstraint * (^)(id))lessThanOrEqualTo { + return ^id(id attribute) { + return self.equalToWithRelation(attribute, NSLayoutRelationLessThanOrEqual); + }; +} + +- (MASConstraint * (^)(id))mas_lessThanOrEqualTo { + return ^id(id attribute) { + return self.equalToWithRelation(attribute, NSLayoutRelationLessThanOrEqual); + }; +} + +#pragma mark - MASLayoutPriority proxies + +- (MASConstraint * (^)(void))priorityLow { + return ^id{ + self.priority(MASLayoutPriorityDefaultLow); + return self; + }; +} + +- (MASConstraint * (^)(void))priorityMedium { + return ^id{ + self.priority(MASLayoutPriorityDefaultMedium); + return self; + }; +} + +- (MASConstraint * (^)(void))priorityHigh { + return ^id{ + self.priority(MASLayoutPriorityDefaultHigh); + return self; + }; +} + +#pragma mark - NSLayoutConstraint constant proxies + +- (MASConstraint * (^)(MASEdgeInsets))insets { + return ^id(MASEdgeInsets insets){ + self.insets = insets; + return self; + }; +} + +- (MASConstraint * (^)(CGFloat))inset { + return ^id(CGFloat inset){ + self.inset = inset; + return self; + }; +} + +- (MASConstraint * (^)(CGSize))sizeOffset { + return ^id(CGSize offset) { + self.sizeOffset = offset; + return self; + }; +} + +- (MASConstraint * (^)(CGPoint))centerOffset { + return ^id(CGPoint offset) { + self.centerOffset = offset; + return self; + }; +} + +- (MASConstraint * (^)(CGFloat))offset { + return ^id(CGFloat offset){ + self.offset = offset; + return self; + }; +} + +- (MASConstraint * (^)(NSValue *value))valueOffset { + return ^id(NSValue *offset) { + NSAssert([offset isKindOfClass:NSValue.class], @"expected an NSValue offset, got: %@", offset); + [self setLayoutConstantWithValue:offset]; + return self; + }; +} + +- (MASConstraint * (^)(id offset))mas_offset { + // Will never be called due to macro + return nil; +} + +#pragma mark - NSLayoutConstraint constant setter + +- (void)setLayoutConstantWithValue:(NSValue *)value { + if ([value isKindOfClass:NSNumber.class]) { + self.offset = [(NSNumber *)value doubleValue]; + } else if (strcmp(value.objCType, @encode(CGPoint)) == 0) { + CGPoint point; + [value getValue:&point]; + self.centerOffset = point; + } else if (strcmp(value.objCType, @encode(CGSize)) == 0) { + CGSize size; + [value getValue:&size]; + self.sizeOffset = size; + } else if (strcmp(value.objCType, @encode(MASEdgeInsets)) == 0) { + MASEdgeInsets insets; + [value getValue:&insets]; + self.insets = insets; + } else { + NSAssert(NO, @"attempting to set layout constant with unsupported value: %@", value); + } +} + +#pragma mark - Semantic properties + +- (MASConstraint *)with { + return self; +} + +- (MASConstraint *)and { + return self; +} + +#pragma mark - Chaining + +- (MASConstraint *)addConstraintWithLayoutAttribute:(NSLayoutAttribute __unused)layoutAttribute { + MASMethodNotImplemented(); +} + +- (MASConstraint *)left { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeft]; +} + +- (MASConstraint *)top { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTop]; +} + +- (MASConstraint *)right { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeRight]; +} + +- (MASConstraint *)bottom { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBottom]; +} + +- (MASConstraint *)leading { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeading]; +} + +- (MASConstraint *)trailing { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTrailing]; +} + +- (MASConstraint *)width { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeWidth]; +} + +- (MASConstraint *)height { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeHeight]; +} + +- (MASConstraint *)centerX { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterX]; +} + +- (MASConstraint *)centerY { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterY]; +} + +- (MASConstraint *)baseline { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBaseline]; +} + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + +- (MASConstraint *)firstBaseline { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeFirstBaseline]; +} +- (MASConstraint *)lastBaseline { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLastBaseline]; +} + +#endif + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) + +- (MASConstraint *)leftMargin { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeftMargin]; +} + +- (MASConstraint *)rightMargin { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeRightMargin]; +} + +- (MASConstraint *)topMargin { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTopMargin]; +} + +- (MASConstraint *)bottomMargin { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBottomMargin]; +} + +- (MASConstraint *)leadingMargin { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeadingMargin]; +} + +- (MASConstraint *)trailingMargin { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTrailingMargin]; +} + +- (MASConstraint *)centerXWithinMargins { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterXWithinMargins]; +} + +- (MASConstraint *)centerYWithinMargins { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterYWithinMargins]; +} + +#endif + +#pragma mark - Abstract + +- (MASConstraint * (^)(CGFloat multiplier))multipliedBy { MASMethodNotImplemented(); } + +- (MASConstraint * (^)(CGFloat divider))dividedBy { MASMethodNotImplemented(); } + +- (MASConstraint * (^)(MASLayoutPriority priority))priority { MASMethodNotImplemented(); } + +- (MASConstraint * (^)(id, NSLayoutRelation))equalToWithRelation { MASMethodNotImplemented(); } + +- (MASConstraint * (^)(id key))key { MASMethodNotImplemented(); } + +- (void)setInsets:(MASEdgeInsets __unused)insets { MASMethodNotImplemented(); } + +- (void)setInset:(CGFloat __unused)inset { MASMethodNotImplemented(); } + +- (void)setSizeOffset:(CGSize __unused)sizeOffset { MASMethodNotImplemented(); } + +- (void)setCenterOffset:(CGPoint __unused)centerOffset { MASMethodNotImplemented(); } + +- (void)setOffset:(CGFloat __unused)offset { MASMethodNotImplemented(); } + +#if TARGET_OS_MAC && !(TARGET_OS_IPHONE || TARGET_OS_TV) + +- (MASConstraint *)animator { MASMethodNotImplemented(); } + +#endif + +- (void)activate { MASMethodNotImplemented(); } + +- (void)deactivate { MASMethodNotImplemented(); } + +- (void)install { MASMethodNotImplemented(); } + +- (void)uninstall { MASMethodNotImplemented(); } + +@end diff --git a/Pods/Masonry/Masonry/MASConstraintMaker.h b/Pods/Masonry/Masonry/MASConstraintMaker.h new file mode 100644 index 0000000..d9b58f4 --- /dev/null +++ b/Pods/Masonry/Masonry/MASConstraintMaker.h @@ -0,0 +1,146 @@ +// +// MASConstraintMaker.h +// Masonry +// +// Created by Jonas Budelmann on 20/07/13. +// Copyright (c) 2013 cloudling. All rights reserved. +// + +#import "MASConstraint.h" +#import "MASUtilities.h" + +typedef NS_OPTIONS(NSInteger, MASAttribute) { + MASAttributeLeft = 1 << NSLayoutAttributeLeft, + MASAttributeRight = 1 << NSLayoutAttributeRight, + MASAttributeTop = 1 << NSLayoutAttributeTop, + MASAttributeBottom = 1 << NSLayoutAttributeBottom, + MASAttributeLeading = 1 << NSLayoutAttributeLeading, + MASAttributeTrailing = 1 << NSLayoutAttributeTrailing, + MASAttributeWidth = 1 << NSLayoutAttributeWidth, + MASAttributeHeight = 1 << NSLayoutAttributeHeight, + MASAttributeCenterX = 1 << NSLayoutAttributeCenterX, + MASAttributeCenterY = 1 << NSLayoutAttributeCenterY, + MASAttributeBaseline = 1 << NSLayoutAttributeBaseline, + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + + MASAttributeFirstBaseline = 1 << NSLayoutAttributeFirstBaseline, + MASAttributeLastBaseline = 1 << NSLayoutAttributeLastBaseline, + +#endif + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) + + MASAttributeLeftMargin = 1 << NSLayoutAttributeLeftMargin, + MASAttributeRightMargin = 1 << NSLayoutAttributeRightMargin, + MASAttributeTopMargin = 1 << NSLayoutAttributeTopMargin, + MASAttributeBottomMargin = 1 << NSLayoutAttributeBottomMargin, + MASAttributeLeadingMargin = 1 << NSLayoutAttributeLeadingMargin, + MASAttributeTrailingMargin = 1 << NSLayoutAttributeTrailingMargin, + MASAttributeCenterXWithinMargins = 1 << NSLayoutAttributeCenterXWithinMargins, + MASAttributeCenterYWithinMargins = 1 << NSLayoutAttributeCenterYWithinMargins, + +#endif + +}; + +/** + * Provides factory methods for creating MASConstraints. + * Constraints are collected until they are ready to be installed + * + */ +@interface MASConstraintMaker : NSObject + +/** + * The following properties return a new MASViewConstraint + * with the first item set to the makers associated view and the appropriate MASViewAttribute + */ +@property (nonatomic, strong, readonly) MASConstraint *left; +@property (nonatomic, strong, readonly) MASConstraint *top; +@property (nonatomic, strong, readonly) MASConstraint *right; +@property (nonatomic, strong, readonly) MASConstraint *bottom; +@property (nonatomic, strong, readonly) MASConstraint *leading; +@property (nonatomic, strong, readonly) MASConstraint *trailing; +@property (nonatomic, strong, readonly) MASConstraint *width; +@property (nonatomic, strong, readonly) MASConstraint *height; +@property (nonatomic, strong, readonly) MASConstraint *centerX; +@property (nonatomic, strong, readonly) MASConstraint *centerY; +@property (nonatomic, strong, readonly) MASConstraint *baseline; + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + +@property (nonatomic, strong, readonly) MASConstraint *firstBaseline; +@property (nonatomic, strong, readonly) MASConstraint *lastBaseline; + +#endif + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) + +@property (nonatomic, strong, readonly) MASConstraint *leftMargin; +@property (nonatomic, strong, readonly) MASConstraint *rightMargin; +@property (nonatomic, strong, readonly) MASConstraint *topMargin; +@property (nonatomic, strong, readonly) MASConstraint *bottomMargin; +@property (nonatomic, strong, readonly) MASConstraint *leadingMargin; +@property (nonatomic, strong, readonly) MASConstraint *trailingMargin; +@property (nonatomic, strong, readonly) MASConstraint *centerXWithinMargins; +@property (nonatomic, strong, readonly) MASConstraint *centerYWithinMargins; + +#endif + +/** + * Returns a block which creates a new MASCompositeConstraint with the first item set + * to the makers associated view and children corresponding to the set bits in the + * MASAttribute parameter. Combine multiple attributes via binary-or. + */ +@property (nonatomic, strong, readonly) MASConstraint *(^attributes)(MASAttribute attrs); + +/** + * Creates a MASCompositeConstraint with type MASCompositeConstraintTypeEdges + * which generates the appropriate MASViewConstraint children (top, left, bottom, right) + * with the first item set to the makers associated view + */ +@property (nonatomic, strong, readonly) MASConstraint *edges; + +/** + * Creates a MASCompositeConstraint with type MASCompositeConstraintTypeSize + * which generates the appropriate MASViewConstraint children (width, height) + * with the first item set to the makers associated view + */ +@property (nonatomic, strong, readonly) MASConstraint *size; + +/** + * Creates a MASCompositeConstraint with type MASCompositeConstraintTypeCenter + * which generates the appropriate MASViewConstraint children (centerX, centerY) + * with the first item set to the makers associated view + */ +@property (nonatomic, strong, readonly) MASConstraint *center; + +/** + * Whether or not to check for an existing constraint instead of adding constraint + */ +@property (nonatomic, assign) BOOL updateExisting; + +/** + * Whether or not to remove existing constraints prior to installing + */ +@property (nonatomic, assign) BOOL removeExisting; + +/** + * initialises the maker with a default view + * + * @param view any MASConstraint are created with this view as the first item + * + * @return a new MASConstraintMaker + */ +- (id)initWithView:(MAS_VIEW *)view; + +/** + * Calls install method on any MASConstraints which have been created by this maker + * + * @return an array of all the installed MASConstraints + */ +- (NSArray *)install; + +- (MASConstraint * (^)(dispatch_block_t))group; + +@end diff --git a/Pods/Masonry/Masonry/MASConstraintMaker.m b/Pods/Masonry/Masonry/MASConstraintMaker.m new file mode 100644 index 0000000..f11492a --- /dev/null +++ b/Pods/Masonry/Masonry/MASConstraintMaker.m @@ -0,0 +1,273 @@ +// +// MASConstraintMaker.m +// Masonry +// +// Created by Jonas Budelmann on 20/07/13. +// Copyright (c) 2013 cloudling. All rights reserved. +// + +#import "MASConstraintMaker.h" +#import "MASViewConstraint.h" +#import "MASCompositeConstraint.h" +#import "MASConstraint+Private.h" +#import "MASViewAttribute.h" +#import "View+MASAdditions.h" + +@interface MASConstraintMaker () + +@property (nonatomic, weak) MAS_VIEW *view; +@property (nonatomic, strong) NSMutableArray *constraints; + +@end + +@implementation MASConstraintMaker + +- (id)initWithView:(MAS_VIEW *)view { + self = [super init]; + if (!self) return nil; + + self.view = view; + self.constraints = NSMutableArray.new; + + return self; +} + +- (NSArray *)install { + if (self.removeExisting) { + NSArray *installedConstraints = [MASViewConstraint installedConstraintsForView:self.view]; + for (MASConstraint *constraint in installedConstraints) { + [constraint uninstall]; + } + } + NSArray *constraints = self.constraints.copy; + for (MASConstraint *constraint in constraints) { + constraint.updateExisting = self.updateExisting; + [constraint install]; + } + [self.constraints removeAllObjects]; + return constraints; +} + +#pragma mark - MASConstraintDelegate + +- (void)constraint:(MASConstraint *)constraint shouldBeReplacedWithConstraint:(MASConstraint *)replacementConstraint { + NSUInteger index = [self.constraints indexOfObject:constraint]; + NSAssert(index != NSNotFound, @"Could not find constraint %@", constraint); + [self.constraints replaceObjectAtIndex:index withObject:replacementConstraint]; +} + +- (MASConstraint *)constraint:(MASConstraint *)constraint addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute { + MASViewAttribute *viewAttribute = [[MASViewAttribute alloc] initWithView:self.view layoutAttribute:layoutAttribute]; + MASViewConstraint *newConstraint = [[MASViewConstraint alloc] initWithFirstViewAttribute:viewAttribute]; + if ([constraint isKindOfClass:MASViewConstraint.class]) { + //replace with composite constraint + NSArray *children = @[constraint, newConstraint]; + MASCompositeConstraint *compositeConstraint = [[MASCompositeConstraint alloc] initWithChildren:children]; + compositeConstraint.delegate = self; + [self constraint:constraint shouldBeReplacedWithConstraint:compositeConstraint]; + return compositeConstraint; + } + if (!constraint) { + newConstraint.delegate = self; + [self.constraints addObject:newConstraint]; + } + return newConstraint; +} + +- (MASConstraint *)addConstraintWithAttributes:(MASAttribute)attrs { + __unused MASAttribute anyAttribute = (MASAttributeLeft | MASAttributeRight | MASAttributeTop | MASAttributeBottom | MASAttributeLeading + | MASAttributeTrailing | MASAttributeWidth | MASAttributeHeight | MASAttributeCenterX + | MASAttributeCenterY | MASAttributeBaseline +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + | MASAttributeFirstBaseline | MASAttributeLastBaseline +#endif +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) + | MASAttributeLeftMargin | MASAttributeRightMargin | MASAttributeTopMargin | MASAttributeBottomMargin + | MASAttributeLeadingMargin | MASAttributeTrailingMargin | MASAttributeCenterXWithinMargins + | MASAttributeCenterYWithinMargins +#endif + ); + + NSAssert((attrs & anyAttribute) != 0, @"You didn't pass any attribute to make.attributes(...)"); + + NSMutableArray *attributes = [NSMutableArray array]; + + if (attrs & MASAttributeLeft) [attributes addObject:self.view.mas_left]; + if (attrs & MASAttributeRight) [attributes addObject:self.view.mas_right]; + if (attrs & MASAttributeTop) [attributes addObject:self.view.mas_top]; + if (attrs & MASAttributeBottom) [attributes addObject:self.view.mas_bottom]; + if (attrs & MASAttributeLeading) [attributes addObject:self.view.mas_leading]; + if (attrs & MASAttributeTrailing) [attributes addObject:self.view.mas_trailing]; + if (attrs & MASAttributeWidth) [attributes addObject:self.view.mas_width]; + if (attrs & MASAttributeHeight) [attributes addObject:self.view.mas_height]; + if (attrs & MASAttributeCenterX) [attributes addObject:self.view.mas_centerX]; + if (attrs & MASAttributeCenterY) [attributes addObject:self.view.mas_centerY]; + if (attrs & MASAttributeBaseline) [attributes addObject:self.view.mas_baseline]; + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + + if (attrs & MASAttributeFirstBaseline) [attributes addObject:self.view.mas_firstBaseline]; + if (attrs & MASAttributeLastBaseline) [attributes addObject:self.view.mas_lastBaseline]; + +#endif + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) + + if (attrs & MASAttributeLeftMargin) [attributes addObject:self.view.mas_leftMargin]; + if (attrs & MASAttributeRightMargin) [attributes addObject:self.view.mas_rightMargin]; + if (attrs & MASAttributeTopMargin) [attributes addObject:self.view.mas_topMargin]; + if (attrs & MASAttributeBottomMargin) [attributes addObject:self.view.mas_bottomMargin]; + if (attrs & MASAttributeLeadingMargin) [attributes addObject:self.view.mas_leadingMargin]; + if (attrs & MASAttributeTrailingMargin) [attributes addObject:self.view.mas_trailingMargin]; + if (attrs & MASAttributeCenterXWithinMargins) [attributes addObject:self.view.mas_centerXWithinMargins]; + if (attrs & MASAttributeCenterYWithinMargins) [attributes addObject:self.view.mas_centerYWithinMargins]; + +#endif + + NSMutableArray *children = [NSMutableArray arrayWithCapacity:attributes.count]; + + for (MASViewAttribute *a in attributes) { + [children addObject:[[MASViewConstraint alloc] initWithFirstViewAttribute:a]]; + } + + MASCompositeConstraint *constraint = [[MASCompositeConstraint alloc] initWithChildren:children]; + constraint.delegate = self; + [self.constraints addObject:constraint]; + return constraint; +} + +#pragma mark - standard Attributes + +- (MASConstraint *)addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute { + return [self constraint:nil addConstraintWithLayoutAttribute:layoutAttribute]; +} + +- (MASConstraint *)left { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeft]; +} + +- (MASConstraint *)top { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTop]; +} + +- (MASConstraint *)right { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeRight]; +} + +- (MASConstraint *)bottom { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBottom]; +} + +- (MASConstraint *)leading { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeading]; +} + +- (MASConstraint *)trailing { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTrailing]; +} + +- (MASConstraint *)width { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeWidth]; +} + +- (MASConstraint *)height { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeHeight]; +} + +- (MASConstraint *)centerX { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterX]; +} + +- (MASConstraint *)centerY { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterY]; +} + +- (MASConstraint *)baseline { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBaseline]; +} + +- (MASConstraint *(^)(MASAttribute))attributes { + return ^(MASAttribute attrs){ + return [self addConstraintWithAttributes:attrs]; + }; +} + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + +- (MASConstraint *)firstBaseline { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeFirstBaseline]; +} + +- (MASConstraint *)lastBaseline { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLastBaseline]; +} + +#endif + + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) + +- (MASConstraint *)leftMargin { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeftMargin]; +} + +- (MASConstraint *)rightMargin { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeRightMargin]; +} + +- (MASConstraint *)topMargin { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTopMargin]; +} + +- (MASConstraint *)bottomMargin { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBottomMargin]; +} + +- (MASConstraint *)leadingMargin { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeadingMargin]; +} + +- (MASConstraint *)trailingMargin { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTrailingMargin]; +} + +- (MASConstraint *)centerXWithinMargins { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterXWithinMargins]; +} + +- (MASConstraint *)centerYWithinMargins { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterYWithinMargins]; +} + +#endif + + +#pragma mark - composite Attributes + +- (MASConstraint *)edges { + return [self addConstraintWithAttributes:MASAttributeTop | MASAttributeLeft | MASAttributeRight | MASAttributeBottom]; +} + +- (MASConstraint *)size { + return [self addConstraintWithAttributes:MASAttributeWidth | MASAttributeHeight]; +} + +- (MASConstraint *)center { + return [self addConstraintWithAttributes:MASAttributeCenterX | MASAttributeCenterY]; +} + +#pragma mark - grouping + +- (MASConstraint *(^)(dispatch_block_t group))group { + return ^id(dispatch_block_t group) { + NSInteger previousCount = self.constraints.count; + group(); + + NSArray *children = [self.constraints subarrayWithRange:NSMakeRange(previousCount, self.constraints.count - previousCount)]; + MASCompositeConstraint *constraint = [[MASCompositeConstraint alloc] initWithChildren:children]; + constraint.delegate = self; + return constraint; + }; +} + +@end diff --git a/Pods/Masonry/Masonry/MASLayoutConstraint.h b/Pods/Masonry/Masonry/MASLayoutConstraint.h new file mode 100644 index 0000000..699041c --- /dev/null +++ b/Pods/Masonry/Masonry/MASLayoutConstraint.h @@ -0,0 +1,22 @@ +// +// MASLayoutConstraint.h +// Masonry +// +// Created by Jonas Budelmann on 3/08/13. +// Copyright (c) 2013 Jonas Budelmann. All rights reserved. +// + +#import "MASUtilities.h" + +/** + * When you are debugging or printing the constraints attached to a view this subclass + * makes it easier to identify which constraints have been created via Masonry + */ +@interface MASLayoutConstraint : NSLayoutConstraint + +/** + * a key to associate with this constraint + */ +@property (nonatomic, strong) id mas_key; + +@end diff --git a/Pods/Masonry/Masonry/MASLayoutConstraint.m b/Pods/Masonry/Masonry/MASLayoutConstraint.m new file mode 100644 index 0000000..3483f02 --- /dev/null +++ b/Pods/Masonry/Masonry/MASLayoutConstraint.m @@ -0,0 +1,13 @@ +// +// MASLayoutConstraint.m +// Masonry +// +// Created by Jonas Budelmann on 3/08/13. +// Copyright (c) 2013 Jonas Budelmann. All rights reserved. +// + +#import "MASLayoutConstraint.h" + +@implementation MASLayoutConstraint + +@end diff --git a/Pods/Masonry/Masonry/MASUtilities.h b/Pods/Masonry/Masonry/MASUtilities.h new file mode 100644 index 0000000..1dbfd93 --- /dev/null +++ b/Pods/Masonry/Masonry/MASUtilities.h @@ -0,0 +1,136 @@ +// +// MASUtilities.h +// Masonry +// +// Created by Jonas Budelmann on 19/08/13. +// Copyright (c) 2013 Jonas Budelmann. All rights reserved. +// + +#import + + + +#if TARGET_OS_IPHONE || TARGET_OS_TV + + #import + #define MAS_VIEW UIView + #define MAS_VIEW_CONTROLLER UIViewController + #define MASEdgeInsets UIEdgeInsets + + typedef UILayoutPriority MASLayoutPriority; + static const MASLayoutPriority MASLayoutPriorityRequired = UILayoutPriorityRequired; + static const MASLayoutPriority MASLayoutPriorityDefaultHigh = UILayoutPriorityDefaultHigh; + static const MASLayoutPriority MASLayoutPriorityDefaultMedium = 500; + static const MASLayoutPriority MASLayoutPriorityDefaultLow = UILayoutPriorityDefaultLow; + static const MASLayoutPriority MASLayoutPriorityFittingSizeLevel = UILayoutPriorityFittingSizeLevel; + +#elif TARGET_OS_MAC + + #import + #define MAS_VIEW NSView + #define MASEdgeInsets NSEdgeInsets + + typedef NSLayoutPriority MASLayoutPriority; + static const MASLayoutPriority MASLayoutPriorityRequired = NSLayoutPriorityRequired; + static const MASLayoutPriority MASLayoutPriorityDefaultHigh = NSLayoutPriorityDefaultHigh; + static const MASLayoutPriority MASLayoutPriorityDragThatCanResizeWindow = NSLayoutPriorityDragThatCanResizeWindow; + static const MASLayoutPriority MASLayoutPriorityDefaultMedium = 501; + static const MASLayoutPriority MASLayoutPriorityWindowSizeStayPut = NSLayoutPriorityWindowSizeStayPut; + static const MASLayoutPriority MASLayoutPriorityDragThatCannotResizeWindow = NSLayoutPriorityDragThatCannotResizeWindow; + static const MASLayoutPriority MASLayoutPriorityDefaultLow = NSLayoutPriorityDefaultLow; + static const MASLayoutPriority MASLayoutPriorityFittingSizeCompression = NSLayoutPriorityFittingSizeCompression; + +#endif + +/** + * Allows you to attach keys to objects matching the variable names passed. + * + * view1.mas_key = @"view1", view2.mas_key = @"view2"; + * + * is equivalent to: + * + * MASAttachKeys(view1, view2); + */ +#define MASAttachKeys(...) \ + { \ + NSDictionary *keyPairs = NSDictionaryOfVariableBindings(__VA_ARGS__); \ + for (id key in keyPairs.allKeys) { \ + id obj = keyPairs[key]; \ + NSAssert([obj respondsToSelector:@selector(setMas_key:)], \ + @"Cannot attach mas_key to %@", obj); \ + [obj setMas_key:key]; \ + } \ + } + +/** + * Used to create object hashes + * Based on http://www.mikeash.com/pyblog/friday-qa-2010-06-18-implementing-equality-and-hashing.html + */ +#define MAS_NSUINT_BIT (CHAR_BIT * sizeof(NSUInteger)) +#define MAS_NSUINTROTATE(val, howmuch) ((((NSUInteger)val) << howmuch) | (((NSUInteger)val) >> (MAS_NSUINT_BIT - howmuch))) + +/** + * Given a scalar or struct value, wraps it in NSValue + * Based on EXPObjectify: https://github.com/specta/expecta + */ +static inline id _MASBoxValue(const char *type, ...) { + va_list v; + va_start(v, type); + id obj = nil; + if (strcmp(type, @encode(id)) == 0) { + id actual = va_arg(v, id); + obj = actual; + } else if (strcmp(type, @encode(CGPoint)) == 0) { + CGPoint actual = (CGPoint)va_arg(v, CGPoint); + obj = [NSValue value:&actual withObjCType:type]; + } else if (strcmp(type, @encode(CGSize)) == 0) { + CGSize actual = (CGSize)va_arg(v, CGSize); + obj = [NSValue value:&actual withObjCType:type]; + } else if (strcmp(type, @encode(MASEdgeInsets)) == 0) { + MASEdgeInsets actual = (MASEdgeInsets)va_arg(v, MASEdgeInsets); + obj = [NSValue value:&actual withObjCType:type]; + } else if (strcmp(type, @encode(double)) == 0) { + double actual = (double)va_arg(v, double); + obj = [NSNumber numberWithDouble:actual]; + } else if (strcmp(type, @encode(float)) == 0) { + float actual = (float)va_arg(v, double); + obj = [NSNumber numberWithFloat:actual]; + } else if (strcmp(type, @encode(int)) == 0) { + int actual = (int)va_arg(v, int); + obj = [NSNumber numberWithInt:actual]; + } else if (strcmp(type, @encode(long)) == 0) { + long actual = (long)va_arg(v, long); + obj = [NSNumber numberWithLong:actual]; + } else if (strcmp(type, @encode(long long)) == 0) { + long long actual = (long long)va_arg(v, long long); + obj = [NSNumber numberWithLongLong:actual]; + } else if (strcmp(type, @encode(short)) == 0) { + short actual = (short)va_arg(v, int); + obj = [NSNumber numberWithShort:actual]; + } else if (strcmp(type, @encode(char)) == 0) { + char actual = (char)va_arg(v, int); + obj = [NSNumber numberWithChar:actual]; + } else if (strcmp(type, @encode(bool)) == 0) { + bool actual = (bool)va_arg(v, int); + obj = [NSNumber numberWithBool:actual]; + } else if (strcmp(type, @encode(unsigned char)) == 0) { + unsigned char actual = (unsigned char)va_arg(v, unsigned int); + obj = [NSNumber numberWithUnsignedChar:actual]; + } else if (strcmp(type, @encode(unsigned int)) == 0) { + unsigned int actual = (unsigned int)va_arg(v, unsigned int); + obj = [NSNumber numberWithUnsignedInt:actual]; + } else if (strcmp(type, @encode(unsigned long)) == 0) { + unsigned long actual = (unsigned long)va_arg(v, unsigned long); + obj = [NSNumber numberWithUnsignedLong:actual]; + } else if (strcmp(type, @encode(unsigned long long)) == 0) { + unsigned long long actual = (unsigned long long)va_arg(v, unsigned long long); + obj = [NSNumber numberWithUnsignedLongLong:actual]; + } else if (strcmp(type, @encode(unsigned short)) == 0) { + unsigned short actual = (unsigned short)va_arg(v, unsigned int); + obj = [NSNumber numberWithUnsignedShort:actual]; + } + va_end(v); + return obj; +} + +#define MASBoxValue(value) _MASBoxValue(@encode(__typeof__((value))), (value)) diff --git a/Pods/Masonry/Masonry/MASViewAttribute.h b/Pods/Masonry/Masonry/MASViewAttribute.h new file mode 100644 index 0000000..601c25d --- /dev/null +++ b/Pods/Masonry/Masonry/MASViewAttribute.h @@ -0,0 +1,49 @@ +// +// MASViewAttribute.h +// Masonry +// +// Created by Jonas Budelmann on 21/07/13. +// Copyright (c) 2013 cloudling. All rights reserved. +// + +#import "MASUtilities.h" + +/** + * An immutable tuple which stores the view and the related NSLayoutAttribute. + * Describes part of either the left or right hand side of a constraint equation + */ +@interface MASViewAttribute : NSObject + +/** + * The view which the reciever relates to. Can be nil if item is not a view. + */ +@property (nonatomic, weak, readonly) MAS_VIEW *view; + +/** + * The item which the reciever relates to. + */ +@property (nonatomic, weak, readonly) id item; + +/** + * The attribute which the reciever relates to + */ +@property (nonatomic, assign, readonly) NSLayoutAttribute layoutAttribute; + +/** + * Convenience initializer. + */ +- (id)initWithView:(MAS_VIEW *)view layoutAttribute:(NSLayoutAttribute)layoutAttribute; + +/** + * The designated initializer. + */ +- (id)initWithView:(MAS_VIEW *)view item:(id)item layoutAttribute:(NSLayoutAttribute)layoutAttribute; + +/** + * Determine whether the layoutAttribute is a size attribute + * + * @return YES if layoutAttribute is equal to NSLayoutAttributeWidth or NSLayoutAttributeHeight + */ +- (BOOL)isSizeAttribute; + +@end diff --git a/Pods/Masonry/Masonry/MASViewAttribute.m b/Pods/Masonry/Masonry/MASViewAttribute.m new file mode 100644 index 0000000..e573e8b --- /dev/null +++ b/Pods/Masonry/Masonry/MASViewAttribute.m @@ -0,0 +1,46 @@ +// +// MASViewAttribute.m +// Masonry +// +// Created by Jonas Budelmann on 21/07/13. +// Copyright (c) 2013 cloudling. All rights reserved. +// + +#import "MASViewAttribute.h" + +@implementation MASViewAttribute + +- (id)initWithView:(MAS_VIEW *)view layoutAttribute:(NSLayoutAttribute)layoutAttribute { + self = [self initWithView:view item:view layoutAttribute:layoutAttribute]; + return self; +} + +- (id)initWithView:(MAS_VIEW *)view item:(id)item layoutAttribute:(NSLayoutAttribute)layoutAttribute { + self = [super init]; + if (!self) return nil; + + _view = view; + _item = item; + _layoutAttribute = layoutAttribute; + + return self; +} + +- (BOOL)isSizeAttribute { + return self.layoutAttribute == NSLayoutAttributeWidth + || self.layoutAttribute == NSLayoutAttributeHeight; +} + +- (BOOL)isEqual:(MASViewAttribute *)viewAttribute { + if ([viewAttribute isKindOfClass:self.class]) { + return self.view == viewAttribute.view + && self.layoutAttribute == viewAttribute.layoutAttribute; + } + return [super isEqual:viewAttribute]; +} + +- (NSUInteger)hash { + return MAS_NSUINTROTATE([self.view hash], MAS_NSUINT_BIT / 2) ^ self.layoutAttribute; +} + +@end diff --git a/Pods/Masonry/Masonry/MASViewConstraint.h b/Pods/Masonry/Masonry/MASViewConstraint.h new file mode 100644 index 0000000..ec390d1 --- /dev/null +++ b/Pods/Masonry/Masonry/MASViewConstraint.h @@ -0,0 +1,48 @@ +// +// MASViewConstraint.h +// Masonry +// +// Created by Jonas Budelmann on 20/07/13. +// Copyright (c) 2013 cloudling. All rights reserved. +// + +#import "MASViewAttribute.h" +#import "MASConstraint.h" +#import "MASLayoutConstraint.h" +#import "MASUtilities.h" + +/** + * A single constraint. + * Contains the attributes neccessary for creating a NSLayoutConstraint and adding it to the appropriate view + */ +@interface MASViewConstraint : MASConstraint + +/** + * First item/view and first attribute of the NSLayoutConstraint + */ +@property (nonatomic, strong, readonly) MASViewAttribute *firstViewAttribute; + +/** + * Second item/view and second attribute of the NSLayoutConstraint + */ +@property (nonatomic, strong, readonly) MASViewAttribute *secondViewAttribute; + +/** + * initialises the MASViewConstraint with the first part of the equation + * + * @param firstViewAttribute view.mas_left, view.mas_width etc. + * + * @return a new view constraint + */ +- (id)initWithFirstViewAttribute:(MASViewAttribute *)firstViewAttribute; + +/** + * Returns all MASViewConstraints installed with this view as a first item. + * + * @param view A view to retrieve constraints for. + * + * @return An array of MASViewConstraints. + */ ++ (NSArray *)installedConstraintsForView:(MAS_VIEW *)view; + +@end diff --git a/Pods/Masonry/Masonry/MASViewConstraint.m b/Pods/Masonry/Masonry/MASViewConstraint.m new file mode 100644 index 0000000..173eec1 --- /dev/null +++ b/Pods/Masonry/Masonry/MASViewConstraint.m @@ -0,0 +1,401 @@ +// +// MASViewConstraint.m +// Masonry +// +// Created by Jonas Budelmann on 20/07/13. +// Copyright (c) 2013 cloudling. All rights reserved. +// + +#import "MASViewConstraint.h" +#import "MASConstraint+Private.h" +#import "MASCompositeConstraint.h" +#import "MASLayoutConstraint.h" +#import "View+MASAdditions.h" +#import + +@interface MAS_VIEW (MASConstraints) + +@property (nonatomic, readonly) NSMutableSet *mas_installedConstraints; + +@end + +@implementation MAS_VIEW (MASConstraints) + +static char kInstalledConstraintsKey; + +- (NSMutableSet *)mas_installedConstraints { + NSMutableSet *constraints = objc_getAssociatedObject(self, &kInstalledConstraintsKey); + if (!constraints) { + constraints = [NSMutableSet set]; + objc_setAssociatedObject(self, &kInstalledConstraintsKey, constraints, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + return constraints; +} + +@end + + +@interface MASViewConstraint () + +@property (nonatomic, strong, readwrite) MASViewAttribute *secondViewAttribute; +@property (nonatomic, weak) MAS_VIEW *installedView; +@property (nonatomic, weak) MASLayoutConstraint *layoutConstraint; +@property (nonatomic, assign) NSLayoutRelation layoutRelation; +@property (nonatomic, assign) MASLayoutPriority layoutPriority; +@property (nonatomic, assign) CGFloat layoutMultiplier; +@property (nonatomic, assign) CGFloat layoutConstant; +@property (nonatomic, assign) BOOL hasLayoutRelation; +@property (nonatomic, strong) id mas_key; +@property (nonatomic, assign) BOOL useAnimator; + +@end + +@implementation MASViewConstraint + +- (id)initWithFirstViewAttribute:(MASViewAttribute *)firstViewAttribute { + self = [super init]; + if (!self) return nil; + + _firstViewAttribute = firstViewAttribute; + self.layoutPriority = MASLayoutPriorityRequired; + self.layoutMultiplier = 1; + + return self; +} + +#pragma mark - NSCoping + +- (id)copyWithZone:(NSZone __unused *)zone { + MASViewConstraint *constraint = [[MASViewConstraint alloc] initWithFirstViewAttribute:self.firstViewAttribute]; + constraint.layoutConstant = self.layoutConstant; + constraint.layoutRelation = self.layoutRelation; + constraint.layoutPriority = self.layoutPriority; + constraint.layoutMultiplier = self.layoutMultiplier; + constraint.delegate = self.delegate; + return constraint; +} + +#pragma mark - Public + ++ (NSArray *)installedConstraintsForView:(MAS_VIEW *)view { + return [view.mas_installedConstraints allObjects]; +} + +#pragma mark - Private + +- (void)setLayoutConstant:(CGFloat)layoutConstant { + _layoutConstant = layoutConstant; + +#if TARGET_OS_MAC && !(TARGET_OS_IPHONE || TARGET_OS_TV) + if (self.useAnimator) { + [self.layoutConstraint.animator setConstant:layoutConstant]; + } else { + self.layoutConstraint.constant = layoutConstant; + } +#else + self.layoutConstraint.constant = layoutConstant; +#endif +} + +- (void)setLayoutRelation:(NSLayoutRelation)layoutRelation { + _layoutRelation = layoutRelation; + self.hasLayoutRelation = YES; +} + +- (BOOL)supportsActiveProperty { + return [self.layoutConstraint respondsToSelector:@selector(isActive)]; +} + +- (BOOL)isActive { + BOOL active = YES; + if ([self supportsActiveProperty]) { + active = [self.layoutConstraint isActive]; + } + + return active; +} + +- (BOOL)hasBeenInstalled { + return (self.layoutConstraint != nil) && [self isActive]; +} + +- (void)setSecondViewAttribute:(id)secondViewAttribute { + if ([secondViewAttribute isKindOfClass:NSValue.class]) { + [self setLayoutConstantWithValue:secondViewAttribute]; + } else if ([secondViewAttribute isKindOfClass:MAS_VIEW.class]) { + _secondViewAttribute = [[MASViewAttribute alloc] initWithView:secondViewAttribute layoutAttribute:self.firstViewAttribute.layoutAttribute]; + } else if ([secondViewAttribute isKindOfClass:MASViewAttribute.class]) { + _secondViewAttribute = secondViewAttribute; + } else { + NSAssert(NO, @"attempting to add unsupported attribute: %@", secondViewAttribute); + } +} + +#pragma mark - NSLayoutConstraint multiplier proxies + +- (MASConstraint * (^)(CGFloat))multipliedBy { + return ^id(CGFloat multiplier) { + NSAssert(!self.hasBeenInstalled, + @"Cannot modify constraint multiplier after it has been installed"); + + self.layoutMultiplier = multiplier; + return self; + }; +} + + +- (MASConstraint * (^)(CGFloat))dividedBy { + return ^id(CGFloat divider) { + NSAssert(!self.hasBeenInstalled, + @"Cannot modify constraint multiplier after it has been installed"); + + self.layoutMultiplier = 1.0/divider; + return self; + }; +} + +#pragma mark - MASLayoutPriority proxy + +- (MASConstraint * (^)(MASLayoutPriority))priority { + return ^id(MASLayoutPriority priority) { + NSAssert(!self.hasBeenInstalled, + @"Cannot modify constraint priority after it has been installed"); + + self.layoutPriority = priority; + return self; + }; +} + +#pragma mark - NSLayoutRelation proxy + +- (MASConstraint * (^)(id, NSLayoutRelation))equalToWithRelation { + return ^id(id attribute, NSLayoutRelation relation) { + if ([attribute isKindOfClass:NSArray.class]) { + NSAssert(!self.hasLayoutRelation, @"Redefinition of constraint relation"); + NSMutableArray *children = NSMutableArray.new; + for (id attr in attribute) { + MASViewConstraint *viewConstraint = [self copy]; + viewConstraint.layoutRelation = relation; + viewConstraint.secondViewAttribute = attr; + [children addObject:viewConstraint]; + } + MASCompositeConstraint *compositeConstraint = [[MASCompositeConstraint alloc] initWithChildren:children]; + compositeConstraint.delegate = self.delegate; + [self.delegate constraint:self shouldBeReplacedWithConstraint:compositeConstraint]; + return compositeConstraint; + } else { + NSAssert(!self.hasLayoutRelation || self.layoutRelation == relation && [attribute isKindOfClass:NSValue.class], @"Redefinition of constraint relation"); + self.layoutRelation = relation; + self.secondViewAttribute = attribute; + return self; + } + }; +} + +#pragma mark - Semantic properties + +- (MASConstraint *)with { + return self; +} + +- (MASConstraint *)and { + return self; +} + +#pragma mark - attribute chaining + +- (MASConstraint *)addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute { + NSAssert(!self.hasLayoutRelation, @"Attributes should be chained before defining the constraint relation"); + + return [self.delegate constraint:self addConstraintWithLayoutAttribute:layoutAttribute]; +} + +#pragma mark - Animator proxy + +#if TARGET_OS_MAC && !(TARGET_OS_IPHONE || TARGET_OS_TV) + +- (MASConstraint *)animator { + self.useAnimator = YES; + return self; +} + +#endif + +#pragma mark - debug helpers + +- (MASConstraint * (^)(id))key { + return ^id(id key) { + self.mas_key = key; + return self; + }; +} + +#pragma mark - NSLayoutConstraint constant setters + +- (void)setInsets:(MASEdgeInsets)insets { + NSLayoutAttribute layoutAttribute = self.firstViewAttribute.layoutAttribute; + switch (layoutAttribute) { + case NSLayoutAttributeLeft: + case NSLayoutAttributeLeading: + self.layoutConstant = insets.left; + break; + case NSLayoutAttributeTop: + self.layoutConstant = insets.top; + break; + case NSLayoutAttributeBottom: + self.layoutConstant = -insets.bottom; + break; + case NSLayoutAttributeRight: + case NSLayoutAttributeTrailing: + self.layoutConstant = -insets.right; + break; + default: + break; + } +} + +- (void)setInset:(CGFloat)inset { + [self setInsets:(MASEdgeInsets){.top = inset, .left = inset, .bottom = inset, .right = inset}]; +} + +- (void)setOffset:(CGFloat)offset { + self.layoutConstant = offset; +} + +- (void)setSizeOffset:(CGSize)sizeOffset { + NSLayoutAttribute layoutAttribute = self.firstViewAttribute.layoutAttribute; + switch (layoutAttribute) { + case NSLayoutAttributeWidth: + self.layoutConstant = sizeOffset.width; + break; + case NSLayoutAttributeHeight: + self.layoutConstant = sizeOffset.height; + break; + default: + break; + } +} + +- (void)setCenterOffset:(CGPoint)centerOffset { + NSLayoutAttribute layoutAttribute = self.firstViewAttribute.layoutAttribute; + switch (layoutAttribute) { + case NSLayoutAttributeCenterX: + self.layoutConstant = centerOffset.x; + break; + case NSLayoutAttributeCenterY: + self.layoutConstant = centerOffset.y; + break; + default: + break; + } +} + +#pragma mark - MASConstraint + +- (void)activate { + [self install]; +} + +- (void)deactivate { + [self uninstall]; +} + +- (void)install { + if (self.hasBeenInstalled) { + return; + } + + if ([self supportsActiveProperty] && self.layoutConstraint) { + self.layoutConstraint.active = YES; + [self.firstViewAttribute.view.mas_installedConstraints addObject:self]; + return; + } + + MAS_VIEW *firstLayoutItem = self.firstViewAttribute.item; + NSLayoutAttribute firstLayoutAttribute = self.firstViewAttribute.layoutAttribute; + MAS_VIEW *secondLayoutItem = self.secondViewAttribute.item; + NSLayoutAttribute secondLayoutAttribute = self.secondViewAttribute.layoutAttribute; + + // alignment attributes must have a secondViewAttribute + // therefore we assume that is refering to superview + // eg make.left.equalTo(@10) + if (!self.firstViewAttribute.isSizeAttribute && !self.secondViewAttribute) { + secondLayoutItem = self.firstViewAttribute.view.superview; + secondLayoutAttribute = firstLayoutAttribute; + } + + MASLayoutConstraint *layoutConstraint + = [MASLayoutConstraint constraintWithItem:firstLayoutItem + attribute:firstLayoutAttribute + relatedBy:self.layoutRelation + toItem:secondLayoutItem + attribute:secondLayoutAttribute + multiplier:self.layoutMultiplier + constant:self.layoutConstant]; + + layoutConstraint.priority = self.layoutPriority; + layoutConstraint.mas_key = self.mas_key; + + if (self.secondViewAttribute.view) { + MAS_VIEW *closestCommonSuperview = [self.firstViewAttribute.view mas_closestCommonSuperview:self.secondViewAttribute.view]; + NSAssert(closestCommonSuperview, + @"couldn't find a common superview for %@ and %@", + self.firstViewAttribute.view, self.secondViewAttribute.view); + self.installedView = closestCommonSuperview; + } else if (self.firstViewAttribute.isSizeAttribute) { + self.installedView = self.firstViewAttribute.view; + } else { + self.installedView = self.firstViewAttribute.view.superview; + } + + + MASLayoutConstraint *existingConstraint = nil; + if (self.updateExisting) { + existingConstraint = [self layoutConstraintSimilarTo:layoutConstraint]; + } + if (existingConstraint) { + // just update the constant + existingConstraint.constant = layoutConstraint.constant; + self.layoutConstraint = existingConstraint; + } else { + [self.installedView addConstraint:layoutConstraint]; + self.layoutConstraint = layoutConstraint; + [firstLayoutItem.mas_installedConstraints addObject:self]; + } +} + +- (MASLayoutConstraint *)layoutConstraintSimilarTo:(MASLayoutConstraint *)layoutConstraint { + // check if any constraints are the same apart from the only mutable property constant + + // go through constraints in reverse as we do not want to match auto-resizing or interface builder constraints + // and they are likely to be added first. + for (NSLayoutConstraint *existingConstraint in self.installedView.constraints.reverseObjectEnumerator) { + if (![existingConstraint isKindOfClass:MASLayoutConstraint.class]) continue; + if (existingConstraint.firstItem != layoutConstraint.firstItem) continue; + if (existingConstraint.secondItem != layoutConstraint.secondItem) continue; + if (existingConstraint.firstAttribute != layoutConstraint.firstAttribute) continue; + if (existingConstraint.secondAttribute != layoutConstraint.secondAttribute) continue; + if (existingConstraint.relation != layoutConstraint.relation) continue; + if (existingConstraint.multiplier != layoutConstraint.multiplier) continue; + if (existingConstraint.priority != layoutConstraint.priority) continue; + + return (id)existingConstraint; + } + return nil; +} + +- (void)uninstall { + if ([self supportsActiveProperty]) { + self.layoutConstraint.active = NO; + [self.firstViewAttribute.view.mas_installedConstraints removeObject:self]; + return; + } + + [self.installedView removeConstraint:self.layoutConstraint]; + self.layoutConstraint = nil; + self.installedView = nil; + + [self.firstViewAttribute.view.mas_installedConstraints removeObject:self]; +} + +@end diff --git a/Pods/Masonry/Masonry/Masonry.h b/Pods/Masonry/Masonry/Masonry.h new file mode 100644 index 0000000..d1bd579 --- /dev/null +++ b/Pods/Masonry/Masonry/Masonry.h @@ -0,0 +1,29 @@ +// +// Masonry.h +// Masonry +// +// Created by Jonas Budelmann on 20/07/13. +// Copyright (c) 2013 cloudling. All rights reserved. +// + +#import + +//! Project version number for Masonry. +FOUNDATION_EXPORT double MasonryVersionNumber; + +//! Project version string for Masonry. +FOUNDATION_EXPORT const unsigned char MasonryVersionString[]; + +#import "MASUtilities.h" +#import "View+MASAdditions.h" +#import "View+MASShorthandAdditions.h" +#import "ViewController+MASAdditions.h" +#import "NSArray+MASAdditions.h" +#import "NSArray+MASShorthandAdditions.h" +#import "MASConstraint.h" +#import "MASCompositeConstraint.h" +#import "MASViewAttribute.h" +#import "MASViewConstraint.h" +#import "MASConstraintMaker.h" +#import "MASLayoutConstraint.h" +#import "NSLayoutConstraint+MASDebugAdditions.h" diff --git a/Pods/Masonry/Masonry/NSArray+MASAdditions.h b/Pods/Masonry/Masonry/NSArray+MASAdditions.h new file mode 100644 index 0000000..587618d --- /dev/null +++ b/Pods/Masonry/Masonry/NSArray+MASAdditions.h @@ -0,0 +1,72 @@ +// +// NSArray+MASAdditions.h +// +// +// Created by Daniel Hammond on 11/26/13. +// +// + +#import "MASUtilities.h" +#import "MASConstraintMaker.h" +#import "MASViewAttribute.h" + +typedef NS_ENUM(NSUInteger, MASAxisType) { + MASAxisTypeHorizontal, + MASAxisTypeVertical +}; + +@interface NSArray (MASAdditions) + +/** + * Creates a MASConstraintMaker with each view in the callee. + * Any constraints defined are added to the view or the appropriate superview once the block has finished executing on each view + * + * @param block scope within which you can build up the constraints which you wish to apply to each view. + * + * @return Array of created MASConstraints + */ +- (NSArray *)mas_makeConstraints:(void (NS_NOESCAPE ^)(MASConstraintMaker *make))block; + +/** + * Creates a MASConstraintMaker with each view in the callee. + * Any constraints defined are added to each view or the appropriate superview once the block has finished executing on each view. + * If an existing constraint exists then it will be updated instead. + * + * @param block scope within which you can build up the constraints which you wish to apply to each view. + * + * @return Array of created/updated MASConstraints + */ +- (NSArray *)mas_updateConstraints:(void (NS_NOESCAPE ^)(MASConstraintMaker *make))block; + +/** + * Creates a MASConstraintMaker with each view in the callee. + * Any constraints defined are added to each view or the appropriate superview once the block has finished executing on each view. + * All constraints previously installed for the views will be removed. + * + * @param block scope within which you can build up the constraints which you wish to apply to each view. + * + * @return Array of created/updated MASConstraints + */ +- (NSArray *)mas_remakeConstraints:(void (NS_NOESCAPE ^)(MASConstraintMaker *make))block; + +/** + * distribute with fixed spacing + * + * @param axisType which axis to distribute items along + * @param fixedSpacing the spacing between each item + * @param leadSpacing the spacing before the first item and the container + * @param tailSpacing the spacing after the last item and the container + */ +- (void)mas_distributeViewsAlongAxis:(MASAxisType)axisType withFixedSpacing:(CGFloat)fixedSpacing leadSpacing:(CGFloat)leadSpacing tailSpacing:(CGFloat)tailSpacing; + +/** + * distribute with fixed item size + * + * @param axisType which axis to distribute items along + * @param fixedItemLength the fixed length of each item + * @param leadSpacing the spacing before the first item and the container + * @param tailSpacing the spacing after the last item and the container + */ +- (void)mas_distributeViewsAlongAxis:(MASAxisType)axisType withFixedItemLength:(CGFloat)fixedItemLength leadSpacing:(CGFloat)leadSpacing tailSpacing:(CGFloat)tailSpacing; + +@end diff --git a/Pods/Masonry/Masonry/NSArray+MASAdditions.m b/Pods/Masonry/Masonry/NSArray+MASAdditions.m new file mode 100644 index 0000000..831d8cd --- /dev/null +++ b/Pods/Masonry/Masonry/NSArray+MASAdditions.m @@ -0,0 +1,162 @@ +// +// NSArray+MASAdditions.m +// +// +// Created by Daniel Hammond on 11/26/13. +// +// + +#import "NSArray+MASAdditions.h" +#import "View+MASAdditions.h" + +@implementation NSArray (MASAdditions) + +- (NSArray *)mas_makeConstraints:(void(^)(MASConstraintMaker *make))block { + NSMutableArray *constraints = [NSMutableArray array]; + for (MAS_VIEW *view in self) { + NSAssert([view isKindOfClass:[MAS_VIEW class]], @"All objects in the array must be views"); + [constraints addObjectsFromArray:[view mas_makeConstraints:block]]; + } + return constraints; +} + +- (NSArray *)mas_updateConstraints:(void(^)(MASConstraintMaker *make))block { + NSMutableArray *constraints = [NSMutableArray array]; + for (MAS_VIEW *view in self) { + NSAssert([view isKindOfClass:[MAS_VIEW class]], @"All objects in the array must be views"); + [constraints addObjectsFromArray:[view mas_updateConstraints:block]]; + } + return constraints; +} + +- (NSArray *)mas_remakeConstraints:(void(^)(MASConstraintMaker *make))block { + NSMutableArray *constraints = [NSMutableArray array]; + for (MAS_VIEW *view in self) { + NSAssert([view isKindOfClass:[MAS_VIEW class]], @"All objects in the array must be views"); + [constraints addObjectsFromArray:[view mas_remakeConstraints:block]]; + } + return constraints; +} + +- (void)mas_distributeViewsAlongAxis:(MASAxisType)axisType withFixedSpacing:(CGFloat)fixedSpacing leadSpacing:(CGFloat)leadSpacing tailSpacing:(CGFloat)tailSpacing { + if (self.count < 2) { + NSAssert(self.count>1,@"views to distribute need to bigger than one"); + return; + } + + MAS_VIEW *tempSuperView = [self mas_commonSuperviewOfViews]; + if (axisType == MASAxisTypeHorizontal) { + MAS_VIEW *prev; + for (int i = 0; i < self.count; i++) { + MAS_VIEW *v = self[i]; + [v mas_makeConstraints:^(MASConstraintMaker *make) { + if (prev) { + make.width.equalTo(prev); + make.left.equalTo(prev.mas_right).offset(fixedSpacing); + if (i == self.count - 1) {//last one + make.right.equalTo(tempSuperView).offset(-tailSpacing); + } + } + else {//first one + make.left.equalTo(tempSuperView).offset(leadSpacing); + } + + }]; + prev = v; + } + } + else { + MAS_VIEW *prev; + for (int i = 0; i < self.count; i++) { + MAS_VIEW *v = self[i]; + [v mas_makeConstraints:^(MASConstraintMaker *make) { + if (prev) { + make.height.equalTo(prev); + make.top.equalTo(prev.mas_bottom).offset(fixedSpacing); + if (i == self.count - 1) {//last one + make.bottom.equalTo(tempSuperView).offset(-tailSpacing); + } + } + else {//first one + make.top.equalTo(tempSuperView).offset(leadSpacing); + } + + }]; + prev = v; + } + } +} + +- (void)mas_distributeViewsAlongAxis:(MASAxisType)axisType withFixedItemLength:(CGFloat)fixedItemLength leadSpacing:(CGFloat)leadSpacing tailSpacing:(CGFloat)tailSpacing { + if (self.count < 2) { + NSAssert(self.count>1,@"views to distribute need to bigger than one"); + return; + } + + MAS_VIEW *tempSuperView = [self mas_commonSuperviewOfViews]; + if (axisType == MASAxisTypeHorizontal) { + MAS_VIEW *prev; + for (int i = 0; i < self.count; i++) { + MAS_VIEW *v = self[i]; + [v mas_makeConstraints:^(MASConstraintMaker *make) { + make.width.equalTo(@(fixedItemLength)); + if (prev) { + if (i == self.count - 1) {//last one + make.right.equalTo(tempSuperView).offset(-tailSpacing); + } + else { + CGFloat offset = (1-(i/((CGFloat)self.count-1)))*(fixedItemLength+leadSpacing)-i*tailSpacing/(((CGFloat)self.count-1)); + make.right.equalTo(tempSuperView).multipliedBy(i/((CGFloat)self.count-1)).with.offset(offset); + } + } + else {//first one + make.left.equalTo(tempSuperView).offset(leadSpacing); + } + }]; + prev = v; + } + } + else { + MAS_VIEW *prev; + for (int i = 0; i < self.count; i++) { + MAS_VIEW *v = self[i]; + [v mas_makeConstraints:^(MASConstraintMaker *make) { + make.height.equalTo(@(fixedItemLength)); + if (prev) { + if (i == self.count - 1) {//last one + make.bottom.equalTo(tempSuperView).offset(-tailSpacing); + } + else { + CGFloat offset = (1-(i/((CGFloat)self.count-1)))*(fixedItemLength+leadSpacing)-i*tailSpacing/(((CGFloat)self.count-1)); + make.bottom.equalTo(tempSuperView).multipliedBy(i/((CGFloat)self.count-1)).with.offset(offset); + } + } + else {//first one + make.top.equalTo(tempSuperView).offset(leadSpacing); + } + }]; + prev = v; + } + } +} + +- (MAS_VIEW *)mas_commonSuperviewOfViews +{ + MAS_VIEW *commonSuperview = nil; + MAS_VIEW *previousView = nil; + for (id object in self) { + if ([object isKindOfClass:[MAS_VIEW class]]) { + MAS_VIEW *view = (MAS_VIEW *)object; + if (previousView) { + commonSuperview = [view mas_closestCommonSuperview:commonSuperview]; + } else { + commonSuperview = view; + } + previousView = view; + } + } + NSAssert(commonSuperview, @"Can't constrain views that do not share a common superview. Make sure that all the views in this array have been added into the same view hierarchy."); + return commonSuperview; +} + +@end diff --git a/Pods/Masonry/Masonry/NSArray+MASShorthandAdditions.h b/Pods/Masonry/Masonry/NSArray+MASShorthandAdditions.h new file mode 100644 index 0000000..8b47369 --- /dev/null +++ b/Pods/Masonry/Masonry/NSArray+MASShorthandAdditions.h @@ -0,0 +1,41 @@ +// +// NSArray+MASShorthandAdditions.h +// Masonry +// +// Created by Jonas Budelmann on 22/07/13. +// Copyright (c) 2013 Jonas Budelmann. All rights reserved. +// + +#import "NSArray+MASAdditions.h" + +#ifdef MAS_SHORTHAND + +/** + * Shorthand array additions without the 'mas_' prefixes, + * only enabled if MAS_SHORTHAND is defined + */ +@interface NSArray (MASShorthandAdditions) + +- (NSArray *)makeConstraints:(void(^)(MASConstraintMaker *make))block; +- (NSArray *)updateConstraints:(void(^)(MASConstraintMaker *make))block; +- (NSArray *)remakeConstraints:(void(^)(MASConstraintMaker *make))block; + +@end + +@implementation NSArray (MASShorthandAdditions) + +- (NSArray *)makeConstraints:(void(^)(MASConstraintMaker *))block { + return [self mas_makeConstraints:block]; +} + +- (NSArray *)updateConstraints:(void(^)(MASConstraintMaker *))block { + return [self mas_updateConstraints:block]; +} + +- (NSArray *)remakeConstraints:(void(^)(MASConstraintMaker *))block { + return [self mas_remakeConstraints:block]; +} + +@end + +#endif diff --git a/Pods/Masonry/Masonry/NSLayoutConstraint+MASDebugAdditions.h b/Pods/Masonry/Masonry/NSLayoutConstraint+MASDebugAdditions.h new file mode 100644 index 0000000..1279b4f --- /dev/null +++ b/Pods/Masonry/Masonry/NSLayoutConstraint+MASDebugAdditions.h @@ -0,0 +1,16 @@ +// +// NSLayoutConstraint+MASDebugAdditions.h +// Masonry +// +// Created by Jonas Budelmann on 3/08/13. +// Copyright (c) 2013 Jonas Budelmann. All rights reserved. +// + +#import "MASUtilities.h" + +/** + * makes debug and log output of NSLayoutConstraints more readable + */ +@interface NSLayoutConstraint (MASDebugAdditions) + +@end diff --git a/Pods/Masonry/Masonry/NSLayoutConstraint+MASDebugAdditions.m b/Pods/Masonry/Masonry/NSLayoutConstraint+MASDebugAdditions.m new file mode 100644 index 0000000..ab539a2 --- /dev/null +++ b/Pods/Masonry/Masonry/NSLayoutConstraint+MASDebugAdditions.m @@ -0,0 +1,146 @@ +// +// NSLayoutConstraint+MASDebugAdditions.m +// Masonry +// +// Created by Jonas Budelmann on 3/08/13. +// Copyright (c) 2013 Jonas Budelmann. All rights reserved. +// + +#import "NSLayoutConstraint+MASDebugAdditions.h" +#import "MASConstraint.h" +#import "MASLayoutConstraint.h" + +@implementation NSLayoutConstraint (MASDebugAdditions) + +#pragma mark - description maps + ++ (NSDictionary *)layoutRelationDescriptionsByValue { + static dispatch_once_t once; + static NSDictionary *descriptionMap; + dispatch_once(&once, ^{ + descriptionMap = @{ + @(NSLayoutRelationEqual) : @"==", + @(NSLayoutRelationGreaterThanOrEqual) : @">=", + @(NSLayoutRelationLessThanOrEqual) : @"<=", + }; + }); + return descriptionMap; +} + ++ (NSDictionary *)layoutAttributeDescriptionsByValue { + static dispatch_once_t once; + static NSDictionary *descriptionMap; + dispatch_once(&once, ^{ + descriptionMap = @{ + @(NSLayoutAttributeTop) : @"top", + @(NSLayoutAttributeLeft) : @"left", + @(NSLayoutAttributeBottom) : @"bottom", + @(NSLayoutAttributeRight) : @"right", + @(NSLayoutAttributeLeading) : @"leading", + @(NSLayoutAttributeTrailing) : @"trailing", + @(NSLayoutAttributeWidth) : @"width", + @(NSLayoutAttributeHeight) : @"height", + @(NSLayoutAttributeCenterX) : @"centerX", + @(NSLayoutAttributeCenterY) : @"centerY", + @(NSLayoutAttributeBaseline) : @"baseline", + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + @(NSLayoutAttributeFirstBaseline) : @"firstBaseline", + @(NSLayoutAttributeLastBaseline) : @"lastBaseline", +#endif + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) + @(NSLayoutAttributeLeftMargin) : @"leftMargin", + @(NSLayoutAttributeRightMargin) : @"rightMargin", + @(NSLayoutAttributeTopMargin) : @"topMargin", + @(NSLayoutAttributeBottomMargin) : @"bottomMargin", + @(NSLayoutAttributeLeadingMargin) : @"leadingMargin", + @(NSLayoutAttributeTrailingMargin) : @"trailingMargin", + @(NSLayoutAttributeCenterXWithinMargins) : @"centerXWithinMargins", + @(NSLayoutAttributeCenterYWithinMargins) : @"centerYWithinMargins", +#endif + + }; + + }); + return descriptionMap; +} + + ++ (NSDictionary *)layoutPriorityDescriptionsByValue { + static dispatch_once_t once; + static NSDictionary *descriptionMap; + dispatch_once(&once, ^{ +#if TARGET_OS_IPHONE || TARGET_OS_TV + descriptionMap = @{ + @(MASLayoutPriorityDefaultHigh) : @"high", + @(MASLayoutPriorityDefaultLow) : @"low", + @(MASLayoutPriorityDefaultMedium) : @"medium", + @(MASLayoutPriorityRequired) : @"required", + @(MASLayoutPriorityFittingSizeLevel) : @"fitting size", + }; +#elif TARGET_OS_MAC + descriptionMap = @{ + @(MASLayoutPriorityDefaultHigh) : @"high", + @(MASLayoutPriorityDragThatCanResizeWindow) : @"drag can resize window", + @(MASLayoutPriorityDefaultMedium) : @"medium", + @(MASLayoutPriorityWindowSizeStayPut) : @"window size stay put", + @(MASLayoutPriorityDragThatCannotResizeWindow) : @"drag cannot resize window", + @(MASLayoutPriorityDefaultLow) : @"low", + @(MASLayoutPriorityFittingSizeCompression) : @"fitting size", + @(MASLayoutPriorityRequired) : @"required", + }; +#endif + }); + return descriptionMap; +} + +#pragma mark - description override + ++ (NSString *)descriptionForObject:(id)obj { + if ([obj respondsToSelector:@selector(mas_key)] && [obj mas_key]) { + return [NSString stringWithFormat:@"%@:%@", [obj class], [obj mas_key]]; + } + return [NSString stringWithFormat:@"%@:%p", [obj class], obj]; +} + +- (NSString *)description { + NSMutableString *description = [[NSMutableString alloc] initWithString:@"<"]; + + [description appendString:[self.class descriptionForObject:self]]; + + [description appendFormat:@" %@", [self.class descriptionForObject:self.firstItem]]; + if (self.firstAttribute != NSLayoutAttributeNotAnAttribute) { + [description appendFormat:@".%@", self.class.layoutAttributeDescriptionsByValue[@(self.firstAttribute)]]; + } + + [description appendFormat:@" %@", self.class.layoutRelationDescriptionsByValue[@(self.relation)]]; + + if (self.secondItem) { + [description appendFormat:@" %@", [self.class descriptionForObject:self.secondItem]]; + } + if (self.secondAttribute != NSLayoutAttributeNotAnAttribute) { + [description appendFormat:@".%@", self.class.layoutAttributeDescriptionsByValue[@(self.secondAttribute)]]; + } + + if (self.multiplier != 1) { + [description appendFormat:@" * %g", self.multiplier]; + } + + if (self.secondAttribute == NSLayoutAttributeNotAnAttribute) { + [description appendFormat:@" %g", self.constant]; + } else { + if (self.constant) { + [description appendFormat:@" %@ %g", (self.constant < 0 ? @"-" : @"+"), ABS(self.constant)]; + } + } + + if (self.priority != MASLayoutPriorityRequired) { + [description appendFormat:@" ^%@", self.class.layoutPriorityDescriptionsByValue[@(self.priority)] ?: [NSNumber numberWithDouble:self.priority]]; + } + + [description appendString:@">"]; + return description; +} + +@end diff --git a/Pods/Masonry/Masonry/View+MASAdditions.h b/Pods/Masonry/Masonry/View+MASAdditions.h new file mode 100644 index 0000000..f7343d2 --- /dev/null +++ b/Pods/Masonry/Masonry/View+MASAdditions.h @@ -0,0 +1,111 @@ +// +// UIView+MASAdditions.h +// Masonry +// +// Created by Jonas Budelmann on 20/07/13. +// Copyright (c) 2013 cloudling. All rights reserved. +// + +#import "MASUtilities.h" +#import "MASConstraintMaker.h" +#import "MASViewAttribute.h" + +/** + * Provides constraint maker block + * and convience methods for creating MASViewAttribute which are view + NSLayoutAttribute pairs + */ +@interface MAS_VIEW (MASAdditions) + +/** + * following properties return a new MASViewAttribute with current view and appropriate NSLayoutAttribute + */ +@property (nonatomic, strong, readonly) MASViewAttribute *mas_left; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_top; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_right; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_bottom; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_leading; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_trailing; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_width; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_height; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_centerX; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_centerY; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_baseline; +@property (nonatomic, strong, readonly) MASViewAttribute *(^mas_attribute)(NSLayoutAttribute attr); + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + +@property (nonatomic, strong, readonly) MASViewAttribute *mas_firstBaseline; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_lastBaseline; + +#endif + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) + +@property (nonatomic, strong, readonly) MASViewAttribute *mas_leftMargin; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_rightMargin; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_topMargin; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_bottomMargin; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_leadingMargin; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_trailingMargin; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_centerXWithinMargins; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_centerYWithinMargins; + +#endif + +#if (__IPHONE_OS_VERSION_MAX_ALLOWED >= 110000) || (__TV_OS_VERSION_MAX_ALLOWED >= 110000) + +@property (nonatomic, strong, readonly) MASViewAttribute *mas_safeAreaLayoutGuide API_AVAILABLE(ios(11.0),tvos(11.0)); +@property (nonatomic, strong, readonly) MASViewAttribute *mas_safeAreaLayoutGuideTop API_AVAILABLE(ios(11.0),tvos(11.0)); +@property (nonatomic, strong, readonly) MASViewAttribute *mas_safeAreaLayoutGuideBottom API_AVAILABLE(ios(11.0),tvos(11.0)); +@property (nonatomic, strong, readonly) MASViewAttribute *mas_safeAreaLayoutGuideLeft API_AVAILABLE(ios(11.0),tvos(11.0)); +@property (nonatomic, strong, readonly) MASViewAttribute *mas_safeAreaLayoutGuideRight API_AVAILABLE(ios(11.0),tvos(11.0)); + +#endif + +/** + * a key to associate with this view + */ +@property (nonatomic, strong) id mas_key; + +/** + * Finds the closest common superview between this view and another view + * + * @param view other view + * + * @return returns nil if common superview could not be found + */ +- (instancetype)mas_closestCommonSuperview:(MAS_VIEW *)view; + +/** + * Creates a MASConstraintMaker with the callee view. + * Any constraints defined are added to the view or the appropriate superview once the block has finished executing + * + * @param block scope within which you can build up the constraints which you wish to apply to the view. + * + * @return Array of created MASConstraints + */ +- (NSArray *)mas_makeConstraints:(void(NS_NOESCAPE ^)(MASConstraintMaker *make))block; + +/** + * Creates a MASConstraintMaker with the callee view. + * Any constraints defined are added to the view or the appropriate superview once the block has finished executing. + * If an existing constraint exists then it will be updated instead. + * + * @param block scope within which you can build up the constraints which you wish to apply to the view. + * + * @return Array of created/updated MASConstraints + */ +- (NSArray *)mas_updateConstraints:(void(NS_NOESCAPE ^)(MASConstraintMaker *make))block; + +/** + * Creates a MASConstraintMaker with the callee view. + * Any constraints defined are added to the view or the appropriate superview once the block has finished executing. + * All constraints previously installed for the view will be removed. + * + * @param block scope within which you can build up the constraints which you wish to apply to the view. + * + * @return Array of created/updated MASConstraints + */ +- (NSArray *)mas_remakeConstraints:(void(NS_NOESCAPE ^)(MASConstraintMaker *make))block; + +@end diff --git a/Pods/Masonry/Masonry/View+MASAdditions.m b/Pods/Masonry/Masonry/View+MASAdditions.m new file mode 100644 index 0000000..4fa07b4 --- /dev/null +++ b/Pods/Masonry/Masonry/View+MASAdditions.m @@ -0,0 +1,186 @@ +// +// UIView+MASAdditions.m +// Masonry +// +// Created by Jonas Budelmann on 20/07/13. +// Copyright (c) 2013 cloudling. All rights reserved. +// + +#import "View+MASAdditions.h" +#import + +@implementation MAS_VIEW (MASAdditions) + +- (NSArray *)mas_makeConstraints:(void(^)(MASConstraintMaker *))block { + self.translatesAutoresizingMaskIntoConstraints = NO; + MASConstraintMaker *constraintMaker = [[MASConstraintMaker alloc] initWithView:self]; + block(constraintMaker); + return [constraintMaker install]; +} + +- (NSArray *)mas_updateConstraints:(void(^)(MASConstraintMaker *))block { + self.translatesAutoresizingMaskIntoConstraints = NO; + MASConstraintMaker *constraintMaker = [[MASConstraintMaker alloc] initWithView:self]; + constraintMaker.updateExisting = YES; + block(constraintMaker); + return [constraintMaker install]; +} + +- (NSArray *)mas_remakeConstraints:(void(^)(MASConstraintMaker *make))block { + self.translatesAutoresizingMaskIntoConstraints = NO; + MASConstraintMaker *constraintMaker = [[MASConstraintMaker alloc] initWithView:self]; + constraintMaker.removeExisting = YES; + block(constraintMaker); + return [constraintMaker install]; +} + +#pragma mark - NSLayoutAttribute properties + +- (MASViewAttribute *)mas_left { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeLeft]; +} + +- (MASViewAttribute *)mas_top { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeTop]; +} + +- (MASViewAttribute *)mas_right { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeRight]; +} + +- (MASViewAttribute *)mas_bottom { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeBottom]; +} + +- (MASViewAttribute *)mas_leading { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeLeading]; +} + +- (MASViewAttribute *)mas_trailing { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeTrailing]; +} + +- (MASViewAttribute *)mas_width { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeWidth]; +} + +- (MASViewAttribute *)mas_height { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeHeight]; +} + +- (MASViewAttribute *)mas_centerX { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeCenterX]; +} + +- (MASViewAttribute *)mas_centerY { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeCenterY]; +} + +- (MASViewAttribute *)mas_baseline { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeBaseline]; +} + +- (MASViewAttribute *(^)(NSLayoutAttribute))mas_attribute +{ + return ^(NSLayoutAttribute attr) { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:attr]; + }; +} + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + +- (MASViewAttribute *)mas_firstBaseline { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeFirstBaseline]; +} +- (MASViewAttribute *)mas_lastBaseline { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeLastBaseline]; +} + +#endif + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) + +- (MASViewAttribute *)mas_leftMargin { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeLeftMargin]; +} + +- (MASViewAttribute *)mas_rightMargin { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeRightMargin]; +} + +- (MASViewAttribute *)mas_topMargin { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeTopMargin]; +} + +- (MASViewAttribute *)mas_bottomMargin { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeBottomMargin]; +} + +- (MASViewAttribute *)mas_leadingMargin { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeLeadingMargin]; +} + +- (MASViewAttribute *)mas_trailingMargin { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeTrailingMargin]; +} + +- (MASViewAttribute *)mas_centerXWithinMargins { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeCenterXWithinMargins]; +} + +- (MASViewAttribute *)mas_centerYWithinMargins { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeCenterYWithinMargins]; +} + +#endif + +#if (__IPHONE_OS_VERSION_MAX_ALLOWED >= 110000) || (__TV_OS_VERSION_MAX_ALLOWED >= 110000) + +- (MASViewAttribute *)mas_safeAreaLayoutGuide { + return [[MASViewAttribute alloc] initWithView:self item:self.safeAreaLayoutGuide layoutAttribute:NSLayoutAttributeBottom]; +} +- (MASViewAttribute *)mas_safeAreaLayoutGuideTop { + return [[MASViewAttribute alloc] initWithView:self item:self.safeAreaLayoutGuide layoutAttribute:NSLayoutAttributeTop]; +} +- (MASViewAttribute *)mas_safeAreaLayoutGuideBottom { + return [[MASViewAttribute alloc] initWithView:self item:self.safeAreaLayoutGuide layoutAttribute:NSLayoutAttributeBottom]; +} +- (MASViewAttribute *)mas_safeAreaLayoutGuideLeft { + return [[MASViewAttribute alloc] initWithView:self item:self.safeAreaLayoutGuide layoutAttribute:NSLayoutAttributeLeft]; +} +- (MASViewAttribute *)mas_safeAreaLayoutGuideRight { + return [[MASViewAttribute alloc] initWithView:self item:self.safeAreaLayoutGuide layoutAttribute:NSLayoutAttributeRight]; +} + +#endif + +#pragma mark - associated properties + +- (id)mas_key { + return objc_getAssociatedObject(self, @selector(mas_key)); +} + +- (void)setMas_key:(id)key { + objc_setAssociatedObject(self, @selector(mas_key), key, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#pragma mark - heirachy + +- (instancetype)mas_closestCommonSuperview:(MAS_VIEW *)view { + MAS_VIEW *closestCommonSuperview = nil; + + MAS_VIEW *secondViewSuperview = view; + while (!closestCommonSuperview && secondViewSuperview) { + MAS_VIEW *firstViewSuperview = self; + while (!closestCommonSuperview && firstViewSuperview) { + if (secondViewSuperview == firstViewSuperview) { + closestCommonSuperview = secondViewSuperview; + } + firstViewSuperview = firstViewSuperview.superview; + } + secondViewSuperview = secondViewSuperview.superview; + } + return closestCommonSuperview; +} + +@end diff --git a/Pods/Masonry/Masonry/View+MASShorthandAdditions.h b/Pods/Masonry/Masonry/View+MASShorthandAdditions.h new file mode 100644 index 0000000..1c19a94 --- /dev/null +++ b/Pods/Masonry/Masonry/View+MASShorthandAdditions.h @@ -0,0 +1,133 @@ +// +// UIView+MASShorthandAdditions.h +// Masonry +// +// Created by Jonas Budelmann on 22/07/13. +// Copyright (c) 2013 Jonas Budelmann. All rights reserved. +// + +#import "View+MASAdditions.h" + +#ifdef MAS_SHORTHAND + +/** + * Shorthand view additions without the 'mas_' prefixes, + * only enabled if MAS_SHORTHAND is defined + */ +@interface MAS_VIEW (MASShorthandAdditions) + +@property (nonatomic, strong, readonly) MASViewAttribute *left; +@property (nonatomic, strong, readonly) MASViewAttribute *top; +@property (nonatomic, strong, readonly) MASViewAttribute *right; +@property (nonatomic, strong, readonly) MASViewAttribute *bottom; +@property (nonatomic, strong, readonly) MASViewAttribute *leading; +@property (nonatomic, strong, readonly) MASViewAttribute *trailing; +@property (nonatomic, strong, readonly) MASViewAttribute *width; +@property (nonatomic, strong, readonly) MASViewAttribute *height; +@property (nonatomic, strong, readonly) MASViewAttribute *centerX; +@property (nonatomic, strong, readonly) MASViewAttribute *centerY; +@property (nonatomic, strong, readonly) MASViewAttribute *baseline; +@property (nonatomic, strong, readonly) MASViewAttribute *(^attribute)(NSLayoutAttribute attr); + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + +@property (nonatomic, strong, readonly) MASViewAttribute *firstBaseline; +@property (nonatomic, strong, readonly) MASViewAttribute *lastBaseline; + +#endif + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) + +@property (nonatomic, strong, readonly) MASViewAttribute *leftMargin; +@property (nonatomic, strong, readonly) MASViewAttribute *rightMargin; +@property (nonatomic, strong, readonly) MASViewAttribute *topMargin; +@property (nonatomic, strong, readonly) MASViewAttribute *bottomMargin; +@property (nonatomic, strong, readonly) MASViewAttribute *leadingMargin; +@property (nonatomic, strong, readonly) MASViewAttribute *trailingMargin; +@property (nonatomic, strong, readonly) MASViewAttribute *centerXWithinMargins; +@property (nonatomic, strong, readonly) MASViewAttribute *centerYWithinMargins; + +#endif + +#if (__IPHONE_OS_VERSION_MAX_ALLOWED >= 110000) || (__TV_OS_VERSION_MAX_ALLOWED >= 110000) + +@property (nonatomic, strong, readonly) MASViewAttribute *safeAreaLayoutGuideTop API_AVAILABLE(ios(11.0),tvos(11.0)); +@property (nonatomic, strong, readonly) MASViewAttribute *safeAreaLayoutGuideBottom API_AVAILABLE(ios(11.0),tvos(11.0)); +@property (nonatomic, strong, readonly) MASViewAttribute *safeAreaLayoutGuideLeft API_AVAILABLE(ios(11.0),tvos(11.0)); +@property (nonatomic, strong, readonly) MASViewAttribute *safeAreaLayoutGuideRight API_AVAILABLE(ios(11.0),tvos(11.0)); + +#endif + +- (NSArray *)makeConstraints:(void(^)(MASConstraintMaker *make))block; +- (NSArray *)updateConstraints:(void(^)(MASConstraintMaker *make))block; +- (NSArray *)remakeConstraints:(void(^)(MASConstraintMaker *make))block; + +@end + +#define MAS_ATTR_FORWARD(attr) \ +- (MASViewAttribute *)attr { \ + return [self mas_##attr]; \ +} + +@implementation MAS_VIEW (MASShorthandAdditions) + +MAS_ATTR_FORWARD(top); +MAS_ATTR_FORWARD(left); +MAS_ATTR_FORWARD(bottom); +MAS_ATTR_FORWARD(right); +MAS_ATTR_FORWARD(leading); +MAS_ATTR_FORWARD(trailing); +MAS_ATTR_FORWARD(width); +MAS_ATTR_FORWARD(height); +MAS_ATTR_FORWARD(centerX); +MAS_ATTR_FORWARD(centerY); +MAS_ATTR_FORWARD(baseline); + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + +MAS_ATTR_FORWARD(firstBaseline); +MAS_ATTR_FORWARD(lastBaseline); + +#endif + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) + +MAS_ATTR_FORWARD(leftMargin); +MAS_ATTR_FORWARD(rightMargin); +MAS_ATTR_FORWARD(topMargin); +MAS_ATTR_FORWARD(bottomMargin); +MAS_ATTR_FORWARD(leadingMargin); +MAS_ATTR_FORWARD(trailingMargin); +MAS_ATTR_FORWARD(centerXWithinMargins); +MAS_ATTR_FORWARD(centerYWithinMargins); + +#endif + +#if (__IPHONE_OS_VERSION_MAX_ALLOWED >= 110000) || (__TV_OS_VERSION_MAX_ALLOWED >= 110000) + +MAS_ATTR_FORWARD(safeAreaLayoutGuideTop); +MAS_ATTR_FORWARD(safeAreaLayoutGuideBottom); +MAS_ATTR_FORWARD(safeAreaLayoutGuideLeft); +MAS_ATTR_FORWARD(safeAreaLayoutGuideRight); + +#endif + +- (MASViewAttribute *(^)(NSLayoutAttribute))attribute { + return [self mas_attribute]; +} + +- (NSArray *)makeConstraints:(void(NS_NOESCAPE ^)(MASConstraintMaker *))block { + return [self mas_makeConstraints:block]; +} + +- (NSArray *)updateConstraints:(void(NS_NOESCAPE ^)(MASConstraintMaker *))block { + return [self mas_updateConstraints:block]; +} + +- (NSArray *)remakeConstraints:(void(NS_NOESCAPE ^)(MASConstraintMaker *))block { + return [self mas_remakeConstraints:block]; +} + +@end + +#endif diff --git a/Pods/Masonry/Masonry/ViewController+MASAdditions.h b/Pods/Masonry/Masonry/ViewController+MASAdditions.h new file mode 100644 index 0000000..79fd1fa --- /dev/null +++ b/Pods/Masonry/Masonry/ViewController+MASAdditions.h @@ -0,0 +1,30 @@ +// +// UIViewController+MASAdditions.h +// Masonry +// +// Created by Craig Siemens on 2015-06-23. +// +// + +#import "MASUtilities.h" +#import "MASConstraintMaker.h" +#import "MASViewAttribute.h" + +#ifdef MAS_VIEW_CONTROLLER + +@interface MAS_VIEW_CONTROLLER (MASAdditions) + +/** + * following properties return a new MASViewAttribute with appropriate UILayoutGuide and NSLayoutAttribute + */ +@property (nonatomic, strong, readonly) MASViewAttribute *mas_topLayoutGuide; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_bottomLayoutGuide; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_topLayoutGuideTop; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_topLayoutGuideBottom; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_bottomLayoutGuideTop; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_bottomLayoutGuideBottom; + + +@end + +#endif diff --git a/Pods/Masonry/Masonry/ViewController+MASAdditions.m b/Pods/Masonry/Masonry/ViewController+MASAdditions.m new file mode 100644 index 0000000..2f5139f --- /dev/null +++ b/Pods/Masonry/Masonry/ViewController+MASAdditions.m @@ -0,0 +1,39 @@ +// +// UIViewController+MASAdditions.m +// Masonry +// +// Created by Craig Siemens on 2015-06-23. +// +// + +#import "ViewController+MASAdditions.h" + +#ifdef MAS_VIEW_CONTROLLER + +@implementation MAS_VIEW_CONTROLLER (MASAdditions) + +- (MASViewAttribute *)mas_topLayoutGuide { + return [[MASViewAttribute alloc] initWithView:self.view item:self.topLayoutGuide layoutAttribute:NSLayoutAttributeBottom]; +} +- (MASViewAttribute *)mas_topLayoutGuideTop { + return [[MASViewAttribute alloc] initWithView:self.view item:self.topLayoutGuide layoutAttribute:NSLayoutAttributeTop]; +} +- (MASViewAttribute *)mas_topLayoutGuideBottom { + return [[MASViewAttribute alloc] initWithView:self.view item:self.topLayoutGuide layoutAttribute:NSLayoutAttributeBottom]; +} + +- (MASViewAttribute *)mas_bottomLayoutGuide { + return [[MASViewAttribute alloc] initWithView:self.view item:self.bottomLayoutGuide layoutAttribute:NSLayoutAttributeTop]; +} +- (MASViewAttribute *)mas_bottomLayoutGuideTop { + return [[MASViewAttribute alloc] initWithView:self.view item:self.bottomLayoutGuide layoutAttribute:NSLayoutAttributeTop]; +} +- (MASViewAttribute *)mas_bottomLayoutGuideBottom { + return [[MASViewAttribute alloc] initWithView:self.view item:self.bottomLayoutGuide layoutAttribute:NSLayoutAttributeBottom]; +} + + + +@end + +#endif diff --git a/Pods/Masonry/README.md b/Pods/Masonry/README.md new file mode 100644 index 0000000..d428657 --- /dev/null +++ b/Pods/Masonry/README.md @@ -0,0 +1,415 @@ +# Masonry [![Build Status](https://travis-ci.org/SnapKit/Masonry.svg?branch=master)](https://travis-ci.org/SnapKit/Masonry) [![Coverage Status](https://img.shields.io/coveralls/SnapKit/Masonry.svg?style=flat-square)](https://coveralls.io/r/SnapKit/Masonry) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) ![Pod Version](https://img.shields.io/cocoapods/v/Masonry.svg?style=flat) + +**Masonry is still actively maintained, we are committed to fixing bugs and merging good quality PRs from the wider community. However if you're using Swift in your project, we recommend using [SnapKit](https://github.com/SnapKit/SnapKit) as it provides better type safety with a simpler API.** + +Masonry is a light-weight layout framework which wraps AutoLayout with a nicer syntax. Masonry has its own layout DSL which provides a chainable way of describing your NSLayoutConstraints which results in layout code that is more concise and readable. +Masonry supports iOS and Mac OS X. + +For examples take a look at the **Masonry iOS Examples** project in the Masonry workspace. You will need to run `pod install` after downloading. + +## What's wrong with NSLayoutConstraints? + +Under the hood Auto Layout is a powerful and flexible way of organising and laying out your views. However creating constraints from code is verbose and not very descriptive. +Imagine a simple example in which you want to have a view fill its superview but inset by 10 pixels on every side +```obj-c +UIView *superview = self.view; + +UIView *view1 = [[UIView alloc] init]; +view1.translatesAutoresizingMaskIntoConstraints = NO; +view1.backgroundColor = [UIColor greenColor]; +[superview addSubview:view1]; + +UIEdgeInsets padding = UIEdgeInsetsMake(10, 10, 10, 10); + +[superview addConstraints:@[ + + //view1 constraints + [NSLayoutConstraint constraintWithItem:view1 + attribute:NSLayoutAttributeTop + relatedBy:NSLayoutRelationEqual + toItem:superview + attribute:NSLayoutAttributeTop + multiplier:1.0 + constant:padding.top], + + [NSLayoutConstraint constraintWithItem:view1 + attribute:NSLayoutAttributeLeft + relatedBy:NSLayoutRelationEqual + toItem:superview + attribute:NSLayoutAttributeLeft + multiplier:1.0 + constant:padding.left], + + [NSLayoutConstraint constraintWithItem:view1 + attribute:NSLayoutAttributeBottom + relatedBy:NSLayoutRelationEqual + toItem:superview + attribute:NSLayoutAttributeBottom + multiplier:1.0 + constant:-padding.bottom], + + [NSLayoutConstraint constraintWithItem:view1 + attribute:NSLayoutAttributeRight + relatedBy:NSLayoutRelationEqual + toItem:superview + attribute:NSLayoutAttributeRight + multiplier:1 + constant:-padding.right], + + ]]; +``` +Even with such a simple example the code needed is quite verbose and quickly becomes unreadable when you have more than 2 or 3 views. +Another option is to use Visual Format Language (VFL), which is a bit less long winded. +However the ASCII type syntax has its own pitfalls and its also a bit harder to animate as `NSLayoutConstraint constraintsWithVisualFormat:` returns an array. + +## Prepare to meet your Maker! + +Heres the same constraints created using MASConstraintMaker + +```obj-c +UIEdgeInsets padding = UIEdgeInsetsMake(10, 10, 10, 10); + +[view1 mas_makeConstraints:^(MASConstraintMaker *make) { + make.top.equalTo(superview.mas_top).with.offset(padding.top); //with is an optional semantic filler + make.left.equalTo(superview.mas_left).with.offset(padding.left); + make.bottom.equalTo(superview.mas_bottom).with.offset(-padding.bottom); + make.right.equalTo(superview.mas_right).with.offset(-padding.right); +}]; +``` +Or even shorter + +```obj-c +[view1 mas_makeConstraints:^(MASConstraintMaker *make) { + make.edges.equalTo(superview).with.insets(padding); +}]; +``` + +Also note in the first example we had to add the constraints to the superview `[superview addConstraints:...`. +Masonry however will automagically add constraints to the appropriate view. + +Masonry will also call `view1.translatesAutoresizingMaskIntoConstraints = NO;` for you. + +## Not all things are created equal + +> `.equalTo` equivalent to **NSLayoutRelationEqual** + +> `.lessThanOrEqualTo` equivalent to **NSLayoutRelationLessThanOrEqual** + +> `.greaterThanOrEqualTo` equivalent to **NSLayoutRelationGreaterThanOrEqual** + +These three equality constraints accept one argument which can be any of the following: + +#### 1. MASViewAttribute + +```obj-c +make.centerX.lessThanOrEqualTo(view2.mas_left); +``` + +MASViewAttribute | NSLayoutAttribute +------------------------- | -------------------------- +view.mas_left | NSLayoutAttributeLeft +view.mas_right | NSLayoutAttributeRight +view.mas_top | NSLayoutAttributeTop +view.mas_bottom | NSLayoutAttributeBottom +view.mas_leading | NSLayoutAttributeLeading +view.mas_trailing | NSLayoutAttributeTrailing +view.mas_width | NSLayoutAttributeWidth +view.mas_height | NSLayoutAttributeHeight +view.mas_centerX | NSLayoutAttributeCenterX +view.mas_centerY | NSLayoutAttributeCenterY +view.mas_baseline | NSLayoutAttributeBaseline + +#### 2. UIView/NSView + +if you want view.left to be greater than or equal to label.left : +```obj-c +//these two constraints are exactly the same +make.left.greaterThanOrEqualTo(label); +make.left.greaterThanOrEqualTo(label.mas_left); +``` + +#### 3. NSNumber + +Auto Layout allows width and height to be set to constant values. +if you want to set view to have a minimum and maximum width you could pass a number to the equality blocks: +```obj-c +//width >= 200 && width <= 400 +make.width.greaterThanOrEqualTo(@200); +make.width.lessThanOrEqualTo(@400) +``` + +However Auto Layout does not allow alignment attributes such as left, right, centerY etc to be set to constant values. +So if you pass a NSNumber for these attributes Masonry will turn these into constraints relative to the view’s superview ie: +```obj-c +//creates view.left = view.superview.left + 10 +make.left.lessThanOrEqualTo(@10) +``` + +Instead of using NSNumber, you can use primitives and structs to build your constraints, like so: +```obj-c +make.top.mas_equalTo(42); +make.height.mas_equalTo(20); +make.size.mas_equalTo(CGSizeMake(50, 100)); +make.edges.mas_equalTo(UIEdgeInsetsMake(10, 0, 10, 0)); +make.left.mas_equalTo(view).mas_offset(UIEdgeInsetsMake(10, 0, 10, 0)); +``` + +By default, macros which support [autoboxing](https://en.wikipedia.org/wiki/Autoboxing#Autoboxing) are prefixed with `mas_`. Unprefixed versions are available by defining `MAS_SHORTHAND_GLOBALS` before importing Masonry. + +#### 4. NSArray + +An array of a mixture of any of the previous types +```obj-c +make.height.equalTo(@[view1.mas_height, view2.mas_height]); +make.height.equalTo(@[view1, view2]); +make.left.equalTo(@[view1, @100, view3.right]); +```` + +## Learn to prioritize + +> `.priority` allows you to specify an exact priority + +> `.priorityHigh` equivalent to **UILayoutPriorityDefaultHigh** + +> `.priorityMedium` is half way between high and low + +> `.priorityLow` equivalent to **UILayoutPriorityDefaultLow** + +Priorities are can be tacked on to the end of a constraint chain like so: +```obj-c +make.left.greaterThanOrEqualTo(label.mas_left).with.priorityLow(); + +make.top.equalTo(label.mas_top).with.priority(600); +``` + +## Composition, composition, composition + +Masonry also gives you a few convenience methods which create multiple constraints at the same time. These are called MASCompositeConstraints + +#### edges + +```obj-c +// make top, left, bottom, right equal view2 +make.edges.equalTo(view2); + +// make top = superview.top + 5, left = superview.left + 10, +// bottom = superview.bottom - 15, right = superview.right - 20 +make.edges.equalTo(superview).insets(UIEdgeInsetsMake(5, 10, 15, 20)) +``` + +#### size + +```obj-c +// make width and height greater than or equal to titleLabel +make.size.greaterThanOrEqualTo(titleLabel) + +// make width = superview.width + 100, height = superview.height - 50 +make.size.equalTo(superview).sizeOffset(CGSizeMake(100, -50)) +``` + +#### center +```obj-c +// make centerX and centerY = button1 +make.center.equalTo(button1) + +// make centerX = superview.centerX - 5, centerY = superview.centerY + 10 +make.center.equalTo(superview).centerOffset(CGPointMake(-5, 10)) +``` + +You can chain view attributes for increased readability: + +```obj-c +// All edges but the top should equal those of the superview +make.left.right.and.bottom.equalTo(superview); +make.top.equalTo(otherView); +``` + +## Hold on for dear life + +Sometimes you need modify existing constraints in order to animate or remove/replace constraints. +In Masonry there are a few different approaches to updating constraints. + +#### 1. References +You can hold on to a reference of a particular constraint by assigning the result of a constraint make expression to a local variable or a class property. +You could also reference multiple constraints by storing them away in an array. + +```obj-c +// in public/private interface +@property (nonatomic, strong) MASConstraint *topConstraint; + +... + +// when making constraints +[view1 mas_makeConstraints:^(MASConstraintMaker *make) { + self.topConstraint = make.top.equalTo(superview.mas_top).with.offset(padding.top); + make.left.equalTo(superview.mas_left).with.offset(padding.left); +}]; + +... +// then later you can call +[self.topConstraint uninstall]; +``` + +#### 2. mas_updateConstraints +Alternatively if you are only updating the constant value of the constraint you can use the convience method `mas_updateConstraints` instead of `mas_makeConstraints` + +```obj-c +// this is Apple's recommended place for adding/updating constraints +// this method can get called multiple times in response to setNeedsUpdateConstraints +// which can be called by UIKit internally or in your code if you need to trigger an update to your constraints +- (void)updateConstraints { + [self.growingButton mas_updateConstraints:^(MASConstraintMaker *make) { + make.center.equalTo(self); + make.width.equalTo(@(self.buttonSize.width)).priorityLow(); + make.height.equalTo(@(self.buttonSize.height)).priorityLow(); + make.width.lessThanOrEqualTo(self); + make.height.lessThanOrEqualTo(self); + }]; + + //according to apple super should be called at end of method + [super updateConstraints]; +} +``` + +### 3. mas_remakeConstraints +`mas_updateConstraints` is useful for updating a set of constraints, but doing anything beyond updating constant values can get exhausting. That's where `mas_remakeConstraints` comes in. + +`mas_remakeConstraints` is similar to `mas_updateConstraints`, but instead of updating constant values, it will remove all of its constraints before installing them again. This lets you provide different constraints without having to keep around references to ones which you want to remove. + +```obj-c +- (void)changeButtonPosition { + [self.button mas_remakeConstraints:^(MASConstraintMaker *make) { + make.size.equalTo(self.buttonSize); + + if (topLeft) { + make.top.and.left.offset(10); + } else { + make.bottom.and.right.offset(-10); + } + }]; +} +``` + +You can find more detailed examples of all three approaches in the **Masonry iOS Examples** project. + +## When the ^&*!@ hits the fan! + +Laying out your views doesn't always goto plan. So when things literally go pear shaped, you don't want to be looking at console output like this: + +```obj-c +Unable to simultaneously satisfy constraints.....blah blah blah.... +( + "=5000)]>", + "", + "", + "" +) + +Will attempt to recover by breaking constraint +=5000)]> +``` + +Masonry adds a category to NSLayoutConstraint which overrides the default implementation of `- (NSString *)description`. +Now you can give meaningful names to views and constraints, and also easily pick out the constraints created by Masonry. + +which means your console output can now look like this: + +```obj-c +Unable to simultaneously satisfy constraints......blah blah blah.... +( + "", + "= 5000>", + "", + "" +) + +Will attempt to recover by breaking constraint += 5000> +``` + +For an example of how to set this up take a look at the **Masonry iOS Examples** project in the Masonry workspace. + +## Where should I create my constraints? + +```objc +@implementation DIYCustomView + +- (id)init { + self = [super init]; + if (!self) return nil; + + // --- Create your views here --- + self.button = [[UIButton alloc] init]; + + return self; +} + +// tell UIKit that you are using AutoLayout ++ (BOOL)requiresConstraintBasedLayout { + return YES; +} + +// this is Apple's recommended place for adding/updating constraints +- (void)updateConstraints { + + // --- remake/update constraints here + [self.button remakeConstraints:^(MASConstraintMaker *make) { + make.width.equalTo(@(self.buttonSize.width)); + make.height.equalTo(@(self.buttonSize.height)); + }]; + + //according to apple super should be called at end of method + [super updateConstraints]; +} + +- (void)didTapButton:(UIButton *)button { + // --- Do your changes ie change variables that affect your layout etc --- + self.buttonSize = CGSize(200, 200); + + // tell constraints they need updating + [self setNeedsUpdateConstraints]; +} + +@end +``` + +## Installation +Use the [orsome](http://www.youtube.com/watch?v=YaIZF8uUTtk) [CocoaPods](http://github.com/CocoaPods/CocoaPods). + +In your Podfile +>`pod 'Masonry'` + +If you want to use masonry without all those pesky 'mas_' prefixes. Add #define MAS_SHORTHAND to your prefix.pch before importing Masonry +>`#define MAS_SHORTHAND` + +Get busy Masoning +>`#import "Masonry.h"` + +## Code Snippets + +Copy the included code snippets to ``~/Library/Developer/Xcode/UserData/CodeSnippets`` to write your masonry blocks at lightning speed! + +`mas_make` -> ` [<#view#> mas_makeConstraints:^(MASConstraintMaker *make) { + <#code#> + }];` + +`mas_update` -> ` [<#view#> mas_updateConstraints:^(MASConstraintMaker *make) { + <#code#> + }];` + +`mas_remake` -> ` [<#view#> mas_remakeConstraints:^(MASConstraintMaker *make) { + <#code#> + }];` + +## Features +* Not limited to subset of Auto Layout. Anything NSLayoutConstraint can do, Masonry can do too! +* Great debug support, give your views and constraints meaningful names. +* Constraints read like sentences. +* No crazy macro magic. Masonry won't pollute the global namespace with macros. +* Not string or dictionary based and hence you get compile time checking. + +## TODO +* Eye candy +* Mac example project +* More tests and examples + diff --git a/Pods/Pods.xcodeproj/project.pbxproj b/Pods/Pods.xcodeproj/project.pbxproj new file mode 100644 index 0000000..5dec3e7 --- /dev/null +++ b/Pods/Pods.xcodeproj/project.pbxproj @@ -0,0 +1,3135 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 77; + objects = { + +/* Begin PBXAggregateTarget section */ + 4A68CFD979D413A619DF631BB121D98F /* Bugly */ = { + isa = PBXAggregateTarget; + buildConfigurationList = 9CC7AA793D9397C15E010F8242EE1046 /* Build configuration list for PBXAggregateTarget "Bugly" */; + buildPhases = ( + ); + dependencies = ( + ); + name = Bugly; + }; +/* End PBXAggregateTarget section */ + +/* Begin PBXBuildFile section */ + 00DAE48C9A4FBCD1FCAA922CA57B45F9 /* SDWebImageDownloaderRequestModifier.m in Sources */ = {isa = PBXBuildFile; fileRef = 06B71FC03BF92D5C7E3E050752C0E06C /* SDWebImageDownloaderRequestModifier.m */; }; + 042D40751BD2F51FBE9FECD4707CBBE9 /* SDDeviceHelper.h in Headers */ = {isa = PBXBuildFile; fileRef = AC2514CF7A7B043E035CFB079E6FB5A0 /* SDDeviceHelper.h */; settings = {ATTRIBUTES = (Private, ); }; }; + 0453019EC6578A67B82CF569EC765546 /* SDFileAttributeHelper.h in Headers */ = {isa = PBXBuildFile; fileRef = D13BE3E84BFB9462CF54B22B35F89ADC /* SDFileAttributeHelper.h */; settings = {ATTRIBUTES = (Private, ); }; }; + 05E2B7C1DB7528A0BBEA1521BE0DBAF1 /* MASViewAttribute.h in Headers */ = {isa = PBXBuildFile; fileRef = 2CCE60F6B1B48663415E0A4BC9662B33 /* MASViewAttribute.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 06C4E233E7977DB81A24482E69B2D7D7 /* UIImage+Transform.m in Sources */ = {isa = PBXBuildFile; fileRef = 14C4334FE2177757C132CBBCD17C11B5 /* UIImage+Transform.m */; }; + 08719ABCE689ED74FE7486B1E49DAA6C /* MJRefreshBackStateFooter.h in Headers */ = {isa = PBXBuildFile; fileRef = 1F8526067D06A009E96461455DBA1B40 /* MJRefreshBackStateFooter.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 089F3C4BAA46A37EC5763DD312771021 /* SDImageIOAnimatedCoder.h in Headers */ = {isa = PBXBuildFile; fileRef = 13F0EE17165FE326BF8D348C181A1E71 /* SDImageIOAnimatedCoder.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 08D50C5AC969A3701B6F9137CF3A10F1 /* UIImage+ForceDecode.m in Sources */ = {isa = PBXBuildFile; fileRef = 840FE4FBC8DFDB4B1238B06FEA5AF259 /* UIImage+ForceDecode.m */; }; + 08DF3A0323B44ABF3FAAE0F291F8566E /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 18BF12DFF6188AFC43E6F26853B048F9 /* Foundation.framework */; }; + 09A2ACBC8CE1761652EAA20886AEFE10 /* SDImageCoder.h in Headers */ = {isa = PBXBuildFile; fileRef = B3A54C7306CBDB1BC3189CCF492C92DE /* SDImageCoder.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 0B0E6CECDF516BC83756C1D5515A725B /* SDAsyncBlockOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = FF49D60AE2D0E7C2857D88C5353083C3 /* SDAsyncBlockOperation.m */; }; + 0BADC710EA22BBCD76E59748C2A56ECF /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = A9F5CF889820DAD55268C3832155A2E1 /* PrivacyInfo.xcprivacy */; }; + 0EF10747EF2A02413E84BD5EF7C87A4B /* MJRefreshNormalHeader.m in Sources */ = {isa = PBXBuildFile; fileRef = E7D9B8C39A19DDF2CE7619D44758B033 /* MJRefreshNormalHeader.m */; }; + 0F1D0F5DCC8C94A4C684DF846D14F436 /* SDWebImagePrefetcher.m in Sources */ = {isa = PBXBuildFile; fileRef = 916FC91BADACF2A6F0FF12F1385FC1D4 /* SDWebImagePrefetcher.m */; }; + 0FF9F459ED16719292443A4C99B52B20 /* SDImageCache.m in Sources */ = {isa = PBXBuildFile; fileRef = 8332CB32D0FA2CE8D910AA5A9BE18D8B /* SDImageCache.m */; }; + 10017B43AC38C3A89D7AC1376C6E7066 /* SDImageLoadersManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 80E9D6278C5650A6AD05F331651F6DEB /* SDImageLoadersManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 11C929E6BFB46F981685446F26DCE605 /* MJRefreshAutoFooter.m in Sources */ = {isa = PBXBuildFile; fileRef = 568638C925360332377ACFB503131A76 /* MJRefreshAutoFooter.m */; }; + 126496714AD564062A8C10787CC01B8B /* MJFoundation.m in Sources */ = {isa = PBXBuildFile; fileRef = 4830CF5BA96EF2AA3AC7496D62A49A0D /* MJFoundation.m */; }; + 14943D0EE97A4966510A86F5C3FC66A5 /* MJExtension-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = C5D0E76AC56695893DB1713CA7212B8C /* MJExtension-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 14CA284AC4FF1EED75E785641EE98034 /* SDImageCacheConfig.h in Headers */ = {isa = PBXBuildFile; fileRef = 19E0C6994863739B688E61DCE0E025C3 /* SDImageCacheConfig.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 165F1C9CBD621828C788A3018D0426C5 /* SDImageAPNGCoder.h in Headers */ = {isa = PBXBuildFile; fileRef = 7C38C5957F4EAC459AB28A71622C865C /* SDImageAPNGCoder.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 16D7DCB7CC985C33EEC41B371C029C84 /* SDWebImage-SDWebImage in Resources */ = {isa = PBXBuildFile; fileRef = CF1281E58AA1045D4B7F33FC56691C42 /* SDWebImage-SDWebImage */; }; + 1708C1D28B421C4AD310426D1695CE77 /* SDAnimatedImage.m in Sources */ = {isa = PBXBuildFile; fileRef = DC6CF0A46A4D9FFFBA2057678DF1978B /* SDAnimatedImage.m */; }; + 1754DD5511A7BF462B116F70B0D4006A /* SDWebImageOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = 76F97ACAD92849B1F665FD0FF282B3C8 /* SDWebImageOperation.m */; }; + 1830558A4D2D63C8E76BC3136D8213F9 /* UIImage+ExtendedCacheData.h in Headers */ = {isa = PBXBuildFile; fileRef = 377FB4D51134D774594E6EAF0BB4DFAA /* UIImage+ExtendedCacheData.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 18660FA595DBE133BB784E813A7122A8 /* SDImageHEICCoder.m in Sources */ = {isa = PBXBuildFile; fileRef = 20B21087EF80825B8FC789A191A95BAA /* SDImageHEICCoder.m */; }; + 186B573F1BEB8A23419A02814A7741DB /* MJRefreshFooter.m in Sources */ = {isa = PBXBuildFile; fileRef = EAFBBF7E1270693113CDF0C1D9CBB512 /* MJRefreshFooter.m */; }; + 18AD90784D549657DF51BC8377DA3085 /* SDWebImageDownloaderResponseModifier.h in Headers */ = {isa = PBXBuildFile; fileRef = D99D7FCB3FD62B8D8BF11087E1D6E47F /* SDWebImageDownloaderResponseModifier.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 1B6CE67196EE181E6B56788EFC7E00D3 /* SDImageGIFCoder.h in Headers */ = {isa = PBXBuildFile; fileRef = B60142D76441D9D2B7BA4991E7523577 /* SDImageGIFCoder.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 1BC44E2FDD197D5210A23C9CCF1A906B /* SDWebImageCompat.m in Sources */ = {isa = PBXBuildFile; fileRef = 7980625AB48FABAF33EDB825FF587011 /* SDWebImageCompat.m */; }; + 1C73BC7EEF39CC3D3A21EACAD858413D /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 970B39752136D5831550118975DC4A91 /* PrivacyInfo.xcprivacy */; }; + 1C8B70C74291A3076746C3B18781568E /* SDImageCachesManagerOperation.h in Headers */ = {isa = PBXBuildFile; fileRef = 9DBD448EB576D346FBA1D20A1BD13F1D /* SDImageCachesManagerOperation.h */; settings = {ATTRIBUTES = (Private, ); }; }; + 1EA011B45EC780B434507AFB3D9647ED /* NSObject+MJCoding.h in Headers */ = {isa = PBXBuildFile; fileRef = E200433A892F1843DD9B8C05E3C226BE /* NSObject+MJCoding.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 1ECC5F320AEFB120081358B4FFB7442F /* NSString+MJExtension.m in Sources */ = {isa = PBXBuildFile; fileRef = E310A44D757B0556FA6F2882D1565A8C /* NSString+MJExtension.m */; }; + 2055774CD703B52DABFB1CC588394A94 /* MJExtension-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = FB792580573132155A61C027392EF360 /* MJExtension-dummy.m */; }; + 20D618EF3EA5E3BE96DA24D36E3CA9EF /* SDAsyncBlockOperation.h in Headers */ = {isa = PBXBuildFile; fileRef = 42134A400043398C196C2BDF73B21075 /* SDAsyncBlockOperation.h */; settings = {ATTRIBUTES = (Private, ); }; }; + 22516EA77E7120000632C30BD9A03927 /* UIScrollView+MJExtension.h in Headers */ = {isa = PBXBuildFile; fileRef = C55407E10212267DCB2FC49D3260EF48 /* UIScrollView+MJExtension.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 24E8E4ED0B5D988E3346E6638619F4E4 /* SDImageFrame.m in Sources */ = {isa = PBXBuildFile; fileRef = 9B7D77CB378449CF4A7041A3EA89C102 /* SDImageFrame.m */; }; + 24E963C1D6245F98BAC8A0ACCB7DE987 /* NSBundle+MJRefresh.m in Sources */ = {isa = PBXBuildFile; fileRef = 37DCC80FE271D2095A398F8D8F22C7E7 /* NSBundle+MJRefresh.m */; }; + 2567FE276DB76481DEFC7DDFE7D775CC /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 18BF12DFF6188AFC43E6F26853B048F9 /* Foundation.framework */; }; + 288CD3416B265CAC1300D7938167AE66 /* MJPropertyKey.h in Headers */ = {isa = PBXBuildFile; fileRef = 250848691A5C0FC662F372FB71E83AE5 /* MJPropertyKey.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 288D796F3F7B9F42690E24A3B1018B2C /* SDImageIOAnimatedCoder.m in Sources */ = {isa = PBXBuildFile; fileRef = E2EAE5E554B07101C740E6CB128A93A0 /* SDImageIOAnimatedCoder.m */; }; + 28BA9702905AA2B4C1E9E4878032D4E4 /* MJRefreshConst.h in Headers */ = {isa = PBXBuildFile; fileRef = BE6C3AB94897685F9464AA252C4EFB17 /* MJRefreshConst.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29F7F0E98FD26A96364DBACD7D5F237A /* SDWebImageDownloader.h in Headers */ = {isa = PBXBuildFile; fileRef = 00031196DD7FBA552243DCF5CEB19ABD /* SDWebImageDownloader.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 2DC44A09A6C9D6DC7D1BDA2DFCF99EE3 /* MJRefreshConfig.m in Sources */ = {isa = PBXBuildFile; fileRef = 2EFA72948DE45F4B6CAD9DA5C625D259 /* MJRefreshConfig.m */; }; + 2DDD48230ED9E8068C7E439D79B99A8E /* SDInternalMacros.h in Headers */ = {isa = PBXBuildFile; fileRef = A294AA5EAB4FD3CAF8C4A072117591C1 /* SDInternalMacros.h */; settings = {ATTRIBUTES = (Private, ); }; }; + 2F6D9BEA582A2DBB70A6C3B2FC2DB91E /* SDWebImageDownloaderResponseModifier.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F51691B6717B6D9E4E3FE0977CF3163 /* SDWebImageDownloaderResponseModifier.m */; }; + 3187FF0C251D1B78BE87F64F6F6E944A /* SDWebImageTransition.m in Sources */ = {isa = PBXBuildFile; fileRef = A11030FED687E26E2A7953D880C8DDD7 /* SDWebImageTransition.m */; }; + 31DC2EC78AD1F8241AE6051EF9E73B0A /* SDWebImageDefine.m in Sources */ = {isa = PBXBuildFile; fileRef = 6DE36A434A8BD3593CCBD95090373332 /* SDWebImageDefine.m */; }; + 320DE42AF3CFE11FF785FEB1A7E6547B /* SDImageFramePool.m in Sources */ = {isa = PBXBuildFile; fileRef = BF3675A98BB80F2630D08AB3BE31E1B7 /* SDImageFramePool.m */; }; + 321F87DA34863DC5C977323BAEDB2B55 /* NSObject+MJCoding.m in Sources */ = {isa = PBXBuildFile; fileRef = 9D403D54754F62E7ECBA2668B217E5FD /* NSObject+MJCoding.m */; }; + 325CA20B9271F3E008234E1518B79061 /* MJRefresh-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = AECAC2F59ABD4A78D2B73C898E485890 /* MJRefresh-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 327BA3DDA513422E632D3DA4A8FC60EC /* MJRefresh-MJRefresh.Privacy in Resources */ = {isa = PBXBuildFile; fileRef = 7E3097CFEFDA621E9FB0E62009FF87FC /* MJRefresh-MJRefresh.Privacy */; }; + 32ACEDCEBE0507A82D6323114A1C74F1 /* UIImageView+WebCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 23078E14E88B14332A0B4BE57A2A9488 /* UIImageView+WebCache.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 32F2B91621A2F8F9AD7C8E2B224D73F6 /* SDWebImageDownloaderDecryptor.m in Sources */ = {isa = PBXBuildFile; fileRef = 1C27DC7D5FFFA31A8EA1C7B95F3079E1 /* SDWebImageDownloaderDecryptor.m */; }; + 3331A013D48A5063B483A51B7E9068ED /* AFURLSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 7506ED7F0118C1C5FE230328CCC6543E /* AFURLSessionManager.m */; }; + 33D3587AF629B2FA21554DA002D6ACB8 /* SDImageCachesManager.m in Sources */ = {isa = PBXBuildFile; fileRef = F0CEEBB5DD628DB121172299787A25A9 /* SDImageCachesManager.m */; }; + 34B28D4F0168194B6EFAC0520EB7A7F4 /* NSImage+Compatibility.h in Headers */ = {isa = PBXBuildFile; fileRef = F76369243ECD96D54BBB9C4A97EB6946 /* NSImage+Compatibility.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 36F4B09E7C71DCC5CEC6057814033C37 /* UIView+WebCache.h in Headers */ = {isa = PBXBuildFile; fileRef = A87E9EA0B6E9AB8C1E29A3AE50F278CB /* UIView+WebCache.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 3777CD89D444CBBB48AE323B303F3FC7 /* ImageIO.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DDAE741F085915AF2475C918F1A17466 /* ImageIO.framework */; }; + 37B890ABDC7DD441E6AA662325D412E6 /* MASConstraint.h in Headers */ = {isa = PBXBuildFile; fileRef = 71C9A7FB9BC0D7C0FA902D0643B08962 /* MASConstraint.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 38938E604A7D708E6378A44063EF3512 /* UIImageView+WebCache.m in Sources */ = {isa = PBXBuildFile; fileRef = C6C465F665338FA163A2F6623C933047 /* UIImageView+WebCache.m */; }; + 3A1AD84C0DC3C256418CC46739024E96 /* SDmetamacros.h in Headers */ = {isa = PBXBuildFile; fileRef = 61B4061AC178FEE58C9618133524CF08 /* SDmetamacros.h */; settings = {ATTRIBUTES = (Private, ); }; }; + 3A2FCB914F6EADED828FF05F7E9132AE /* UIView+MJExtension.h in Headers */ = {isa = PBXBuildFile; fileRef = 35F55EE8682F170A101CA85DD55D1B58 /* UIView+MJExtension.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 3B8EDFF69A68ABD3735E0C6931CA5C95 /* AFURLSessionManager.h in Headers */ = {isa = PBXBuildFile; fileRef = A95F96D9DAA700949C3A302C92FD9231 /* AFURLSessionManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 3C7815EEC599DD7D42FDEF19B2FF1563 /* SDWebImageOptionsProcessor.h in Headers */ = {isa = PBXBuildFile; fileRef = B9DF6B027952E0BE3781007ECC6436E7 /* SDWebImageOptionsProcessor.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 3C7EAECB8C573E714C818BA04EB33773 /* UIImage+MultiFormat.h in Headers */ = {isa = PBXBuildFile; fileRef = 897B6BFD5EA50E7440FD4FA3769B3C78 /* UIImage+MultiFormat.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 3C8F2F868D0C361CAF43E53CDB8EB631 /* SDWebImageCacheSerializer.h in Headers */ = {isa = PBXBuildFile; fileRef = 4A71363040CF6A8E6D918CEF79A555D5 /* SDWebImageCacheSerializer.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 3CE201A6CFF26BD49792F9A8E4C822A5 /* Pods-keyBoard-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 969A9A842778EFB5D62826500DFF4E11 /* Pods-keyBoard-dummy.m */; }; + 3D0BBFEC1921CE71BC240DC18D8BE540 /* SDImageTransformer.m in Sources */ = {isa = PBXBuildFile; fileRef = 6E7A746456C4F5E2C887572055F6A833 /* SDImageTransformer.m */; }; + 3FE4CEC187728FF5B98CECE3D92744E7 /* Pods-CustomKeyboard-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 9DDD0462C32F55EF5E9CB1056459809F /* Pods-CustomKeyboard-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 3FF7252DD60182221BB1E5A167C41A07 /* UIProgressView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = 018B520CB407C3492F13C3767C15E377 /* UIProgressView+AFNetworking.m */; }; + 416DA8B2997381F954DBA6E6A53DA4A2 /* NSData+ImageContentType.m in Sources */ = {isa = PBXBuildFile; fileRef = 90687AA744E720C17FD8600B60F43FF5 /* NSData+ImageContentType.m */; }; + 425C9EA28FBEB7F7FC09A3F4A88C5955 /* SDWebImageError.m in Sources */ = {isa = PBXBuildFile; fileRef = B509365346F676352BBC6630F5F1FADB /* SDWebImageError.m */; }; + 442F468E261A1106C291BF52BDBF9DB7 /* MJRefreshHeader.h in Headers */ = {isa = PBXBuildFile; fileRef = 724FB5172055CF20AE6E6F4D007D8038 /* MJRefreshHeader.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 44CD842019B1CEA681F820F37A30B7C4 /* SDImageFramePool.h in Headers */ = {isa = PBXBuildFile; fileRef = 12C162655386843E5BE2582AC09CA762 /* SDImageFramePool.h */; settings = {ATTRIBUTES = (Private, ); }; }; + 452C940762F65B125C216F73B369F583 /* MJRefreshStateTrailer.m in Sources */ = {isa = PBXBuildFile; fileRef = 34B9AAE9B2C02781F4AC71AEDB56A439 /* MJRefreshStateTrailer.m */; }; + 4571A0EA37DC84F39E3830D38A1531AB /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5BA0325112AB8CA7AB613D1A8ED2DB65 /* UIKit.framework */; }; + 45E1583D7EF53489B82C4CA2AD1AD0CF /* MJRefreshBackFooter.h in Headers */ = {isa = PBXBuildFile; fileRef = 3126B87E909122AFEE37CA26F800E7D9 /* MJRefreshBackFooter.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 4688743B7B845309486559EB7BD5D147 /* SDWebImageCompat.h in Headers */ = {isa = PBXBuildFile; fileRef = 7B6867FF0B2276E04032D8E5C44B4EB9 /* SDWebImageCompat.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 475B4F3E71C293065AAFDB1888696CF6 /* MJRefreshBackGifFooter.h in Headers */ = {isa = PBXBuildFile; fileRef = 29AFC65F883E204F73DDE040C829BC77 /* MJRefreshBackGifFooter.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 48916DE9521F627589300512ECC2D4A5 /* NSButton+WebCache.m in Sources */ = {isa = PBXBuildFile; fileRef = 008AD8F77F87E2DC5C0DB4CD71AC5858 /* NSButton+WebCache.m */; }; + 4B2C2AE16AE3DDA7417AFCF7952588F1 /* SDImageAssetManager.h in Headers */ = {isa = PBXBuildFile; fileRef = F7A20DE3DDDA450D1997F9A3184CD3C6 /* SDImageAssetManager.h */; settings = {ATTRIBUTES = (Private, ); }; }; + 4D2C79AB2D24CFEC864F08D913CE7692 /* SDImageCodersManager.m in Sources */ = {isa = PBXBuildFile; fileRef = C3EC2E3BBB3895884BB4AA3B74A54476 /* SDImageCodersManager.m */; }; + 4DCA75BFE1558CE59DFC56607E49B3D2 /* MJRefreshConfig.h in Headers */ = {isa = PBXBuildFile; fileRef = BEC2871B1357A63D88FCC0144C7847CD /* MJRefreshConfig.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 4ED05DB3E43FF6AE1FA22130B2B50F05 /* UIImage+MemoryCacheCost.h in Headers */ = {isa = PBXBuildFile; fileRef = 4797723C6D7C918B816F46FCFB028F6F /* UIImage+MemoryCacheCost.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 506FC58999564A737C745F2590E9B4D5 /* AFHTTPSessionManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 1C60E3EC4F7CE664E3A6586ED2AC0ED5 /* AFHTTPSessionManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 5111A0A0934551CD2B9DDB1A1CA79FA7 /* SDAnimatedImageRep.m in Sources */ = {isa = PBXBuildFile; fileRef = 9954286F43C39384A1EADABA9AAE0B0D /* SDAnimatedImageRep.m */; }; + 512B9661FC34235E0EEB3A6D3E319B88 /* MJPropertyType.m in Sources */ = {isa = PBXBuildFile; fileRef = 7842E350E0D12563DE7C0EB363356BF8 /* MJPropertyType.m */; }; + 5163FC6D715F6881B1FA1AB13DCEF870 /* UICollectionViewLayout+MJRefresh.h in Headers */ = {isa = PBXBuildFile; fileRef = 24B89B49F862DFF8218AA2D11CEDFD3E /* UICollectionViewLayout+MJRefresh.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 5174DD2019966DFDC21B8864453ED3DE /* NSObject+MJClass.m in Sources */ = {isa = PBXBuildFile; fileRef = 5A50D4A4631B759E5D73FDFF78C8BF75 /* NSObject+MJClass.m */; }; + 523235228A1C021C67F2E3776A922DC5 /* MJRefreshTrailer.h in Headers */ = {isa = PBXBuildFile; fileRef = B6011963612818816E2CF40CED8B0112 /* MJRefreshTrailer.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 526485EF6D2B62B24DB59122FB94BD42 /* SDDeviceHelper.m in Sources */ = {isa = PBXBuildFile; fileRef = 4090C24D16A324EB9D2A6747886BD217 /* SDDeviceHelper.m */; }; + 5308E660E723C11E7691D311FD59C459 /* SDDisplayLink.m in Sources */ = {isa = PBXBuildFile; fileRef = 48E4A519DF8188F67D6109DB1AF82FF9 /* SDDisplayLink.m */; }; + 53433003112C4FE271EC985803862B61 /* SDWebImageCacheKeyFilter.h in Headers */ = {isa = PBXBuildFile; fileRef = 9802609AB0266E444A1BD29FA119D9BC /* SDWebImageCacheKeyFilter.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 54E268C32915CF908E7AA776909B45EB /* MJRefreshConst.m in Sources */ = {isa = PBXBuildFile; fileRef = 8BECBF70665658E16C4E9DDD74C7161A /* MJRefreshConst.m */; }; + 55F7C7F055A18044497F8C88CAE34118 /* SDImageCachesManagerOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = 305FF55ADA3393924EFC2D4B6D38166D /* SDImageCachesManagerOperation.m */; }; + 561420A20DC0A84258A902E9EB69A15A /* MJRefreshAutoFooter.h in Headers */ = {isa = PBXBuildFile; fileRef = 7D4327E5DC3980134C42B829E8798AA4 /* MJRefreshAutoFooter.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 564714D075CF51356D3D8437846AA6EB /* AFURLRequestSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = 74446596F2A689B17D9187482A194EEC /* AFURLRequestSerialization.m */; }; + 56D8A7EAE4D72FF6C23421CAB6F21504 /* MJPropertyType.h in Headers */ = {isa = PBXBuildFile; fileRef = 950F7A4DEA1A2D31E4A650C9526788F7 /* MJPropertyType.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 56E800EB3B2BE8AE0BA45A30974D7920 /* Masonry-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 5E8106411081DD6C7F5FE7804947412C /* Masonry-dummy.m */; }; + 58F7CE37BB4CB3BE806B68A502E6E1A7 /* SDWeakProxy.h in Headers */ = {isa = PBXBuildFile; fileRef = 1F0E8534D3C055E4D5D27EBF7422DA74 /* SDWeakProxy.h */; settings = {ATTRIBUTES = (Private, ); }; }; + 596180E0EC9F46D12BA840DC4AA62659 /* UIImage+MemoryCacheCost.m in Sources */ = {isa = PBXBuildFile; fileRef = EA1E48B813787CAC28E89E7F260BFCD4 /* UIImage+MemoryCacheCost.m */; }; + 597E390C0BBB75B8045B651C487C2034 /* SDImageAWebPCoder.m in Sources */ = {isa = PBXBuildFile; fileRef = DFD5A14F9DC74814903A901B625C5A94 /* SDImageAWebPCoder.m */; }; + 5A6D3BE92C77ED70C397567996DFAEB9 /* AFHTTPSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 8C0AB8960CBA6D24923E096B9378691C /* AFHTTPSessionManager.m */; }; + 5AF22814CD055B553AD9D78BE54B94E1 /* UIProgressView+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = EAE5F401F42AA242D6CAE9E463DE5CD4 /* UIProgressView+AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 5B08596E856E4CC2F34A8A2372F9F764 /* NSArray+MASAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = F934ACD20FEDAB980427B3D001DF8312 /* NSArray+MASAdditions.m */; }; + 5BB6B99986FD7111B3AEBE931C7F507B /* MJRefreshAutoStateFooter.h in Headers */ = {isa = PBXBuildFile; fileRef = 3526591F674CF19FB39EF872089A7F49 /* MJRefreshAutoStateFooter.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 5BD5D9B8F61C124A62C75D9AC36A07BD /* MJRefreshTrailer.m in Sources */ = {isa = PBXBuildFile; fileRef = B1CE88DD0007C23B107D2BD3A6AB545B /* MJRefreshTrailer.m */; }; + 5C8279C226EB028B044C5A0F4AC5A91A /* SDAssociatedObject.h in Headers */ = {isa = PBXBuildFile; fileRef = 34E2AA501576A0C5221012B9066EC56A /* SDAssociatedObject.h */; settings = {ATTRIBUTES = (Private, ); }; }; + 5DCBA14510E091D6A1CE499B08B794B5 /* UIImage+Metadata.h in Headers */ = {isa = PBXBuildFile; fileRef = 03DE7669ACCB33ED7598791177D4881A /* UIImage+Metadata.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 5DFCBADAC7D0FAC82C84A6C8E7BF1DA6 /* MJRefreshStateHeader.h in Headers */ = {isa = PBXBuildFile; fileRef = A20073D67775A184A6AEF2667BC7628C /* MJRefreshStateHeader.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 5E10328A83E05D0015D7459FAAEF121D /* SDGraphicsImageRenderer.h in Headers */ = {isa = PBXBuildFile; fileRef = 5FD6594A1D1613C90FF5EF2CBD5CE123 /* SDGraphicsImageRenderer.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 5F45735DF355530CC955066D3C007E19 /* MASViewConstraint.h in Headers */ = {isa = PBXBuildFile; fileRef = 266F6A7CA0ABF9B26D746459A14BAEBA /* MASViewConstraint.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 5FDC4239F7B651092BF582D0F460BAD4 /* UIView+MJExtension.m in Sources */ = {isa = PBXBuildFile; fileRef = 06B650CAE141ABD90E360415151BC9B9 /* UIView+MJExtension.m */; }; + 61461B0D9D7B81C3F8D24066D9A19DCE /* MJRefreshGifHeader.h in Headers */ = {isa = PBXBuildFile; fileRef = F4E10DADB58D42AEAD6CD268CEB583E8 /* MJRefreshGifHeader.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 61507E402F1F7C58BF119995A0479A22 /* NSArray+MASShorthandAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = 1DA8FCC29DBFD3824ADEAD9F14A76E86 /* NSArray+MASShorthandAdditions.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 616A8338C42FB01748DF1BDDA944858D /* UIView+WebCache.m in Sources */ = {isa = PBXBuildFile; fileRef = 7D3CFDF279C9B9946089A89EFB72A50D /* UIView+WebCache.m */; }; + 61857C821395B868C65A8FFE4DA1B4E3 /* MJExtension.h in Headers */ = {isa = PBXBuildFile; fileRef = 569FA95248CF0B824C3928196386FFC2 /* MJExtension.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 62FE895DF9D65A2955A275D909ECBE18 /* SDAnimatedImageView.m in Sources */ = {isa = PBXBuildFile; fileRef = F0C38163E5AA6D4BEAA1C7E79C82A930 /* SDAnimatedImageView.m */; }; + 67178A8153B1A2F1D0D544B8093E23C5 /* SDAnimatedImageView+WebCache.m in Sources */ = {isa = PBXBuildFile; fileRef = 0C6DD7AD3672258C4407B4269B490F27 /* SDAnimatedImageView+WebCache.m */; }; + 676775CB29378BB6CA3CA5992E9C6A99 /* SDImageIOAnimatedCoderInternal.h in Headers */ = {isa = PBXBuildFile; fileRef = 0CB3E312C9D65596A37072C76944B850 /* SDImageIOAnimatedCoderInternal.h */; settings = {ATTRIBUTES = (Private, ); }; }; + 69345CBCB31076EBF8A2C5885AF973AB /* MJRefreshComponent.h in Headers */ = {isa = PBXBuildFile; fileRef = E553AE6B35449F8CB4BAA4FFE1DCAFAC /* MJRefreshComponent.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 694B8697854A776E32032999B2EF1FEA /* UIImage+Metadata.m in Sources */ = {isa = PBXBuildFile; fileRef = 46F91B0801CEBD1D73003708566CC913 /* UIImage+Metadata.m */; }; + 69A06A02F52EB26259FAD1DF6B121BE1 /* SDCallbackQueue.m in Sources */ = {isa = PBXBuildFile; fileRef = AF26D1DF8BE4D63027161EEBE6FDE7AE /* SDCallbackQueue.m */; }; + 69AB6A513D5F36D7360FEF4FDA1D60D0 /* UIView+WebCacheState.h in Headers */ = {isa = PBXBuildFile; fileRef = DC6DB03243923516662807D789FF26B1 /* UIView+WebCacheState.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 69E353C99C6EEA3C93CCF2E526460B9D /* UIScrollView+MJRefresh.h in Headers */ = {isa = PBXBuildFile; fileRef = 4C64CBB1952BF537420E489E4AF7DED5 /* UIScrollView+MJRefresh.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 6A19379E3B0370EDA447743C9B1A1379 /* UIImageView+HighlightedWebCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 982D370CD4E116E0C1917E832541C530 /* UIImageView+HighlightedWebCache.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 6B0978C9398336656EE309E62060AEAB /* SDImageAssetManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 19F5C3BFE7C9E2977EB241266B257ABE /* SDImageAssetManager.m */; }; + 6B5C3592B5E911E833D067D0BC785B1A /* SDImageFrame.h in Headers */ = {isa = PBXBuildFile; fileRef = AB8EC26A51378B3F4C5559E371607480 /* SDImageFrame.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 6C85CA8D99E50C137D056B6057DAC58A /* UIRefreshControl+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = B070DCCCA22D6ECC24DC0BD5CCEF5372 /* UIRefreshControl+AFNetworking.m */; }; + 6CA0B4A9E7B2957063163BC673F355CD /* AFAutoPurgingImageCache.m in Sources */ = {isa = PBXBuildFile; fileRef = 3FBCEF9827DD721BAF021C98F7311D30 /* AFAutoPurgingImageCache.m */; }; + 6DE6C7F0FA965828E4FCE687BF75FBBE /* MJRefreshAutoNormalFooter.m in Sources */ = {isa = PBXBuildFile; fileRef = 7E6DD5C54D7EC67B674C64E88446BAA7 /* MJRefreshAutoNormalFooter.m */; }; + 6E66305665DBCFBCF5B2480BF705D500 /* SDWebImageTransition.h in Headers */ = {isa = PBXBuildFile; fileRef = 575E3DAA2F5DDC8FBD895B8BEA5FB8C6 /* SDWebImageTransition.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 6EFEEE3AE22E97DCEC4F5A3B88F56FC7 /* SDImageLoader.m in Sources */ = {isa = PBXBuildFile; fileRef = 7869EB02C0774141B550180F17DBF9F0 /* SDImageLoader.m */; }; + 6F3637EE643EABB1DE9212EA68649A64 /* UIColor+SDHexString.m in Sources */ = {isa = PBXBuildFile; fileRef = 10E420AEEA134E4CDDBAA68DEA103561 /* UIColor+SDHexString.m */; }; + 7074EA7FCC90B4967A437F5C43496828 /* SDDisplayLink.h in Headers */ = {isa = PBXBuildFile; fileRef = 078FC3682AC6F2B8020DD6D0F6A1A818 /* SDDisplayLink.h */; settings = {ATTRIBUTES = (Private, ); }; }; + 711D32EF4A9901567A488291603BF906 /* SDWebImage.h in Headers */ = {isa = PBXBuildFile; fileRef = 67DDCFED9CF39A1F995D9E7B12E35A7E /* SDWebImage.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 71538A1D21015F459964BA625D5EE90A /* NSObject+MJClass.h in Headers */ = {isa = PBXBuildFile; fileRef = 25ABF76DAF311B44A4F41DD3F9F04644 /* NSObject+MJClass.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 717F76926C7BCB5B10C3037AD9239084 /* SDImageIOCoder.m in Sources */ = {isa = PBXBuildFile; fileRef = 21EE020A32A9ADF76D7C1AF1A9B28D63 /* SDImageIOCoder.m */; }; + 71BEB1D9532900291A5A24B1C038516F /* UIColor+SDHexString.h in Headers */ = {isa = PBXBuildFile; fileRef = 851329DB564FCDDAD9A52952F487E28D /* UIColor+SDHexString.h */; settings = {ATTRIBUTES = (Private, ); }; }; + 71F2B8CBB99087F348C472230200586F /* SDGraphicsImageRenderer.m in Sources */ = {isa = PBXBuildFile; fileRef = 661BCD3C752D21E81C83DA14D3C4502A /* SDGraphicsImageRenderer.m */; }; + 724991CA89C46BAFBC08264D94D86484 /* AFURLRequestSerialization.h in Headers */ = {isa = PBXBuildFile; fileRef = 5DD19473CA2658646B964B6124A31FB9 /* AFURLRequestSerialization.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 74C474676C69A80BEC29B0F55FDF4D19 /* UIView+WebCacheState.m in Sources */ = {isa = PBXBuildFile; fileRef = 197BBC12418F4C1E7719181019D1E9EA /* UIView+WebCacheState.m */; }; + 74E069F8C9E22C0E37F261A5AB03A613 /* SDWebImageDownloaderConfig.m in Sources */ = {isa = PBXBuildFile; fileRef = 1E8EE46DFF5945CB5FDB220509F5E1A0 /* SDWebImageDownloaderConfig.m */; }; + 752822FE3F5092322D18FEC4533B79A9 /* SDWebImageDownloader.m in Sources */ = {isa = PBXBuildFile; fileRef = F104350C0F7D19687DAC6BD75101DA7F /* SDWebImageDownloader.m */; }; + 75771A97B77FA30A0175A81B480F80EF /* UIImage+ForceDecode.h in Headers */ = {isa = PBXBuildFile; fileRef = EA46C1DE7820870BF842553EA6A951F9 /* UIImage+ForceDecode.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 772CF8E9CD02ECA4275B6173E2110E80 /* View+MASShorthandAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = E5886305209187E582C024335BD55AE9 /* View+MASShorthandAdditions.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 7873F2F89CD0A435FAB776BC27BFB56A /* MJExtension-MJExtension in Resources */ = {isa = PBXBuildFile; fileRef = 43EAAD2AB7E6B407E80E95F643F93D22 /* MJExtension-MJExtension */; }; + 7902D28FC9EF5AFEB452F508C7F266B1 /* MJRefreshAutoNormalFooter.h in Headers */ = {isa = PBXBuildFile; fileRef = 0073EB182F9CC003B9721B132AC0082F /* MJRefreshAutoNormalFooter.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 7989A6E79BFA78440C39F568D972305C /* MJRefresh.h in Headers */ = {isa = PBXBuildFile; fileRef = 2D2A2C7E78B1029B85E812A9CC5D4F58 /* MJRefresh.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 7A4EB9ED5D4E03170FFE61FCB299687B /* SDAnimatedImagePlayer.m in Sources */ = {isa = PBXBuildFile; fileRef = B20A669086F5506692603D3336437ABD /* SDAnimatedImagePlayer.m */; }; + 7C45DBA62EE045C4922404182F6393B8 /* SDWebImageError.h in Headers */ = {isa = PBXBuildFile; fileRef = 646B483EDAD1F8B7F96981EB5E185F2E /* SDWebImageError.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 7C5505A2D3F2A697A5F324787061F4B7 /* MASConstraint+Private.h in Headers */ = {isa = PBXBuildFile; fileRef = 5AC074355067D4E88EB993DD28E44948 /* MASConstraint+Private.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 7F10C0D094C74F2FA4CD38C7FD77B0A8 /* WKWebView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = 71A4B6E144674403F50435C67561B1BB /* WKWebView+AFNetworking.m */; }; + 7F886FC2763F0BF1625A24EE4F94C04D /* UIRefreshControl+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 0044E51493E8CC5F8C46E1EC18F97722 /* UIRefreshControl+AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 7FA8C78DB021A7731D30D80C102DE042 /* NSObject+MJKeyValue.m in Sources */ = {isa = PBXBuildFile; fileRef = C23DF793769699E27A02E0B30615EF6F /* NSObject+MJKeyValue.m */; }; + 7FF8A56511E71D6FEC966BF9FEE135B5 /* AFNetworkActivityIndicatorManager.h in Headers */ = {isa = PBXBuildFile; fileRef = D875CFB5AA1591E80BD3A95A94255894 /* AFNetworkActivityIndicatorManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 813BE4C96A6D39C13EC50C6CD164F0AF /* MASConstraintMaker.h in Headers */ = {isa = PBXBuildFile; fileRef = F9CEF650A6E8658ECF7704A7EE2E7452 /* MASConstraintMaker.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 81A5635CEA2AD9623E30CAE9AFC3BF65 /* NSBundle+MJRefresh.h in Headers */ = {isa = PBXBuildFile; fileRef = 2E459098B6FF83AA9172F97696B64090 /* NSBundle+MJRefresh.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 83530BF68848CD2C4A79A1FD69B304A5 /* SDImageGIFCoder.m in Sources */ = {isa = PBXBuildFile; fileRef = 42FE2C6A18379D9944FBBA606FB88133 /* SDImageGIFCoder.m */; }; + 83A4F2816C1B3F072E1A26A34C3BC4AC /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 18BF12DFF6188AFC43E6F26853B048F9 /* Foundation.framework */; }; + 8414CFEEB64ACA817EB88D2FEADDA3B3 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 18BF12DFF6188AFC43E6F26853B048F9 /* Foundation.framework */; }; + 854807558DCB972EDDFC1D00032BA6E4 /* SDWebImageDownloaderConfig.h in Headers */ = {isa = PBXBuildFile; fileRef = 8A926EA8E3863425810DDC585C464587 /* SDWebImageDownloaderConfig.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 85AB23275E9D19394969235E5DC2300E /* MJRefreshHeader.m in Sources */ = {isa = PBXBuildFile; fileRef = F74EE2D92793519D84E4B72CD6AB0C63 /* MJRefreshHeader.m */; }; + 85C0B4EE334B9972299E62DE61A4BB56 /* SDImageLoadersManager.m in Sources */ = {isa = PBXBuildFile; fileRef = A1ECACF57484B51D17735566ED038104 /* SDImageLoadersManager.m */; }; + 860CB3A5D2E13B946CD2EFB7F749C4CF /* UIActivityIndicatorView+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 29DD9709CE876731037B630B8F1370DA /* UIActivityIndicatorView+AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 864972FB0DF4B464B1B505AA5F788E91 /* SDInternalMacros.m in Sources */ = {isa = PBXBuildFile; fileRef = 06A2AED69705719F9BEBAEDC9D1D18C6 /* SDInternalMacros.m */; }; + 88473AE7C22F952DACB39FA0758D1624 /* SDMemoryCache.h in Headers */ = {isa = PBXBuildFile; fileRef = E97276CEE18BF4611E1C1D42736F6EAB /* SDMemoryCache.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 8872BEB0954C0254A792469F4DBC9891 /* MJRefreshAutoStateFooter.m in Sources */ = {isa = PBXBuildFile; fileRef = CCDB436E5F20F839485E728CEF386187 /* MJRefreshAutoStateFooter.m */; }; + 88A23DF6F5638AC66C28C4102824E8B5 /* NSImage+Compatibility.m in Sources */ = {isa = PBXBuildFile; fileRef = 9C040DD9465E298ACD105143A3265009 /* NSImage+Compatibility.m */; }; + 8AF38EDB1E9BF0D334AEB23C488870B8 /* NSData+ImageContentType.h in Headers */ = {isa = PBXBuildFile; fileRef = DDC08D9E69C76309DA07F96C62824633 /* NSData+ImageContentType.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 8C6C7E25C5A24C936F81823978190E96 /* ViewController+MASAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = 6EB624EDC7B2F6F92D5F6AEF8AAA4356 /* ViewController+MASAdditions.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 8D8AD606ECD8E1F247965CD43956D412 /* UIImage+Transform.h in Headers */ = {isa = PBXBuildFile; fileRef = AF6FBF6EC0693B752A91650764E380C8 /* UIImage+Transform.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 8FF7B6477BFA6E6ABA168E1417291D5F /* MASCompositeConstraint.m in Sources */ = {isa = PBXBuildFile; fileRef = 0F7E589343BFFDCABC0FCDF6E321CDA2 /* MASCompositeConstraint.m */; }; + 906DCE66CD5BD236081D468616199BB7 /* SDWebImageOptionsProcessor.m in Sources */ = {isa = PBXBuildFile; fileRef = ADF1D8C19CC2D66E65B4B1746316FFC5 /* SDWebImageOptionsProcessor.m */; }; + 91AAF555B286FBF53E4F98D092B406BD /* SDWebImageTransitionInternal.h in Headers */ = {isa = PBXBuildFile; fileRef = 755B7205B482C6B79DEAE02978E7FD20 /* SDWebImageTransitionInternal.h */; settings = {ATTRIBUTES = (Private, ); }; }; + 91E8B94F8E02ABF5197DF5AE7D0B3934 /* SDWebImageDownloaderDecryptor.h in Headers */ = {isa = PBXBuildFile; fileRef = 29834704EC1453F0ACBDF5CAA435E7B0 /* SDWebImageDownloaderDecryptor.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 928371B066E1211CE87089668D5BCB4C /* SDDiskCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 6DFD30C63C15966EA8BF3CAD55EB97F8 /* SDDiskCache.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 9345137ED10358B60E37D05FB6165759 /* SDFileAttributeHelper.m in Sources */ = {isa = PBXBuildFile; fileRef = DBFD2ECA52ECDAAA78246FE8B02312A9 /* SDFileAttributeHelper.m */; }; + 9358FC6C6DA728AEE250D8E7DD236946 /* MJProperty.h in Headers */ = {isa = PBXBuildFile; fileRef = 7D8FF130378AA0390E3754AB93673319 /* MJProperty.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 955B87902E039163281C4F47C95DB851 /* MJRefreshBackNormalFooter.m in Sources */ = {isa = PBXBuildFile; fileRef = 14C952AD321D89B78D085CA0FBC817D9 /* MJRefreshBackNormalFooter.m */; }; + 96E97174F4614FFA0649085022CB4AFE /* SDWebImage-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 34F1A2FD98EEB8019052FBD5528585C9 /* SDWebImage-dummy.m */; }; + 97235408E59E16C18B6BDA1D29E1CB26 /* SDWebImageManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 09C03827CE30DECF1B8884688B6651D8 /* SDWebImageManager.m */; }; + 97385A64CA020489951EF769392C6DCF /* UIView+WebCacheOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = 3D5935FEEF657D48BF93BE04A41CF816 /* UIView+WebCacheOperation.m */; }; + 9A7FB1E975A5955C896E6B195C521804 /* MJRefreshBackNormalFooter.h in Headers */ = {isa = PBXBuildFile; fileRef = 087882A7DEA5E7EECA5B73EB89E95C00 /* MJRefreshBackNormalFooter.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 9B3420DEB8A0CCB9E1241A669AEFCA8E /* SDAnimatedImage.h in Headers */ = {isa = PBXBuildFile; fileRef = 2CCDC185ACCEFD6ACB87234F081FC1A1 /* SDAnimatedImage.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 9B9343E8599EE5196BA75E842DCB48B7 /* NSBezierPath+SDRoundedCorners.h in Headers */ = {isa = PBXBuildFile; fileRef = 7A46DCA8F7BDEE6453116CAF6CBBAC40 /* NSBezierPath+SDRoundedCorners.h */; settings = {ATTRIBUTES = (Private, ); }; }; + 9CE425B89294BE2C13E70A86E75B15CF /* SDDiskCache.m in Sources */ = {isa = PBXBuildFile; fileRef = A113F5BE027C0A2BC1CC3F420069F969 /* SDDiskCache.m */; }; + 9D422527A25BAE6A207DEFE11958ABBC /* AFCompatibilityMacros.h in Headers */ = {isa = PBXBuildFile; fileRef = 2B8247E0ADA45F5408F3DE8313900894 /* AFCompatibilityMacros.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 9DF446F8CA5BC4D4098766EC9063012C /* SDWebImageOperation.h in Headers */ = {isa = PBXBuildFile; fileRef = 33152C1C1E9FE19D1E9C8D8BF0C963DA /* SDWebImageOperation.h */; settings = {ATTRIBUTES = (Public, ); }; }; + A078A275FFFA48D620074790DA3CA6CE /* MJRefreshStateHeader.m in Sources */ = {isa = PBXBuildFile; fileRef = D513B9FE4981B810C5EBD34AAD6D0CD7 /* MJRefreshStateHeader.m */; }; + A0E0DC76F51300E7EB1EBA5492DE854D /* UIImageView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = AF94F3E24B633799AB0B2B75B193A4F3 /* UIImageView+AFNetworking.m */; }; + A1560247914C760D9EE5F7A2392CC06C /* UIImage+GIF.h in Headers */ = {isa = PBXBuildFile; fileRef = 429C09B93893D24656048D336CE95D59 /* UIImage+GIF.h */; settings = {ATTRIBUTES = (Public, ); }; }; + A1DC9EFDF50DF0EAF24D9D7C219AD2C1 /* NSObject+MJProperty.h in Headers */ = {isa = PBXBuildFile; fileRef = 0C8185E7D34531047F63FFFBB2C6C9D3 /* NSObject+MJProperty.h */; settings = {ATTRIBUTES = (Public, ); }; }; + A1E44277704AD68E867FD7C955A6632D /* MJRefreshBackGifFooter.m in Sources */ = {isa = PBXBuildFile; fileRef = 32EACA7B3E95EF3C511EEAED34B5C23A /* MJRefreshBackGifFooter.m */; }; + A3148D9EB39C7BFAF4F85E3378F3EF80 /* Pods-CustomKeyboard-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 3CB13D51E717D347023EEB57263E3072 /* Pods-CustomKeyboard-dummy.m */; }; + A3EA39A13714B3103B82F4066A642F53 /* MJExtensionConst.h in Headers */ = {isa = PBXBuildFile; fileRef = 2D68500D4C2F7DB8B114E62F888BDD85 /* MJExtensionConst.h */; settings = {ATTRIBUTES = (Public, ); }; }; + A839428F403C52D8AA3466B65E20C27A /* NSButton+WebCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 11F1BA773620708277D240BE4CD304E4 /* NSButton+WebCache.h */; settings = {ATTRIBUTES = (Public, ); }; }; + A86CC1AFDFDD692DC4EE66F57C0F39E6 /* UIScrollView+MJRefresh.m in Sources */ = {isa = PBXBuildFile; fileRef = 8AF059A8B1C2B3EE76BCDE329D0C926E /* UIScrollView+MJRefresh.m */; }; + A92AB5E65CA85947368E46E6627F1BFB /* UIButton+WebCache.m in Sources */ = {isa = PBXBuildFile; fileRef = 4638EBD469283AF4DC5CBD3CE927D254 /* UIButton+WebCache.m */; }; + A9A49E4A3BE8882F60DF32BAF39DE191 /* SDWebImageManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 02379CD5F0D938EE2DBABC8871CB17E5 /* SDWebImageManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; + AA1EA8F0F0470F1596B1FFA58ABF3375 /* SDWebImageDownloaderOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = 825CA08D9974B4E876CAFA68A0F53F93 /* SDWebImageDownloaderOperation.m */; }; + ABCB80C4813C849FC93D57676820C907 /* SDImageCacheDefine.h in Headers */ = {isa = PBXBuildFile; fileRef = 97F65BC08A412ED6706647722A834532 /* SDImageCacheDefine.h */; settings = {ATTRIBUTES = (Public, ); }; }; + AC14E56ECA7A4980A8E1CA68E800B12C /* SDWebImagePrefetcher.h in Headers */ = {isa = PBXBuildFile; fileRef = 0DC8E0CC70A7B84D1A1E1FAAF5AF5A4D /* SDWebImagePrefetcher.h */; settings = {ATTRIBUTES = (Public, ); }; }; + AC710813CB6A1DAEEE45914402F864D2 /* MJProperty.m in Sources */ = {isa = PBXBuildFile; fileRef = 87A1195922F05E5D23FF9A3C4509A854 /* MJProperty.m */; }; + AE7B02645B8F769CA5F215EE8F7CC5B0 /* View+MASAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = 88799C33D6D0AAE2D395A1496F3A9E5D /* View+MASAdditions.h */; settings = {ATTRIBUTES = (Public, ); }; }; + AF1A6353DEDBE196A10C8897F94DDA8E /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 94F556719E0728E491D5BDF953E9A668 /* PrivacyInfo.xcprivacy */; }; + B030B558BE97E0225652EFB8C8FA431F /* AFAutoPurgingImageCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 246841FAF82F0BA847818A9594B81CCB /* AFAutoPurgingImageCache.h */; settings = {ATTRIBUTES = (Public, ); }; }; + B09F08548ACA8379445F6525011EE219 /* MJRefreshBackStateFooter.m in Sources */ = {isa = PBXBuildFile; fileRef = 71B30FE27ADA94703A3F06804277A5C0 /* MJRefreshBackStateFooter.m */; }; + B2704AFFC5CC053154839DB44924D255 /* SDImageCoderHelper.m in Sources */ = {isa = PBXBuildFile; fileRef = F62E78180455B791A034CFBD4F4CE6A3 /* SDImageCoderHelper.m */; }; + B331CE2D3DEB461E738B886086A365F9 /* SDImageGraphics.h in Headers */ = {isa = PBXBuildFile; fileRef = 34CEE2DA708B82493E132F274E2E9493 /* SDImageGraphics.h */; settings = {ATTRIBUTES = (Public, ); }; }; + B48A975992E58328254C494F133DE467 /* NSObject+MJProperty.m in Sources */ = {isa = PBXBuildFile; fileRef = 4AFCF05D160C4A925AEC624ED1CD826F /* NSObject+MJProperty.m */; }; + B4F231C5CBAB3D4A184699D0066E0E83 /* SDImageAWebPCoder.h in Headers */ = {isa = PBXBuildFile; fileRef = 7315702A1F332F57A8765F720EE5B18F /* SDImageAWebPCoder.h */; settings = {ATTRIBUTES = (Public, ); }; }; + B59E60FBC9665FC1061B88B8E6FD9FAF /* Masonry-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 92D14A3D3FA826806436A8CFCBD915DA /* Masonry-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + B5AF87C11A465F666473F6191D173905 /* UIView+WebCacheOperation.h in Headers */ = {isa = PBXBuildFile; fileRef = AED6E178EFE04C18394DE24CF7E24E01 /* UIView+WebCacheOperation.h */; settings = {ATTRIBUTES = (Public, ); }; }; + B66356D4E7E43B3D15324569AA7EBB05 /* SDWebImageDownloaderOperation.h in Headers */ = {isa = PBXBuildFile; fileRef = A1D6DA8B66269F171ED8918C664075F4 /* SDWebImageDownloaderOperation.h */; settings = {ATTRIBUTES = (Public, ); }; }; + B680C2604BD8BC9644AE7C67BC46B9BB /* MASLayoutConstraint.h in Headers */ = {isa = PBXBuildFile; fileRef = 52AD4C798F619843C6425BB666EE43A0 /* MASLayoutConstraint.h */; settings = {ATTRIBUTES = (Public, ); }; }; + B741DBE2A466E6211F879EF997D9322D /* SDImageCodersManager.h in Headers */ = {isa = PBXBuildFile; fileRef = DBEED872AB83B013F34A14A1823F4820 /* SDImageCodersManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; + B95C63A039D9D08896421291DEBD3AEB /* SDWebImageCacheKeyFilter.m in Sources */ = {isa = PBXBuildFile; fileRef = F7E0DB23007E49794165F74548446C13 /* SDWebImageCacheKeyFilter.m */; }; + BA904ABA8ED36CC4E5EB2B2004CA1F18 /* MASCompositeConstraint.h in Headers */ = {isa = PBXBuildFile; fileRef = 104166B53DA0CBE95AF12518EB609B7A /* MASCompositeConstraint.h */; settings = {ATTRIBUTES = (Public, ); }; }; + BACAA91A92F35CD7E7795232A83F21D1 /* AFNetworkActivityIndicatorManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 859BA7601F83844D2D2ABC395E386663 /* AFNetworkActivityIndicatorManager.m */; }; + BADA31750A2136D073EDA4461DBE1EEA /* UIButton+WebCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 9E2F76F628A20AA296860E039C6A51DE /* UIButton+WebCache.h */; settings = {ATTRIBUTES = (Public, ); }; }; + BC2F9B1D6986FEB23B4FB1288B512538 /* MJRefreshNormalTrailer.h in Headers */ = {isa = PBXBuildFile; fileRef = 73D1ED74B2085AA85B8213943DE4AD83 /* MJRefreshNormalTrailer.h */; settings = {ATTRIBUTES = (Public, ); }; }; + BC5458210A973BC7A29D1F45D458A14B /* AFNetworking-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 14D8DE9600B7E469FA4A83E84C149E08 /* AFNetworking-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + BCDC1E1D46DD124B5726A064D2EE66A3 /* UIImage+MultiFormat.m in Sources */ = {isa = PBXBuildFile; fileRef = F68941BD4F4913D60B00D4A8F049112A /* UIImage+MultiFormat.m */; }; + BCEFDE57BB0E0B36731C8D39FFA1BE2C /* SDWebImageDownloaderRequestModifier.h in Headers */ = {isa = PBXBuildFile; fileRef = 969BDA148FEBCD19E1B7701E7F70E539 /* SDWebImageDownloaderRequestModifier.h */; settings = {ATTRIBUTES = (Public, ); }; }; + BCFA1CA56CA625A754714006E0032750 /* Pods-keyBoard-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = A2D8E1EB42D41EA6B94901E5B68C9011 /* Pods-keyBoard-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + BD30193C1E3D7B1F17B1B1F3F08BE655 /* UICollectionViewLayout+MJRefresh.m in Sources */ = {isa = PBXBuildFile; fileRef = BCC0677B77FA6DFFDE007551F1660B1E /* UICollectionViewLayout+MJRefresh.m */; }; + BDBE494BAC544843982C3CA96A6C41DD /* SDAnimatedImagePlayer.h in Headers */ = {isa = PBXBuildFile; fileRef = 81D5F6E26D64BB94294CEC208FAEEBE2 /* SDAnimatedImagePlayer.h */; settings = {ATTRIBUTES = (Public, ); }; }; + BF0C3D2782FE1425C2F1F8827132A94B /* MJFoundation.h in Headers */ = {isa = PBXBuildFile; fileRef = 0AFFFE7105483F8A94BFD883AD56221D /* MJFoundation.h */; settings = {ATTRIBUTES = (Public, ); }; }; + BF22D137EF6324675FA50080C5D93C00 /* NSArray+MASAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = 93EB15003C1E2452E5C21AD7FF38A39D /* NSArray+MASAdditions.h */; settings = {ATTRIBUTES = (Public, ); }; }; + C0D7926E41A294ACA98D7B033B283919 /* WKWebView+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 9E3334C24AC0A37A21A6D9B9ECA94AB2 /* WKWebView+AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + C1DD8C6A64F948E4C53560C76B995DA4 /* SDAnimatedImageView.h in Headers */ = {isa = PBXBuildFile; fileRef = 8AACAEAAD31005B66599055215ADA658 /* SDAnimatedImageView.h */; settings = {ATTRIBUTES = (Public, ); }; }; + C2068AEACC2D9C7F1FFE41AA25B12A68 /* MASUtilities.h in Headers */ = {isa = PBXBuildFile; fileRef = 3F58F61640AAFD16139A83CC4EA55B1D /* MASUtilities.h */; settings = {ATTRIBUTES = (Public, ); }; }; + C2840BF1950FF7EE2DCD6D55F768A49C /* UIImage+GIF.m in Sources */ = {isa = PBXBuildFile; fileRef = 24F6DCD61BBDE3823CE167416B3799D1 /* UIImage+GIF.m */; }; + C2FE60A10C792613E45031AE6E851ECB /* MASViewConstraint.m in Sources */ = {isa = PBXBuildFile; fileRef = D28BB6B7AF2BC47AA045CB28AE578B56 /* MASViewConstraint.m */; }; + C60DB44F719853DE3B7157960DAF9270 /* MJRefreshComponent.m in Sources */ = {isa = PBXBuildFile; fileRef = FB988F307C9B24539A026F84144A0402 /* MJRefreshComponent.m */; }; + C6A100159974349FEAAC99B82BE0F872 /* SDImageLoader.h in Headers */ = {isa = PBXBuildFile; fileRef = 50DC89AF710F42BFF3D4C048EFAC8BB7 /* SDImageLoader.h */; settings = {ATTRIBUTES = (Public, ); }; }; + C857B8D2D0BAA5A8A764F9E1C4B85807 /* ViewController+MASAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = 33EBB93597383ED9EEA18C0A9BCE3B84 /* ViewController+MASAdditions.m */; }; + C8EC35DFB0945DBE2F2FF9ECFE6D9711 /* NSLayoutConstraint+MASDebugAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = DE966A3AAABAC126A570DC36F74E07AE /* NSLayoutConstraint+MASDebugAdditions.m */; }; + C93E972E75F84674690300123984EC43 /* SDAssociatedObject.m in Sources */ = {isa = PBXBuildFile; fileRef = 0C838D64A8654D1DDA15A6DDC98360A9 /* SDAssociatedObject.m */; }; + C9E19D164C26414115CC969ED9A303C1 /* MASLayoutConstraint.m in Sources */ = {isa = PBXBuildFile; fileRef = 047628989EB45DFAC6DD4B6DDC61C1D7 /* MASLayoutConstraint.m */; }; + CA1E0DCDF679EA2DE2ED0915426E1D04 /* SDWeakProxy.m in Sources */ = {isa = PBXBuildFile; fileRef = 93A3B9C517383784D38DA222632F5FFB /* SDWeakProxy.m */; }; + CFF8D1A5E4C2097EF05E1021FE112886 /* SDWebImageIndicator.m in Sources */ = {isa = PBXBuildFile; fileRef = 0FC44A2AEE9BAA02332A14994FF0E2E0 /* SDWebImageIndicator.m */; }; + D06BB547D59D183FD1DDD84DEBAC9EE8 /* SDWebImageCacheSerializer.m in Sources */ = {isa = PBXBuildFile; fileRef = 6C4CAA32BF7068345545D717BAAF7069 /* SDWebImageCacheSerializer.m */; }; + D2AF9A7FD73B95960FDA4FD06C4BED08 /* NSObject+MJKeyValue.h in Headers */ = {isa = PBXBuildFile; fileRef = D915858ABB2794C80C0D2328483F75C4 /* NSObject+MJKeyValue.h */; settings = {ATTRIBUTES = (Public, ); }; }; + D2CD8848F856EC9942A76610AAE66F0A /* SDImageIOCoder.h in Headers */ = {isa = PBXBuildFile; fileRef = FF09658FCA5560C3552AF5B4B7E7C6ED /* SDImageIOCoder.h */; settings = {ATTRIBUTES = (Public, ); }; }; + D5C046C46961BE465293625D6B870620 /* AFNetworking-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = CC69297E62F679246B8FE5B49D774CF4 /* AFNetworking-dummy.m */; }; + D62A672EEB252581BD972DDA862BE1DD /* SDWebImage-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 70330531B46EEB4398625F2AFC6683E5 /* SDWebImage-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + D662C83ECE8BEDA5FFB52F3575CA3E1A /* SDImageCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 93D1581B25C7E0154AE410EBB56CE516 /* SDImageCache.h */; settings = {ATTRIBUTES = (Public, ); }; }; + D663837F4347AF58660EE6F7FD426ECE /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 18BF12DFF6188AFC43E6F26853B048F9 /* Foundation.framework */; }; + D788BA4B9E8186271BA75CA52B30502C /* View+MASAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = E135DFBB6A830F84DCF4A1D31534EE65 /* View+MASAdditions.m */; }; + D7B3E8948DB04BD8FB6748419DA03EA9 /* SDAnimatedImageView+WebCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 371EEAE238A16CCB71633D3E6EF40F2B /* SDAnimatedImageView+WebCache.h */; settings = {ATTRIBUTES = (Public, ); }; }; + D90607B4E56247B19B14462E487BA86E /* MJRefreshNormalTrailer.m in Sources */ = {isa = PBXBuildFile; fileRef = 8E7292A83C005323B245A7EF2737878F /* MJRefreshNormalTrailer.m */; }; + D90DED0F5638B1C44F4B6C62D600D240 /* MJRefreshFooter.h in Headers */ = {isa = PBXBuildFile; fileRef = 53392BC7B7115E12AC2077F4447BF455 /* MJRefreshFooter.h */; settings = {ATTRIBUTES = (Public, ); }; }; + D90DF1376DF5E2EA644313BCD2E03058 /* MJRefresh.bundle in Resources */ = {isa = PBXBuildFile; fileRef = 5FDFD2C717749B65FE64DACB99DF72A3 /* MJRefresh.bundle */; }; + DBA9500CBBA5FF6FCBBA115AE4D12152 /* NSLayoutConstraint+MASDebugAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = 5679D7FEFDE3E519C17C0EAAA7867122 /* NSLayoutConstraint+MASDebugAdditions.h */; settings = {ATTRIBUTES = (Public, ); }; }; + DBD9152526A180771BF7D7CD209B957E /* AFSecurityPolicy.h in Headers */ = {isa = PBXBuildFile; fileRef = 85AD1C60C75A73E360E4320DD271A77D /* AFSecurityPolicy.h */; settings = {ATTRIBUTES = (Public, ); }; }; + DC87E6C5364DC59641BC8A0676B5EA55 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 18BF12DFF6188AFC43E6F26853B048F9 /* Foundation.framework */; }; + DDA16FB9C21AD941442357DAE6939530 /* UIKit+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 2008561C63F2B5CE8C1C38CF97F13753 /* UIKit+AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + DE5A78F116018E2AC54714238276574D /* UIActivityIndicatorView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = 4C41FE7B076060F0600FEC9D5AFF762A /* UIActivityIndicatorView+AFNetworking.m */; }; + DE98ECCCA7106A4EA575EF34830D41FF /* MJRefresh-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = C71B36DE1531E30C6C8E2592C55C0ED5 /* MJRefresh-dummy.m */; }; + DEA09692CF813A23899CD4949A9B6801 /* SDAnimatedImageRep.h in Headers */ = {isa = PBXBuildFile; fileRef = FB47049112F4F8EEA8F6068CB0393B3F /* SDAnimatedImageRep.h */; settings = {ATTRIBUTES = (Public, ); }; }; + DED9ADFC8CC65243FC54E008A853742C /* MJPropertyKey.m in Sources */ = {isa = PBXBuildFile; fileRef = 12CCB648397BE0600012171A844509DE /* MJPropertyKey.m */; }; + DF2B15402CE105F5A8CE48BBDCFFD5DD /* MASConstraint.m in Sources */ = {isa = PBXBuildFile; fileRef = 7C1791A7C256B13C227BF8DAE4C2EFE9 /* MASConstraint.m */; }; + E0BCF21E9FA59F638C13ECCECC4D9690 /* SDMemoryCache.m in Sources */ = {isa = PBXBuildFile; fileRef = A6CCAA7B0AD1373217438DACF7AB456C /* SDMemoryCache.m */; }; + E1BF615DD0422B06C97542F03C879D41 /* AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = BE440D8DEC29075E20FE83DB3AB2620D /* AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + E1DE69F6BB6235A6EDB6C99A184BEDB4 /* UIScrollView+MJExtension.m in Sources */ = {isa = PBXBuildFile; fileRef = 3B4BB6924504E595528A838685E1B608 /* UIScrollView+MJExtension.m */; }; + E3FC6BEE41652C0500F57E0CB83B347F /* UIButton+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 7AE552655E7E703CCEDD4BE44EFA5662 /* UIButton+AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + E4F1B478580D6D7328BC29607BDE46F6 /* UIImage+ExtendedCacheData.m in Sources */ = {isa = PBXBuildFile; fileRef = 8FC489301C2534B7DD53B90720E80BF3 /* UIImage+ExtendedCacheData.m */; }; + E50613C67DD02AF6EA825DA0B31EFFAD /* SDImageGraphics.m in Sources */ = {isa = PBXBuildFile; fileRef = 830D06A83C1E8E77E539514107F83812 /* SDImageGraphics.m */; }; + E55B3151D86660E28CEABC3CDE6B1508 /* UIButton+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = F0300A3A30BF1560E306C61ACCE11C1A /* UIButton+AFNetworking.m */; }; + E5B057BC87284367918B2DB9CA084B4E /* MJRefreshAutoGifFooter.m in Sources */ = {isa = PBXBuildFile; fileRef = 2514349975FAC97A668A1C6665BD754F /* MJRefreshAutoGifFooter.m */; }; + E76969F9B01139118427505B18F9CD21 /* SDImageHEICCoder.h in Headers */ = {isa = PBXBuildFile; fileRef = 8430A616C01FADC1B0DB9E5D08A03C35 /* SDImageHEICCoder.h */; settings = {ATTRIBUTES = (Public, ); }; }; + E8AB529B9E0B4C23921344F6C4ABFEA4 /* SDImageCoder.m in Sources */ = {isa = PBXBuildFile; fileRef = 01F1EC51FF11D8BE91D0807E9CB714CC /* SDImageCoder.m */; }; + E930A5612DC6D120BE040AD17C6D1BCD /* MASViewAttribute.m in Sources */ = {isa = PBXBuildFile; fileRef = E5AEFA07EBF944C0387D10A7BD7BC85F /* MASViewAttribute.m */; }; + EA82B6D97C9C5D0558047AF552D63203 /* SDWebImageDefine.h in Headers */ = {isa = PBXBuildFile; fileRef = 19C379703ED728112C6AD8D69CB97193 /* SDWebImageDefine.h */; settings = {ATTRIBUTES = (Public, ); }; }; + EABCB60A26B06BF576E50BBD2F89A385 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 18BF12DFF6188AFC43E6F26853B048F9 /* Foundation.framework */; }; + EB3DF628891F7D6AB114718AF760CB2A /* UIImageView+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = AB321552F4E1B0F80966FCA9AF11848F /* UIImageView+AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + EC8E84A8FFADDCA562A8608D141D9027 /* MJRefreshAutoGifFooter.h in Headers */ = {isa = PBXBuildFile; fileRef = 1D9CC7A1A5CD78BA5BDFC0C1D94B2D4D /* MJRefreshAutoGifFooter.h */; settings = {ATTRIBUTES = (Public, ); }; }; + EC9B34262AED632D7EFB49804337648E /* Masonry.h in Headers */ = {isa = PBXBuildFile; fileRef = 23D13EEFDD6A912D7922FE8AE4E23D60 /* Masonry.h */; settings = {ATTRIBUTES = (Public, ); }; }; + ECE64B732F9FA7C402DDEEC58DCB9D98 /* SDImageAPNGCoder.m in Sources */ = {isa = PBXBuildFile; fileRef = BF154B0F2EB8913A8674795FD63311D2 /* SDImageAPNGCoder.m */; }; + ED8991A8AE7C04362C2BED3875DC1656 /* AFURLResponseSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = CEC061A3621F113DA97A66F89E6A844B /* AFURLResponseSerialization.m */; }; + ED8F64FF98CFAE0B12CF60A1B0E6BAF8 /* SDCallbackQueue.h in Headers */ = {isa = PBXBuildFile; fileRef = 678A010D7D73785C1E08D97B5F67AAAA /* SDCallbackQueue.h */; settings = {ATTRIBUTES = (Public, ); }; }; + EE6E8FE636D2C02E3D2FC1E8555B4612 /* MJRefreshNormalHeader.h in Headers */ = {isa = PBXBuildFile; fileRef = 5713367A1E361064DE338AB389631FF5 /* MJRefreshNormalHeader.h */; settings = {ATTRIBUTES = (Public, ); }; }; + EED016DE8173CD38CC01D88CD2628984 /* NSString+MJExtension.h in Headers */ = {isa = PBXBuildFile; fileRef = 0A6C15EE27B77ABD56B0A0807D581260 /* NSString+MJExtension.h */; settings = {ATTRIBUTES = (Public, ); }; }; + EF6A6C725598F572A70C5FCEE328C184 /* SDImageTransformer.h in Headers */ = {isa = PBXBuildFile; fileRef = 2C0A8B13D619D89C3E57F4B83ACBF157 /* SDImageTransformer.h */; settings = {ATTRIBUTES = (Public, ); }; }; + F1D845E22D5B8FC6AFC3C2E41DA1B6DF /* AFNetworkReachabilityManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 523BDC065F0AF63F170A84FAF905FD26 /* AFNetworkReachabilityManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; + F2AD91050B1FE3C8BC78567F1FDE3ED5 /* AFURLResponseSerialization.h in Headers */ = {isa = PBXBuildFile; fileRef = 517973DC2D89829B73698FF20240431A /* AFURLResponseSerialization.h */; settings = {ATTRIBUTES = (Public, ); }; }; + F3263D294D688533EB974E37C61F1E24 /* MJExtensionConst.m in Sources */ = {isa = PBXBuildFile; fileRef = 31F5F018A672BC56D29258EEBC019C32 /* MJExtensionConst.m */; }; + F3AECEF6D3BB919B3E7392942E1BC58B /* MJRefreshBackFooter.m in Sources */ = {isa = PBXBuildFile; fileRef = 19839A21E0B314D9E8C99EBD5D071916 /* MJRefreshBackFooter.m */; }; + F49CB22863CCFEC7817D259F27F91C57 /* SDWebImageIndicator.h in Headers */ = {isa = PBXBuildFile; fileRef = D0B1FCAC31B9EF58F1FD85B83EA55B1C /* SDWebImageIndicator.h */; settings = {ATTRIBUTES = (Public, ); }; }; + F53BE4449AE5896F76325E4DCB6D0B13 /* SDImageCachesManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 0ACA8E457A64FBC07F850B4E390020D4 /* SDImageCachesManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; + F60F90EAF35CFF40DF1C33557965787D /* MJRefreshStateTrailer.h in Headers */ = {isa = PBXBuildFile; fileRef = 036A5C31DE156FE1001CC60EF1E3E122 /* MJRefreshStateTrailer.h */; settings = {ATTRIBUTES = (Public, ); }; }; + F68889CD481716EE5D6B75EBD8FD53A6 /* SDImageCoderHelper.h in Headers */ = {isa = PBXBuildFile; fileRef = 176CBDEEAB52421C3AA5CB3917B54885 /* SDImageCoderHelper.h */; settings = {ATTRIBUTES = (Public, ); }; }; + F6D1C960368EB1E067ABD0BFF707FC56 /* MASConstraintMaker.m in Sources */ = {isa = PBXBuildFile; fileRef = 8ABF0BFFB097FE97D207EBE5498289D3 /* MASConstraintMaker.m */; }; + F7623E7C314AA5010D8D0BD6ED4AAAD4 /* AFImageDownloader.m in Sources */ = {isa = PBXBuildFile; fileRef = 61D0A0EB33F4B0A380D6DE9E8E5D56D7 /* AFImageDownloader.m */; }; + F9789D86D3279D71B398B550F27C3EFF /* AFSecurityPolicy.m in Sources */ = {isa = PBXBuildFile; fileRef = 52AA08F30FFF4D9FF32F48E3AC195A6A /* AFSecurityPolicy.m */; }; + FA3021DED76B9B182CC9195A60EB1209 /* NSBezierPath+SDRoundedCorners.m in Sources */ = {isa = PBXBuildFile; fileRef = B147B49E855B11A35493E26865607BDF /* NSBezierPath+SDRoundedCorners.m */; }; + FCDEC6A53CF5517E1AF5B331FD65F6D9 /* SDImageCacheConfig.m in Sources */ = {isa = PBXBuildFile; fileRef = C5D645FDA53D7713D436C992B2BC3E96 /* SDImageCacheConfig.m */; }; + FCEE5BD645E95FF55468C4AB6D17CFDA /* UIImageView+HighlightedWebCache.m in Sources */ = {isa = PBXBuildFile; fileRef = 56347C360CEDAA8246A01A213DEBBF8B /* UIImageView+HighlightedWebCache.m */; }; + FDACBA49610EA6F39CABB7FE44B137D1 /* AFImageDownloader.h in Headers */ = {isa = PBXBuildFile; fileRef = E8780E8A7822982224C2ACEBBC3B52B8 /* AFImageDownloader.h */; settings = {ATTRIBUTES = (Public, ); }; }; + FE07C069C2E3543002CEB5D751ABA9AC /* AFNetworkReachabilityManager.m in Sources */ = {isa = PBXBuildFile; fileRef = B7BBB3446628A3BC637B9F57A5C49901 /* AFNetworkReachabilityManager.m */; }; + FEA8BA4F82CCBD1D28DCC7EF39FB4096 /* SDImageCacheDefine.m in Sources */ = {isa = PBXBuildFile; fileRef = 9AF4B903EB65570DDDE8731659809CA1 /* SDImageCacheDefine.m */; }; + FEE883575278D5BE8F185437AB5DB3BB /* MJRefreshGifHeader.m in Sources */ = {isa = PBXBuildFile; fileRef = 275A2D66E7913A4B508816E187F4D3C3 /* MJRefreshGifHeader.m */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 23C4ACB33CF11EF7F294BFEFDFEE525F /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = B32AF3F43989CBA171BB1FB3957A4509; + remoteInfo = "MJExtension-MJExtension"; + }; + 74C35E0C9F3979D774EBA89927D5F9BE /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = B26054DF1DEA11585A231AF6D1D80D5E; + remoteInfo = "MJRefresh-MJRefresh.Privacy"; + }; + 7F4A11CEA9C42F01CCC8FD8CF31E0D31 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 55AF53E6C77A10ED4985E04D74A8878E; + remoteInfo = Masonry; + }; + 8C46BC742135C578AA462516574ECF6A /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 94CFBA7D633ECA58DF85C327B035E6A3; + remoteInfo = "SDWebImage-SDWebImage"; + }; + D00922B5D33413CCF1E3D4753D9B5522 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 6868056D761E163D10FDAF8CF1C4D9B8; + remoteInfo = MJRefresh; + }; + D31947E4B8C395A2964CC7C4CA10B4B3 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 4D3BA58D0583DF37575CACAB3DDADC85; + remoteInfo = MJExtension; + }; + ED8283C03EBD084126ED5759CD5B7EF5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 4A68CFD979D413A619DF631BB121D98F; + remoteInfo = Bugly; + }; + F236FEF1E37470AFA015925961D566A3 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 3847153A6E5EEFB86565BA840768F429; + remoteInfo = SDWebImage; + }; + F4298358FEAF506C773B2D34F3DF6B12 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 0130B3724283586C0E9D2A112D4F2AA1; + remoteInfo = AFNetworking; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 00031196DD7FBA552243DCF5CEB19ABD /* SDWebImageDownloader.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWebImageDownloader.h; path = SDWebImage/Core/SDWebImageDownloader.h; sourceTree = ""; }; + 0044E51493E8CC5F8C46E1EC18F97722 /* UIRefreshControl+AFNetworking.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIRefreshControl+AFNetworking.h"; path = "UIKit+AFNetworking/UIRefreshControl+AFNetworking.h"; sourceTree = ""; }; + 0073EB182F9CC003B9721B132AC0082F /* MJRefreshAutoNormalFooter.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJRefreshAutoNormalFooter.h; path = MJRefresh/Custom/Footer/Auto/MJRefreshAutoNormalFooter.h; sourceTree = ""; }; + 008AD8F77F87E2DC5C0DB4CD71AC5858 /* NSButton+WebCache.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSButton+WebCache.m"; path = "SDWebImage/Core/NSButton+WebCache.m"; sourceTree = ""; }; + 018B520CB407C3492F13C3767C15E377 /* UIProgressView+AFNetworking.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIProgressView+AFNetworking.m"; path = "UIKit+AFNetworking/UIProgressView+AFNetworking.m"; sourceTree = ""; }; + 01F1EC51FF11D8BE91D0807E9CB714CC /* SDImageCoder.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDImageCoder.m; path = SDWebImage/Core/SDImageCoder.m; sourceTree = ""; }; + 02379CD5F0D938EE2DBABC8871CB17E5 /* SDWebImageManager.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWebImageManager.h; path = SDWebImage/Core/SDWebImageManager.h; sourceTree = ""; }; + 036A5C31DE156FE1001CC60EF1E3E122 /* MJRefreshStateTrailer.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJRefreshStateTrailer.h; path = MJRefresh/Custom/Trailer/MJRefreshStateTrailer.h; sourceTree = ""; }; + 03DE7669ACCB33ED7598791177D4881A /* UIImage+Metadata.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIImage+Metadata.h"; path = "SDWebImage/Core/UIImage+Metadata.h"; sourceTree = ""; }; + 047628989EB45DFAC6DD4B6DDC61C1D7 /* MASLayoutConstraint.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MASLayoutConstraint.m; path = Masonry/MASLayoutConstraint.m; sourceTree = ""; }; + 06A2AED69705719F9BEBAEDC9D1D18C6 /* SDInternalMacros.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDInternalMacros.m; path = SDWebImage/Private/SDInternalMacros.m; sourceTree = ""; }; + 06B650CAE141ABD90E360415151BC9B9 /* UIView+MJExtension.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIView+MJExtension.m"; path = "MJRefresh/UIView+MJExtension.m"; sourceTree = ""; }; + 06B71FC03BF92D5C7E3E050752C0E06C /* SDWebImageDownloaderRequestModifier.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDWebImageDownloaderRequestModifier.m; path = SDWebImage/Core/SDWebImageDownloaderRequestModifier.m; sourceTree = ""; }; + 078FC3682AC6F2B8020DD6D0F6A1A818 /* SDDisplayLink.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDDisplayLink.h; path = SDWebImage/Private/SDDisplayLink.h; sourceTree = ""; }; + 087882A7DEA5E7EECA5B73EB89E95C00 /* MJRefreshBackNormalFooter.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJRefreshBackNormalFooter.h; path = MJRefresh/Custom/Footer/Back/MJRefreshBackNormalFooter.h; sourceTree = ""; }; + 09C03827CE30DECF1B8884688B6651D8 /* SDWebImageManager.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDWebImageManager.m; path = SDWebImage/Core/SDWebImageManager.m; sourceTree = ""; }; + 0A6C15EE27B77ABD56B0A0807D581260 /* NSString+MJExtension.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSString+MJExtension.h"; path = "MJExtension/NSString+MJExtension.h"; sourceTree = ""; }; + 0ACA8E457A64FBC07F850B4E390020D4 /* SDImageCachesManager.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDImageCachesManager.h; path = SDWebImage/Core/SDImageCachesManager.h; sourceTree = ""; }; + 0AFFFE7105483F8A94BFD883AD56221D /* MJFoundation.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJFoundation.h; path = MJExtension/MJFoundation.h; sourceTree = ""; }; + 0B4AAC15A428CDC2A62AF9CC27BEA609 /* Pods-CustomKeyboard */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = "Pods-CustomKeyboard"; path = Pods_CustomKeyboard.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 0C4AE62ED97252893F28F670D61AFB24 /* Pods-keyBoard-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-keyBoard-Info.plist"; sourceTree = ""; }; + 0C6DD7AD3672258C4407B4269B490F27 /* SDAnimatedImageView+WebCache.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "SDAnimatedImageView+WebCache.m"; path = "SDWebImage/Core/SDAnimatedImageView+WebCache.m"; sourceTree = ""; }; + 0C8185E7D34531047F63FFFBB2C6C9D3 /* NSObject+MJProperty.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSObject+MJProperty.h"; path = "MJExtension/NSObject+MJProperty.h"; sourceTree = ""; }; + 0C838D64A8654D1DDA15A6DDC98360A9 /* SDAssociatedObject.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDAssociatedObject.m; path = SDWebImage/Private/SDAssociatedObject.m; sourceTree = ""; }; + 0CB3E312C9D65596A37072C76944B850 /* SDImageIOAnimatedCoderInternal.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDImageIOAnimatedCoderInternal.h; path = SDWebImage/Private/SDImageIOAnimatedCoderInternal.h; sourceTree = ""; }; + 0D6215D1BCCE125B8DF73E38013CBBDC /* Pods-CustomKeyboard.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-CustomKeyboard.debug.xcconfig"; sourceTree = ""; }; + 0DC8E0CC70A7B84D1A1E1FAAF5AF5A4D /* SDWebImagePrefetcher.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWebImagePrefetcher.h; path = SDWebImage/Core/SDWebImagePrefetcher.h; sourceTree = ""; }; + 0E732C0D026ACBC7DBD039DC3BDC2BCE /* Pods-keyBoard.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-keyBoard.modulemap"; sourceTree = ""; }; + 0F7E589343BFFDCABC0FCDF6E321CDA2 /* MASCompositeConstraint.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MASCompositeConstraint.m; path = Masonry/MASCompositeConstraint.m; sourceTree = ""; }; + 0FC44A2AEE9BAA02332A14994FF0E2E0 /* SDWebImageIndicator.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDWebImageIndicator.m; path = SDWebImage/Core/SDWebImageIndicator.m; sourceTree = ""; }; + 104166B53DA0CBE95AF12518EB609B7A /* MASCompositeConstraint.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MASCompositeConstraint.h; path = Masonry/MASCompositeConstraint.h; sourceTree = ""; }; + 10E420AEEA134E4CDDBAA68DEA103561 /* UIColor+SDHexString.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIColor+SDHexString.m"; path = "SDWebImage/Private/UIColor+SDHexString.m"; sourceTree = ""; }; + 1170792DCF45BF664C43019D3E77D80F /* Masonry.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = Masonry.modulemap; sourceTree = ""; }; + 11F1BA773620708277D240BE4CD304E4 /* NSButton+WebCache.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSButton+WebCache.h"; path = "SDWebImage/Core/NSButton+WebCache.h"; sourceTree = ""; }; + 12C162655386843E5BE2582AC09CA762 /* SDImageFramePool.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDImageFramePool.h; path = SDWebImage/Private/SDImageFramePool.h; sourceTree = ""; }; + 12CCB648397BE0600012171A844509DE /* MJPropertyKey.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MJPropertyKey.m; path = MJExtension/MJPropertyKey.m; sourceTree = ""; }; + 13F0EE17165FE326BF8D348C181A1E71 /* SDImageIOAnimatedCoder.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDImageIOAnimatedCoder.h; path = SDWebImage/Core/SDImageIOAnimatedCoder.h; sourceTree = ""; }; + 14C4334FE2177757C132CBBCD17C11B5 /* UIImage+Transform.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIImage+Transform.m"; path = "SDWebImage/Core/UIImage+Transform.m"; sourceTree = ""; }; + 14C952AD321D89B78D085CA0FBC817D9 /* MJRefreshBackNormalFooter.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MJRefreshBackNormalFooter.m; path = MJRefresh/Custom/Footer/Back/MJRefreshBackNormalFooter.m; sourceTree = ""; }; + 14D8DE9600B7E469FA4A83E84C149E08 /* AFNetworking-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "AFNetworking-umbrella.h"; sourceTree = ""; }; + 176CBDEEAB52421C3AA5CB3917B54885 /* SDImageCoderHelper.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDImageCoderHelper.h; path = SDWebImage/Core/SDImageCoderHelper.h; sourceTree = ""; }; + 18BF12DFF6188AFC43E6F26853B048F9 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS18.0.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; + 197BBC12418F4C1E7719181019D1E9EA /* UIView+WebCacheState.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIView+WebCacheState.m"; path = "SDWebImage/Core/UIView+WebCacheState.m"; sourceTree = ""; }; + 19839A21E0B314D9E8C99EBD5D071916 /* MJRefreshBackFooter.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MJRefreshBackFooter.m; path = MJRefresh/Base/MJRefreshBackFooter.m; sourceTree = ""; }; + 19C379703ED728112C6AD8D69CB97193 /* SDWebImageDefine.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWebImageDefine.h; path = SDWebImage/Core/SDWebImageDefine.h; sourceTree = ""; }; + 19E0C6994863739B688E61DCE0E025C3 /* SDImageCacheConfig.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDImageCacheConfig.h; path = SDWebImage/Core/SDImageCacheConfig.h; sourceTree = ""; }; + 19F5C3BFE7C9E2977EB241266B257ABE /* SDImageAssetManager.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDImageAssetManager.m; path = SDWebImage/Private/SDImageAssetManager.m; sourceTree = ""; }; + 1AFEE2DD6CE0A6302F3235AF172A2B77 /* ResourceBundle-MJExtension-MJExtension-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "ResourceBundle-MJExtension-MJExtension-Info.plist"; sourceTree = ""; }; + 1C27DC7D5FFFA31A8EA1C7B95F3079E1 /* SDWebImageDownloaderDecryptor.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDWebImageDownloaderDecryptor.m; path = SDWebImage/Core/SDWebImageDownloaderDecryptor.m; sourceTree = ""; }; + 1C3E83B47A120437F73D41A878F182D1 /* Masonry-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Masonry-prefix.pch"; sourceTree = ""; }; + 1C60E3EC4F7CE664E3A6586ED2AC0ED5 /* AFHTTPSessionManager.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AFHTTPSessionManager.h; path = AFNetworking/AFHTTPSessionManager.h; sourceTree = ""; }; + 1D774D8146EBC82B4A77204A273761B8 /* Pods-CustomKeyboard.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-CustomKeyboard.release.xcconfig"; sourceTree = ""; }; + 1D9CC7A1A5CD78BA5BDFC0C1D94B2D4D /* MJRefreshAutoGifFooter.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJRefreshAutoGifFooter.h; path = MJRefresh/Custom/Footer/Auto/MJRefreshAutoGifFooter.h; sourceTree = ""; }; + 1DA8FCC29DBFD3824ADEAD9F14A76E86 /* NSArray+MASShorthandAdditions.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSArray+MASShorthandAdditions.h"; path = "Masonry/NSArray+MASShorthandAdditions.h"; sourceTree = ""; }; + 1E8EE46DFF5945CB5FDB220509F5E1A0 /* SDWebImageDownloaderConfig.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDWebImageDownloaderConfig.m; path = SDWebImage/Core/SDWebImageDownloaderConfig.m; sourceTree = ""; }; + 1F0E8534D3C055E4D5D27EBF7422DA74 /* SDWeakProxy.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWeakProxy.h; path = SDWebImage/Private/SDWeakProxy.h; sourceTree = ""; }; + 1F8526067D06A009E96461455DBA1B40 /* MJRefreshBackStateFooter.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJRefreshBackStateFooter.h; path = MJRefresh/Custom/Footer/Back/MJRefreshBackStateFooter.h; sourceTree = ""; }; + 1FFED36A657123030ABB700256D73F15 /* Masonry */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Masonry; path = Masonry.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 2008561C63F2B5CE8C1C38CF97F13753 /* UIKit+AFNetworking.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIKit+AFNetworking.h"; path = "UIKit+AFNetworking/UIKit+AFNetworking.h"; sourceTree = ""; }; + 20B1DAD84F32D1AF296F0D63C5DEE9AB /* SDWebImage.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SDWebImage.debug.xcconfig; sourceTree = ""; }; + 20B21087EF80825B8FC789A191A95BAA /* SDImageHEICCoder.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDImageHEICCoder.m; path = SDWebImage/Core/SDImageHEICCoder.m; sourceTree = ""; }; + 21EE020A32A9ADF76D7C1AF1A9B28D63 /* SDImageIOCoder.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDImageIOCoder.m; path = SDWebImage/Core/SDImageIOCoder.m; sourceTree = ""; }; + 23078E14E88B14332A0B4BE57A2A9488 /* UIImageView+WebCache.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIImageView+WebCache.h"; path = "SDWebImage/Core/UIImageView+WebCache.h"; sourceTree = ""; }; + 2356B7A3F963324EEBA83CB0C527CC22 /* ResourceBundle-SDWebImage-SDWebImage-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "ResourceBundle-SDWebImage-SDWebImage-Info.plist"; sourceTree = ""; }; + 23D13EEFDD6A912D7922FE8AE4E23D60 /* Masonry.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = Masonry.h; path = Masonry/Masonry.h; sourceTree = ""; }; + 23D6F4D8D5B6512D7A50FF1054426C09 /* AFNetworking.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = AFNetworking.release.xcconfig; sourceTree = ""; }; + 246841FAF82F0BA847818A9594B81CCB /* AFAutoPurgingImageCache.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AFAutoPurgingImageCache.h; path = "UIKit+AFNetworking/AFAutoPurgingImageCache.h"; sourceTree = ""; }; + 24B89B49F862DFF8218AA2D11CEDFD3E /* UICollectionViewLayout+MJRefresh.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UICollectionViewLayout+MJRefresh.h"; path = "MJRefresh/UICollectionViewLayout+MJRefresh.h"; sourceTree = ""; }; + 24F6DCD61BBDE3823CE167416B3799D1 /* UIImage+GIF.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIImage+GIF.m"; path = "SDWebImage/Core/UIImage+GIF.m"; sourceTree = ""; }; + 250848691A5C0FC662F372FB71E83AE5 /* MJPropertyKey.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJPropertyKey.h; path = MJExtension/MJPropertyKey.h; sourceTree = ""; }; + 25119C155F0BB240A5DDFB8155627C04 /* SDWebImage.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SDWebImage.release.xcconfig; sourceTree = ""; }; + 2514349975FAC97A668A1C6665BD754F /* MJRefreshAutoGifFooter.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MJRefreshAutoGifFooter.m; path = MJRefresh/Custom/Footer/Auto/MJRefreshAutoGifFooter.m; sourceTree = ""; }; + 25ABF76DAF311B44A4F41DD3F9F04644 /* NSObject+MJClass.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSObject+MJClass.h"; path = "MJExtension/NSObject+MJClass.h"; sourceTree = ""; }; + 266F6A7CA0ABF9B26D746459A14BAEBA /* MASViewConstraint.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MASViewConstraint.h; path = Masonry/MASViewConstraint.h; sourceTree = ""; }; + 275A2D66E7913A4B508816E187F4D3C3 /* MJRefreshGifHeader.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MJRefreshGifHeader.m; path = MJRefresh/Custom/Header/MJRefreshGifHeader.m; sourceTree = ""; }; + 281686F4C9CC2C718B45E1DEB7E63948 /* Pods-CustomKeyboard-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-CustomKeyboard-acknowledgements.markdown"; sourceTree = ""; }; + 29834704EC1453F0ACBDF5CAA435E7B0 /* SDWebImageDownloaderDecryptor.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWebImageDownloaderDecryptor.h; path = SDWebImage/Core/SDWebImageDownloaderDecryptor.h; sourceTree = ""; }; + 29AFC65F883E204F73DDE040C829BC77 /* MJRefreshBackGifFooter.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJRefreshBackGifFooter.h; path = MJRefresh/Custom/Footer/Back/MJRefreshBackGifFooter.h; sourceTree = ""; }; + 29DD9709CE876731037B630B8F1370DA /* UIActivityIndicatorView+AFNetworking.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIActivityIndicatorView+AFNetworking.h"; path = "UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h"; sourceTree = ""; }; + 2B276B0A79173A1D6E83C9B4FB9A4A57 /* MJExtension */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = MJExtension; path = MJExtension.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 2B8247E0ADA45F5408F3DE8313900894 /* AFCompatibilityMacros.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AFCompatibilityMacros.h; path = AFNetworking/AFCompatibilityMacros.h; sourceTree = ""; }; + 2C0A8B13D619D89C3E57F4B83ACBF157 /* SDImageTransformer.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDImageTransformer.h; path = SDWebImage/Core/SDImageTransformer.h; sourceTree = ""; }; + 2CCDC185ACCEFD6ACB87234F081FC1A1 /* SDAnimatedImage.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDAnimatedImage.h; path = SDWebImage/Core/SDAnimatedImage.h; sourceTree = ""; }; + 2CCE60F6B1B48663415E0A4BC9662B33 /* MASViewAttribute.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MASViewAttribute.h; path = Masonry/MASViewAttribute.h; sourceTree = ""; }; + 2D2A2C7E78B1029B85E812A9CC5D4F58 /* MJRefresh.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJRefresh.h; path = MJRefresh/MJRefresh.h; sourceTree = ""; }; + 2D68500D4C2F7DB8B114E62F888BDD85 /* MJExtensionConst.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJExtensionConst.h; path = MJExtension/MJExtensionConst.h; sourceTree = ""; }; + 2E459098B6FF83AA9172F97696B64090 /* NSBundle+MJRefresh.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSBundle+MJRefresh.h"; path = "MJRefresh/NSBundle+MJRefresh.h"; sourceTree = ""; }; + 2EFA72948DE45F4B6CAD9DA5C625D259 /* MJRefreshConfig.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MJRefreshConfig.m; path = MJRefresh/MJRefreshConfig.m; sourceTree = ""; }; + 305FF55ADA3393924EFC2D4B6D38166D /* SDImageCachesManagerOperation.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDImageCachesManagerOperation.m; path = SDWebImage/Private/SDImageCachesManagerOperation.m; sourceTree = ""; }; + 3126B87E909122AFEE37CA26F800E7D9 /* MJRefreshBackFooter.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJRefreshBackFooter.h; path = MJRefresh/Base/MJRefreshBackFooter.h; sourceTree = ""; }; + 31F5F018A672BC56D29258EEBC019C32 /* MJExtensionConst.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MJExtensionConst.m; path = MJExtension/MJExtensionConst.m; sourceTree = ""; }; + 32EACA7B3E95EF3C511EEAED34B5C23A /* MJRefreshBackGifFooter.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MJRefreshBackGifFooter.m; path = MJRefresh/Custom/Footer/Back/MJRefreshBackGifFooter.m; sourceTree = ""; }; + 33152C1C1E9FE19D1E9C8D8BF0C963DA /* SDWebImageOperation.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWebImageOperation.h; path = SDWebImage/Core/SDWebImageOperation.h; sourceTree = ""; }; + 3316E3BF456739AB7A0F0FD1920F5F6B /* MJExtension.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = MJExtension.debug.xcconfig; sourceTree = ""; }; + 33EBB93597383ED9EEA18C0A9BCE3B84 /* ViewController+MASAdditions.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "ViewController+MASAdditions.m"; path = "Masonry/ViewController+MASAdditions.m"; sourceTree = ""; }; + 34B9AAE9B2C02781F4AC71AEDB56A439 /* MJRefreshStateTrailer.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MJRefreshStateTrailer.m; path = MJRefresh/Custom/Trailer/MJRefreshStateTrailer.m; sourceTree = ""; }; + 34CEE2DA708B82493E132F274E2E9493 /* SDImageGraphics.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDImageGraphics.h; path = SDWebImage/Core/SDImageGraphics.h; sourceTree = ""; }; + 34E2AA501576A0C5221012B9066EC56A /* SDAssociatedObject.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDAssociatedObject.h; path = SDWebImage/Private/SDAssociatedObject.h; sourceTree = ""; }; + 34F1A2FD98EEB8019052FBD5528585C9 /* SDWebImage-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "SDWebImage-dummy.m"; sourceTree = ""; }; + 3526591F674CF19FB39EF872089A7F49 /* MJRefreshAutoStateFooter.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJRefreshAutoStateFooter.h; path = MJRefresh/Custom/Footer/Auto/MJRefreshAutoStateFooter.h; sourceTree = ""; }; + 35BFA337F4E1FDE67C773A82CCDFD6DA /* Pods-keyBoard.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-keyBoard.debug.xcconfig"; sourceTree = ""; }; + 35F55EE8682F170A101CA85DD55D1B58 /* UIView+MJExtension.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIView+MJExtension.h"; path = "MJRefresh/UIView+MJExtension.h"; sourceTree = ""; }; + 371EEAE238A16CCB71633D3E6EF40F2B /* SDAnimatedImageView+WebCache.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "SDAnimatedImageView+WebCache.h"; path = "SDWebImage/Core/SDAnimatedImageView+WebCache.h"; sourceTree = ""; }; + 377FB4D51134D774594E6EAF0BB4DFAA /* UIImage+ExtendedCacheData.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIImage+ExtendedCacheData.h"; path = "SDWebImage/Core/UIImage+ExtendedCacheData.h"; sourceTree = ""; }; + 37DCC80FE271D2095A398F8D8F22C7E7 /* NSBundle+MJRefresh.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSBundle+MJRefresh.m"; path = "MJRefresh/NSBundle+MJRefresh.m"; sourceTree = ""; }; + 38A043FDCD06C3C9914C9A22FB6B1D28 /* SDWebImage.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = SDWebImage.modulemap; sourceTree = ""; }; + 396F4E7921EA26CDE8AAEADDD8CFBB49 /* Masonry.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Masonry.release.xcconfig; sourceTree = ""; }; + 3B4BB6924504E595528A838685E1B608 /* UIScrollView+MJExtension.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIScrollView+MJExtension.m"; path = "MJRefresh/UIScrollView+MJExtension.m"; sourceTree = ""; }; + 3CB13D51E717D347023EEB57263E3072 /* Pods-CustomKeyboard-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-CustomKeyboard-dummy.m"; sourceTree = ""; }; + 3D5935FEEF657D48BF93BE04A41CF816 /* UIView+WebCacheOperation.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIView+WebCacheOperation.m"; path = "SDWebImage/Core/UIView+WebCacheOperation.m"; sourceTree = ""; }; + 3F58F61640AAFD16139A83CC4EA55B1D /* MASUtilities.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MASUtilities.h; path = Masonry/MASUtilities.h; sourceTree = ""; }; + 3FBCEF9827DD721BAF021C98F7311D30 /* AFAutoPurgingImageCache.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = AFAutoPurgingImageCache.m; path = "UIKit+AFNetworking/AFAutoPurgingImageCache.m"; sourceTree = ""; }; + 4090C24D16A324EB9D2A6747886BD217 /* SDDeviceHelper.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDDeviceHelper.m; path = SDWebImage/Private/SDDeviceHelper.m; sourceTree = ""; }; + 42134A400043398C196C2BDF73B21075 /* SDAsyncBlockOperation.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDAsyncBlockOperation.h; path = SDWebImage/Private/SDAsyncBlockOperation.h; sourceTree = ""; }; + 429C09B93893D24656048D336CE95D59 /* UIImage+GIF.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIImage+GIF.h"; path = "SDWebImage/Core/UIImage+GIF.h"; sourceTree = ""; }; + 42FE2C6A18379D9944FBBA606FB88133 /* SDImageGIFCoder.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDImageGIFCoder.m; path = SDWebImage/Core/SDImageGIFCoder.m; sourceTree = ""; }; + 43EAAD2AB7E6B407E80E95F643F93D22 /* MJExtension-MJExtension */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; name = "MJExtension-MJExtension"; path = MJExtension.bundle; sourceTree = BUILT_PRODUCTS_DIR; }; + 4638EBD469283AF4DC5CBD3CE927D254 /* UIButton+WebCache.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIButton+WebCache.m"; path = "SDWebImage/Core/UIButton+WebCache.m"; sourceTree = ""; }; + 46F91B0801CEBD1D73003708566CC913 /* UIImage+Metadata.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIImage+Metadata.m"; path = "SDWebImage/Core/UIImage+Metadata.m"; sourceTree = ""; }; + 4797723C6D7C918B816F46FCFB028F6F /* UIImage+MemoryCacheCost.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIImage+MemoryCacheCost.h"; path = "SDWebImage/Core/UIImage+MemoryCacheCost.h"; sourceTree = ""; }; + 4830CF5BA96EF2AA3AC7496D62A49A0D /* MJFoundation.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MJFoundation.m; path = MJExtension/MJFoundation.m; sourceTree = ""; }; + 48E4A519DF8188F67D6109DB1AF82FF9 /* SDDisplayLink.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDDisplayLink.m; path = SDWebImage/Private/SDDisplayLink.m; sourceTree = ""; }; + 4A71363040CF6A8E6D918CEF79A555D5 /* SDWebImageCacheSerializer.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWebImageCacheSerializer.h; path = SDWebImage/Core/SDWebImageCacheSerializer.h; sourceTree = ""; }; + 4AFCF05D160C4A925AEC624ED1CD826F /* NSObject+MJProperty.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSObject+MJProperty.m"; path = "MJExtension/NSObject+MJProperty.m"; sourceTree = ""; }; + 4B22EE0B7D2C1D1066750C4AB84FDA27 /* MJExtension.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = MJExtension.release.xcconfig; sourceTree = ""; }; + 4C41FE7B076060F0600FEC9D5AFF762A /* UIActivityIndicatorView+AFNetworking.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIActivityIndicatorView+AFNetworking.m"; path = "UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m"; sourceTree = ""; }; + 4C64CBB1952BF537420E489E4AF7DED5 /* UIScrollView+MJRefresh.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIScrollView+MJRefresh.h"; path = "MJRefresh/UIScrollView+MJRefresh.h"; sourceTree = ""; }; + 4CD2E3B8C4EBAB8CE1F46D4D7B1B5CAA /* Bugly.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Bugly.debug.xcconfig; sourceTree = ""; }; + 4EF47C40D45E06BA89946B4C9F04A546 /* Masonry.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Masonry.debug.xcconfig; sourceTree = ""; }; + 4F51691B6717B6D9E4E3FE0977CF3163 /* SDWebImageDownloaderResponseModifier.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDWebImageDownloaderResponseModifier.m; path = SDWebImage/Core/SDWebImageDownloaderResponseModifier.m; sourceTree = ""; }; + 50DC89AF710F42BFF3D4C048EFAC8BB7 /* SDImageLoader.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDImageLoader.h; path = SDWebImage/Core/SDImageLoader.h; sourceTree = ""; }; + 517973DC2D89829B73698FF20240431A /* AFURLResponseSerialization.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AFURLResponseSerialization.h; path = AFNetworking/AFURLResponseSerialization.h; sourceTree = ""; }; + 523BDC065F0AF63F170A84FAF905FD26 /* AFNetworkReachabilityManager.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AFNetworkReachabilityManager.h; path = AFNetworking/AFNetworkReachabilityManager.h; sourceTree = ""; }; + 52AA08F30FFF4D9FF32F48E3AC195A6A /* AFSecurityPolicy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = AFSecurityPolicy.m; path = AFNetworking/AFSecurityPolicy.m; sourceTree = ""; }; + 52AD4C798F619843C6425BB666EE43A0 /* MASLayoutConstraint.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MASLayoutConstraint.h; path = Masonry/MASLayoutConstraint.h; sourceTree = ""; }; + 5327DD01C6533D102D66E1636B3827F3 /* Pods-keyBoard-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-keyBoard-acknowledgements.plist"; sourceTree = ""; }; + 53392BC7B7115E12AC2077F4447BF455 /* MJRefreshFooter.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJRefreshFooter.h; path = MJRefresh/Base/MJRefreshFooter.h; sourceTree = ""; }; + 56347C360CEDAA8246A01A213DEBBF8B /* UIImageView+HighlightedWebCache.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIImageView+HighlightedWebCache.m"; path = "SDWebImage/Core/UIImageView+HighlightedWebCache.m"; sourceTree = ""; }; + 5679D7FEFDE3E519C17C0EAAA7867122 /* NSLayoutConstraint+MASDebugAdditions.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSLayoutConstraint+MASDebugAdditions.h"; path = "Masonry/NSLayoutConstraint+MASDebugAdditions.h"; sourceTree = ""; }; + 568638C925360332377ACFB503131A76 /* MJRefreshAutoFooter.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MJRefreshAutoFooter.m; path = MJRefresh/Base/MJRefreshAutoFooter.m; sourceTree = ""; }; + 569FA95248CF0B824C3928196386FFC2 /* MJExtension.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJExtension.h; path = MJExtension/MJExtension.h; sourceTree = ""; }; + 5713367A1E361064DE338AB389631FF5 /* MJRefreshNormalHeader.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJRefreshNormalHeader.h; path = MJRefresh/Custom/Header/MJRefreshNormalHeader.h; sourceTree = ""; }; + 575E3DAA2F5DDC8FBD895B8BEA5FB8C6 /* SDWebImageTransition.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWebImageTransition.h; path = SDWebImage/Core/SDWebImageTransition.h; sourceTree = ""; }; + 5A50D4A4631B759E5D73FDFF78C8BF75 /* NSObject+MJClass.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSObject+MJClass.m"; path = "MJExtension/NSObject+MJClass.m"; sourceTree = ""; }; + 5AC074355067D4E88EB993DD28E44948 /* MASConstraint+Private.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "MASConstraint+Private.h"; path = "Masonry/MASConstraint+Private.h"; sourceTree = ""; }; + 5BA0325112AB8CA7AB613D1A8ED2DB65 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS18.0.sdk/System/Library/Frameworks/UIKit.framework; sourceTree = DEVELOPER_DIR; }; + 5DD19473CA2658646B964B6124A31FB9 /* AFURLRequestSerialization.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AFURLRequestSerialization.h; path = AFNetworking/AFURLRequestSerialization.h; sourceTree = ""; }; + 5E8106411081DD6C7F5FE7804947412C /* Masonry-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Masonry-dummy.m"; sourceTree = ""; }; + 5FD6594A1D1613C90FF5EF2CBD5CE123 /* SDGraphicsImageRenderer.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDGraphicsImageRenderer.h; path = SDWebImage/Core/SDGraphicsImageRenderer.h; sourceTree = ""; }; + 5FDFD2C717749B65FE64DACB99DF72A3 /* MJRefresh.bundle */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "wrapper.plug-in"; name = MJRefresh.bundle; path = MJRefresh/MJRefresh.bundle; sourceTree = ""; }; + 6134DA50CBB0F618C7502B9B4E23963F /* Bugly.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Bugly.release.xcconfig; sourceTree = ""; }; + 61B4061AC178FEE58C9618133524CF08 /* SDmetamacros.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDmetamacros.h; path = SDWebImage/Private/SDmetamacros.h; sourceTree = ""; }; + 61D0A0EB33F4B0A380D6DE9E8E5D56D7 /* AFImageDownloader.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = AFImageDownloader.m; path = "UIKit+AFNetworking/AFImageDownloader.m"; sourceTree = ""; }; + 641251D3092FFCF2B6259BF8676A212E /* Pods-CustomKeyboard-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-CustomKeyboard-Info.plist"; sourceTree = ""; }; + 646B483EDAD1F8B7F96981EB5E185F2E /* SDWebImageError.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWebImageError.h; path = SDWebImage/Core/SDWebImageError.h; sourceTree = ""; }; + 661BCD3C752D21E81C83DA14D3C4502A /* SDGraphicsImageRenderer.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDGraphicsImageRenderer.m; path = SDWebImage/Core/SDGraphicsImageRenderer.m; sourceTree = ""; }; + 678A010D7D73785C1E08D97B5F67AAAA /* SDCallbackQueue.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDCallbackQueue.h; path = SDWebImage/Core/SDCallbackQueue.h; sourceTree = ""; }; + 67DDCFED9CF39A1F995D9E7B12E35A7E /* SDWebImage.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWebImage.h; path = WebImage/SDWebImage.h; sourceTree = ""; }; + 6C4CAA32BF7068345545D717BAAF7069 /* SDWebImageCacheSerializer.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDWebImageCacheSerializer.m; path = SDWebImage/Core/SDWebImageCacheSerializer.m; sourceTree = ""; }; + 6DE36A434A8BD3593CCBD95090373332 /* SDWebImageDefine.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDWebImageDefine.m; path = SDWebImage/Core/SDWebImageDefine.m; sourceTree = ""; }; + 6DFD30C63C15966EA8BF3CAD55EB97F8 /* SDDiskCache.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDDiskCache.h; path = SDWebImage/Core/SDDiskCache.h; sourceTree = ""; }; + 6E7A746456C4F5E2C887572055F6A833 /* SDImageTransformer.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDImageTransformer.m; path = SDWebImage/Core/SDImageTransformer.m; sourceTree = ""; }; + 6EB624EDC7B2F6F92D5F6AEF8AAA4356 /* ViewController+MASAdditions.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "ViewController+MASAdditions.h"; path = "Masonry/ViewController+MASAdditions.h"; sourceTree = ""; }; + 70330531B46EEB4398625F2AFC6683E5 /* SDWebImage-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SDWebImage-umbrella.h"; sourceTree = ""; }; + 71A4B6E144674403F50435C67561B1BB /* WKWebView+AFNetworking.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "WKWebView+AFNetworking.m"; path = "UIKit+AFNetworking/WKWebView+AFNetworking.m"; sourceTree = ""; }; + 71B30FE27ADA94703A3F06804277A5C0 /* MJRefreshBackStateFooter.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MJRefreshBackStateFooter.m; path = MJRefresh/Custom/Footer/Back/MJRefreshBackStateFooter.m; sourceTree = ""; }; + 71C9A7FB9BC0D7C0FA902D0643B08962 /* MASConstraint.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MASConstraint.h; path = Masonry/MASConstraint.h; sourceTree = ""; }; + 724FB5172055CF20AE6E6F4D007D8038 /* MJRefreshHeader.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJRefreshHeader.h; path = MJRefresh/Base/MJRefreshHeader.h; sourceTree = ""; }; + 72789BA685A26A276A98609F54509572 /* MJRefresh-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "MJRefresh-prefix.pch"; sourceTree = ""; }; + 7315702A1F332F57A8765F720EE5B18F /* SDImageAWebPCoder.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDImageAWebPCoder.h; path = SDWebImage/Core/SDImageAWebPCoder.h; sourceTree = ""; }; + 73D1ED74B2085AA85B8213943DE4AD83 /* MJRefreshNormalTrailer.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJRefreshNormalTrailer.h; path = MJRefresh/Custom/Trailer/MJRefreshNormalTrailer.h; sourceTree = ""; }; + 74446596F2A689B17D9187482A194EEC /* AFURLRequestSerialization.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = AFURLRequestSerialization.m; path = AFNetworking/AFURLRequestSerialization.m; sourceTree = ""; }; + 74CC813EBCFDBA413D1E8F2AE302E41A /* MJRefresh.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = MJRefresh.debug.xcconfig; sourceTree = ""; }; + 7506ED7F0118C1C5FE230328CCC6543E /* AFURLSessionManager.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = AFURLSessionManager.m; path = AFNetworking/AFURLSessionManager.m; sourceTree = ""; }; + 755B7205B482C6B79DEAE02978E7FD20 /* SDWebImageTransitionInternal.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWebImageTransitionInternal.h; path = SDWebImage/Private/SDWebImageTransitionInternal.h; sourceTree = ""; }; + 76F97ACAD92849B1F665FD0FF282B3C8 /* SDWebImageOperation.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDWebImageOperation.m; path = SDWebImage/Core/SDWebImageOperation.m; sourceTree = ""; }; + 7842E350E0D12563DE7C0EB363356BF8 /* MJPropertyType.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MJPropertyType.m; path = MJExtension/MJPropertyType.m; sourceTree = ""; }; + 7869EB02C0774141B550180F17DBF9F0 /* SDImageLoader.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDImageLoader.m; path = SDWebImage/Core/SDImageLoader.m; sourceTree = ""; }; + 78744B8D1235EE30BFB429D8C13D63F4 /* AFNetworking.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = AFNetworking.debug.xcconfig; sourceTree = ""; }; + 7980625AB48FABAF33EDB825FF587011 /* SDWebImageCompat.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDWebImageCompat.m; path = SDWebImage/Core/SDWebImageCompat.m; sourceTree = ""; }; + 7A46DCA8F7BDEE6453116CAF6CBBAC40 /* NSBezierPath+SDRoundedCorners.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSBezierPath+SDRoundedCorners.h"; path = "SDWebImage/Private/NSBezierPath+SDRoundedCorners.h"; sourceTree = ""; }; + 7AE552655E7E703CCEDD4BE44EFA5662 /* UIButton+AFNetworking.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIButton+AFNetworking.h"; path = "UIKit+AFNetworking/UIButton+AFNetworking.h"; sourceTree = ""; }; + 7B6867FF0B2276E04032D8E5C44B4EB9 /* SDWebImageCompat.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWebImageCompat.h; path = SDWebImage/Core/SDWebImageCompat.h; sourceTree = ""; }; + 7C1791A7C256B13C227BF8DAE4C2EFE9 /* MASConstraint.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MASConstraint.m; path = Masonry/MASConstraint.m; sourceTree = ""; }; + 7C38C5957F4EAC459AB28A71622C865C /* SDImageAPNGCoder.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDImageAPNGCoder.h; path = SDWebImage/Core/SDImageAPNGCoder.h; sourceTree = ""; }; + 7D3CFDF279C9B9946089A89EFB72A50D /* UIView+WebCache.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIView+WebCache.m"; path = "SDWebImage/Core/UIView+WebCache.m"; sourceTree = ""; }; + 7D4327E5DC3980134C42B829E8798AA4 /* MJRefreshAutoFooter.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJRefreshAutoFooter.h; path = MJRefresh/Base/MJRefreshAutoFooter.h; sourceTree = ""; }; + 7D8FF130378AA0390E3754AB93673319 /* MJProperty.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJProperty.h; path = MJExtension/MJProperty.h; sourceTree = ""; }; + 7E3097CFEFDA621E9FB0E62009FF87FC /* MJRefresh-MJRefresh.Privacy */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; name = "MJRefresh-MJRefresh.Privacy"; path = MJRefresh.Privacy.bundle; sourceTree = BUILT_PRODUCTS_DIR; }; + 7E6DD5C54D7EC67B674C64E88446BAA7 /* MJRefreshAutoNormalFooter.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MJRefreshAutoNormalFooter.m; path = MJRefresh/Custom/Footer/Auto/MJRefreshAutoNormalFooter.m; sourceTree = ""; }; + 7E72BDE0490314836A44AFEE2FD465C2 /* AFNetworking.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = AFNetworking.modulemap; sourceTree = ""; }; + 801C19E603261CA9778C89D068D49697 /* SDWebImage-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SDWebImage-prefix.pch"; sourceTree = ""; }; + 80E9D6278C5650A6AD05F331651F6DEB /* SDImageLoadersManager.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDImageLoadersManager.h; path = SDWebImage/Core/SDImageLoadersManager.h; sourceTree = ""; }; + 81D5F6E26D64BB94294CEC208FAEEBE2 /* SDAnimatedImagePlayer.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDAnimatedImagePlayer.h; path = SDWebImage/Core/SDAnimatedImagePlayer.h; sourceTree = ""; }; + 825CA08D9974B4E876CAFA68A0F53F93 /* SDWebImageDownloaderOperation.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDWebImageDownloaderOperation.m; path = SDWebImage/Core/SDWebImageDownloaderOperation.m; sourceTree = ""; }; + 830D06A83C1E8E77E539514107F83812 /* SDImageGraphics.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDImageGraphics.m; path = SDWebImage/Core/SDImageGraphics.m; sourceTree = ""; }; + 8332CB32D0FA2CE8D910AA5A9BE18D8B /* SDImageCache.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDImageCache.m; path = SDWebImage/Core/SDImageCache.m; sourceTree = ""; }; + 840FE4FBC8DFDB4B1238B06FEA5AF259 /* UIImage+ForceDecode.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIImage+ForceDecode.m"; path = "SDWebImage/Core/UIImage+ForceDecode.m"; sourceTree = ""; }; + 8430A616C01FADC1B0DB9E5D08A03C35 /* SDImageHEICCoder.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDImageHEICCoder.h; path = SDWebImage/Core/SDImageHEICCoder.h; sourceTree = ""; }; + 851329DB564FCDDAD9A52952F487E28D /* UIColor+SDHexString.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIColor+SDHexString.h"; path = "SDWebImage/Private/UIColor+SDHexString.h"; sourceTree = ""; }; + 852C84F2242375BE5446ADE5B9509933 /* ResourceBundle-MJRefresh.Privacy-MJRefresh-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "ResourceBundle-MJRefresh.Privacy-MJRefresh-Info.plist"; sourceTree = ""; }; + 859BA7601F83844D2D2ABC395E386663 /* AFNetworkActivityIndicatorManager.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = AFNetworkActivityIndicatorManager.m; path = "UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m"; sourceTree = ""; }; + 85AD1C60C75A73E360E4320DD271A77D /* AFSecurityPolicy.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AFSecurityPolicy.h; path = AFNetworking/AFSecurityPolicy.h; sourceTree = ""; }; + 87A1195922F05E5D23FF9A3C4509A854 /* MJProperty.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MJProperty.m; path = MJExtension/MJProperty.m; sourceTree = ""; }; + 88799C33D6D0AAE2D395A1496F3A9E5D /* View+MASAdditions.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "View+MASAdditions.h"; path = "Masonry/View+MASAdditions.h"; sourceTree = ""; }; + 897B6BFD5EA50E7440FD4FA3769B3C78 /* UIImage+MultiFormat.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIImage+MultiFormat.h"; path = "SDWebImage/Core/UIImage+MultiFormat.h"; sourceTree = ""; }; + 8A926EA8E3863425810DDC585C464587 /* SDWebImageDownloaderConfig.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWebImageDownloaderConfig.h; path = SDWebImage/Core/SDWebImageDownloaderConfig.h; sourceTree = ""; }; + 8AACAEAAD31005B66599055215ADA658 /* SDAnimatedImageView.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDAnimatedImageView.h; path = SDWebImage/Core/SDAnimatedImageView.h; sourceTree = ""; }; + 8ABF0BFFB097FE97D207EBE5498289D3 /* MASConstraintMaker.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MASConstraintMaker.m; path = Masonry/MASConstraintMaker.m; sourceTree = ""; }; + 8AF059A8B1C2B3EE76BCDE329D0C926E /* UIScrollView+MJRefresh.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIScrollView+MJRefresh.m"; path = "MJRefresh/UIScrollView+MJRefresh.m"; sourceTree = ""; }; + 8BECBF70665658E16C4E9DDD74C7161A /* MJRefreshConst.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MJRefreshConst.m; path = MJRefresh/MJRefreshConst.m; sourceTree = ""; }; + 8C0AB8960CBA6D24923E096B9378691C /* AFHTTPSessionManager.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = AFHTTPSessionManager.m; path = AFNetworking/AFHTTPSessionManager.m; sourceTree = ""; }; + 8E7292A83C005323B245A7EF2737878F /* MJRefreshNormalTrailer.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MJRefreshNormalTrailer.m; path = MJRefresh/Custom/Trailer/MJRefreshNormalTrailer.m; sourceTree = ""; }; + 8FC489301C2534B7DD53B90720E80BF3 /* UIImage+ExtendedCacheData.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIImage+ExtendedCacheData.m"; path = "SDWebImage/Core/UIImage+ExtendedCacheData.m"; sourceTree = ""; }; + 90687AA744E720C17FD8600B60F43FF5 /* NSData+ImageContentType.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSData+ImageContentType.m"; path = "SDWebImage/Core/NSData+ImageContentType.m"; sourceTree = ""; }; + 916FC91BADACF2A6F0FF12F1385FC1D4 /* SDWebImagePrefetcher.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDWebImagePrefetcher.m; path = SDWebImage/Core/SDWebImagePrefetcher.m; sourceTree = ""; }; + 92D14A3D3FA826806436A8CFCBD915DA /* Masonry-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Masonry-umbrella.h"; sourceTree = ""; }; + 93A3B9C517383784D38DA222632F5FFB /* SDWeakProxy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDWeakProxy.m; path = SDWebImage/Private/SDWeakProxy.m; sourceTree = ""; }; + 93D1581B25C7E0154AE410EBB56CE516 /* SDImageCache.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDImageCache.h; path = SDWebImage/Core/SDImageCache.h; sourceTree = ""; }; + 93EB15003C1E2452E5C21AD7FF38A39D /* NSArray+MASAdditions.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSArray+MASAdditions.h"; path = "Masonry/NSArray+MASAdditions.h"; sourceTree = ""; }; + 94F556719E0728E491D5BDF953E9A668 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; includeInIndex = 1; name = PrivacyInfo.xcprivacy; path = MJRefresh/PrivacyInfo.xcprivacy; sourceTree = ""; }; + 950F7A4DEA1A2D31E4A650C9526788F7 /* MJPropertyType.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJPropertyType.h; path = MJExtension/MJPropertyType.h; sourceTree = ""; }; + 969A9A842778EFB5D62826500DFF4E11 /* Pods-keyBoard-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-keyBoard-dummy.m"; sourceTree = ""; }; + 969BDA148FEBCD19E1B7701E7F70E539 /* SDWebImageDownloaderRequestModifier.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWebImageDownloaderRequestModifier.h; path = SDWebImage/Core/SDWebImageDownloaderRequestModifier.h; sourceTree = ""; }; + 970B39752136D5831550118975DC4A91 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; includeInIndex = 1; name = PrivacyInfo.xcprivacy; path = MJExtension/PrivacyInfo.xcprivacy; sourceTree = ""; }; + 9784638759F544FA3CC67A7E0CA9454B /* Bugly.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; path = Bugly.framework; sourceTree = ""; }; + 97F65BC08A412ED6706647722A834532 /* SDImageCacheDefine.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDImageCacheDefine.h; path = SDWebImage/Core/SDImageCacheDefine.h; sourceTree = ""; }; + 9802609AB0266E444A1BD29FA119D9BC /* SDWebImageCacheKeyFilter.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWebImageCacheKeyFilter.h; path = SDWebImage/Core/SDWebImageCacheKeyFilter.h; sourceTree = ""; }; + 982D370CD4E116E0C1917E832541C530 /* UIImageView+HighlightedWebCache.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIImageView+HighlightedWebCache.h"; path = "SDWebImage/Core/UIImageView+HighlightedWebCache.h"; sourceTree = ""; }; + 98E94877A92313B71CB6789264CC6752 /* AFNetworking-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "AFNetworking-Info.plist"; sourceTree = ""; }; + 9954286F43C39384A1EADABA9AAE0B0D /* SDAnimatedImageRep.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDAnimatedImageRep.m; path = SDWebImage/Core/SDAnimatedImageRep.m; sourceTree = ""; }; + 9ADF16A9C4A54B7486F74B1F31DE3947 /* Masonry-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Masonry-Info.plist"; sourceTree = ""; }; + 9AF4B903EB65570DDDE8731659809CA1 /* SDImageCacheDefine.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDImageCacheDefine.m; path = SDWebImage/Core/SDImageCacheDefine.m; sourceTree = ""; }; + 9B7D77CB378449CF4A7041A3EA89C102 /* SDImageFrame.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDImageFrame.m; path = SDWebImage/Core/SDImageFrame.m; sourceTree = ""; }; + 9C040DD9465E298ACD105143A3265009 /* NSImage+Compatibility.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSImage+Compatibility.m"; path = "SDWebImage/Core/NSImage+Compatibility.m"; sourceTree = ""; }; + 9D403D54754F62E7ECBA2668B217E5FD /* NSObject+MJCoding.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSObject+MJCoding.m"; path = "MJExtension/NSObject+MJCoding.m"; sourceTree = ""; }; + 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; indentWidth = 2; lastKnownFileType = text; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; tabWidth = 2; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; + 9DBD448EB576D346FBA1D20A1BD13F1D /* SDImageCachesManagerOperation.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDImageCachesManagerOperation.h; path = SDWebImage/Private/SDImageCachesManagerOperation.h; sourceTree = ""; }; + 9DDD0462C32F55EF5E9CB1056459809F /* Pods-CustomKeyboard-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-CustomKeyboard-umbrella.h"; sourceTree = ""; }; + 9E2F76F628A20AA296860E039C6A51DE /* UIButton+WebCache.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIButton+WebCache.h"; path = "SDWebImage/Core/UIButton+WebCache.h"; sourceTree = ""; }; + 9E3334C24AC0A37A21A6D9B9ECA94AB2 /* WKWebView+AFNetworking.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "WKWebView+AFNetworking.h"; path = "UIKit+AFNetworking/WKWebView+AFNetworking.h"; sourceTree = ""; }; + A11030FED687E26E2A7953D880C8DDD7 /* SDWebImageTransition.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDWebImageTransition.m; path = SDWebImage/Core/SDWebImageTransition.m; sourceTree = ""; }; + A113F5BE027C0A2BC1CC3F420069F969 /* SDDiskCache.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDDiskCache.m; path = SDWebImage/Core/SDDiskCache.m; sourceTree = ""; }; + A1D6DA8B66269F171ED8918C664075F4 /* SDWebImageDownloaderOperation.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWebImageDownloaderOperation.h; path = SDWebImage/Core/SDWebImageDownloaderOperation.h; sourceTree = ""; }; + A1ECACF57484B51D17735566ED038104 /* SDImageLoadersManager.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDImageLoadersManager.m; path = SDWebImage/Core/SDImageLoadersManager.m; sourceTree = ""; }; + A20073D67775A184A6AEF2667BC7628C /* MJRefreshStateHeader.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJRefreshStateHeader.h; path = MJRefresh/Custom/Header/MJRefreshStateHeader.h; sourceTree = ""; }; + A294AA5EAB4FD3CAF8C4A072117591C1 /* SDInternalMacros.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDInternalMacros.h; path = SDWebImage/Private/SDInternalMacros.h; sourceTree = ""; }; + A2D8E1EB42D41EA6B94901E5B68C9011 /* Pods-keyBoard-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-keyBoard-umbrella.h"; sourceTree = ""; }; + A4FA15D44DF6BAC7550EDEED10862AA3 /* AFNetworking */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = AFNetworking; path = AFNetworking.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + A6CCAA7B0AD1373217438DACF7AB456C /* SDMemoryCache.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDMemoryCache.m; path = SDWebImage/Core/SDMemoryCache.m; sourceTree = ""; }; + A6E8FF241173D596A21D4D4B7D86A810 /* Pods-keyBoard.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-keyBoard.release.xcconfig"; sourceTree = ""; }; + A87E9EA0B6E9AB8C1E29A3AE50F278CB /* UIView+WebCache.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIView+WebCache.h"; path = "SDWebImage/Core/UIView+WebCache.h"; sourceTree = ""; }; + A95F96D9DAA700949C3A302C92FD9231 /* AFURLSessionManager.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AFURLSessionManager.h; path = AFNetworking/AFURLSessionManager.h; sourceTree = ""; }; + A9F5CF889820DAD55268C3832155A2E1 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; includeInIndex = 1; name = PrivacyInfo.xcprivacy; path = WebImage/PrivacyInfo.xcprivacy; sourceTree = ""; }; + AB321552F4E1B0F80966FCA9AF11848F /* UIImageView+AFNetworking.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIImageView+AFNetworking.h"; path = "UIKit+AFNetworking/UIImageView+AFNetworking.h"; sourceTree = ""; }; + AB8EC26A51378B3F4C5559E371607480 /* SDImageFrame.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDImageFrame.h; path = SDWebImage/Core/SDImageFrame.h; sourceTree = ""; }; + AC2514CF7A7B043E035CFB079E6FB5A0 /* SDDeviceHelper.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDDeviceHelper.h; path = SDWebImage/Private/SDDeviceHelper.h; sourceTree = ""; }; + ADF1D8C19CC2D66E65B4B1746316FFC5 /* SDWebImageOptionsProcessor.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDWebImageOptionsProcessor.m; path = SDWebImage/Core/SDWebImageOptionsProcessor.m; sourceTree = ""; }; + AECAC2F59ABD4A78D2B73C898E485890 /* MJRefresh-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "MJRefresh-umbrella.h"; sourceTree = ""; }; + AED6E178EFE04C18394DE24CF7E24E01 /* UIView+WebCacheOperation.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIView+WebCacheOperation.h"; path = "SDWebImage/Core/UIView+WebCacheOperation.h"; sourceTree = ""; }; + AF26D1DF8BE4D63027161EEBE6FDE7AE /* SDCallbackQueue.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDCallbackQueue.m; path = SDWebImage/Core/SDCallbackQueue.m; sourceTree = ""; }; + AF6FBF6EC0693B752A91650764E380C8 /* UIImage+Transform.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIImage+Transform.h"; path = "SDWebImage/Core/UIImage+Transform.h"; sourceTree = ""; }; + AF94F3E24B633799AB0B2B75B193A4F3 /* UIImageView+AFNetworking.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIImageView+AFNetworking.m"; path = "UIKit+AFNetworking/UIImageView+AFNetworking.m"; sourceTree = ""; }; + B070DCCCA22D6ECC24DC0BD5CCEF5372 /* UIRefreshControl+AFNetworking.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIRefreshControl+AFNetworking.m"; path = "UIKit+AFNetworking/UIRefreshControl+AFNetworking.m"; sourceTree = ""; }; + B0B214D775196BA7CA8E17E53048A493 /* SDWebImage */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = SDWebImage; path = SDWebImage.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + B147B49E855B11A35493E26865607BDF /* NSBezierPath+SDRoundedCorners.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSBezierPath+SDRoundedCorners.m"; path = "SDWebImage/Private/NSBezierPath+SDRoundedCorners.m"; sourceTree = ""; }; + B1CE88DD0007C23B107D2BD3A6AB545B /* MJRefreshTrailer.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MJRefreshTrailer.m; path = MJRefresh/Base/MJRefreshTrailer.m; sourceTree = ""; }; + B20A669086F5506692603D3336437ABD /* SDAnimatedImagePlayer.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDAnimatedImagePlayer.m; path = SDWebImage/Core/SDAnimatedImagePlayer.m; sourceTree = ""; }; + B3A54C7306CBDB1BC3189CCF492C92DE /* SDImageCoder.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDImageCoder.h; path = SDWebImage/Core/SDImageCoder.h; sourceTree = ""; }; + B509365346F676352BBC6630F5F1FADB /* SDWebImageError.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDWebImageError.m; path = SDWebImage/Core/SDWebImageError.m; sourceTree = ""; }; + B6011963612818816E2CF40CED8B0112 /* MJRefreshTrailer.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJRefreshTrailer.h; path = MJRefresh/Base/MJRefreshTrailer.h; sourceTree = ""; }; + B60142D76441D9D2B7BA4991E7523577 /* SDImageGIFCoder.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDImageGIFCoder.h; path = SDWebImage/Core/SDImageGIFCoder.h; sourceTree = ""; }; + B61705A318B7E4CE5BB4A9A618397777 /* MJExtension-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "MJExtension-prefix.pch"; sourceTree = ""; }; + B7BBB3446628A3BC637B9F57A5C49901 /* AFNetworkReachabilityManager.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = AFNetworkReachabilityManager.m; path = AFNetworking/AFNetworkReachabilityManager.m; sourceTree = ""; }; + B9DF6B027952E0BE3781007ECC6436E7 /* SDWebImageOptionsProcessor.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWebImageOptionsProcessor.h; path = SDWebImage/Core/SDWebImageOptionsProcessor.h; sourceTree = ""; }; + BCC0677B77FA6DFFDE007551F1660B1E /* UICollectionViewLayout+MJRefresh.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UICollectionViewLayout+MJRefresh.m"; path = "MJRefresh/UICollectionViewLayout+MJRefresh.m"; sourceTree = ""; }; + BE440D8DEC29075E20FE83DB3AB2620D /* AFNetworking.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AFNetworking.h; path = AFNetworking/AFNetworking.h; sourceTree = ""; }; + BE6C3AB94897685F9464AA252C4EFB17 /* MJRefreshConst.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJRefreshConst.h; path = MJRefresh/MJRefreshConst.h; sourceTree = ""; }; + BEC2871B1357A63D88FCC0144C7847CD /* MJRefreshConfig.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJRefreshConfig.h; path = MJRefresh/MJRefreshConfig.h; sourceTree = ""; }; + BF154B0F2EB8913A8674795FD63311D2 /* SDImageAPNGCoder.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDImageAPNGCoder.m; path = SDWebImage/Core/SDImageAPNGCoder.m; sourceTree = ""; }; + BF3675A98BB80F2630D08AB3BE31E1B7 /* SDImageFramePool.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDImageFramePool.m; path = SDWebImage/Private/SDImageFramePool.m; sourceTree = ""; }; + C23DF793769699E27A02E0B30615EF6F /* NSObject+MJKeyValue.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSObject+MJKeyValue.m"; path = "MJExtension/NSObject+MJKeyValue.m"; sourceTree = ""; }; + C3EC2E3BBB3895884BB4AA3B74A54476 /* SDImageCodersManager.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDImageCodersManager.m; path = SDWebImage/Core/SDImageCodersManager.m; sourceTree = ""; }; + C55407E10212267DCB2FC49D3260EF48 /* UIScrollView+MJExtension.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIScrollView+MJExtension.h"; path = "MJRefresh/UIScrollView+MJExtension.h"; sourceTree = ""; }; + C5D0E76AC56695893DB1713CA7212B8C /* MJExtension-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "MJExtension-umbrella.h"; sourceTree = ""; }; + C5D645FDA53D7713D436C992B2BC3E96 /* SDImageCacheConfig.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDImageCacheConfig.m; path = SDWebImage/Core/SDImageCacheConfig.m; sourceTree = ""; }; + C6C465F665338FA163A2F6623C933047 /* UIImageView+WebCache.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIImageView+WebCache.m"; path = "SDWebImage/Core/UIImageView+WebCache.m"; sourceTree = ""; }; + C71B36DE1531E30C6C8E2592C55C0ED5 /* MJRefresh-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "MJRefresh-dummy.m"; sourceTree = ""; }; + CAD1D653361EAFCC0E4FFD8252FC1E74 /* Pods-CustomKeyboard.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-CustomKeyboard.modulemap"; sourceTree = ""; }; + CC69297E62F679246B8FE5B49D774CF4 /* AFNetworking-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "AFNetworking-dummy.m"; sourceTree = ""; }; + CCDB436E5F20F839485E728CEF386187 /* MJRefreshAutoStateFooter.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MJRefreshAutoStateFooter.m; path = MJRefresh/Custom/Footer/Auto/MJRefreshAutoStateFooter.m; sourceTree = ""; }; + CEC061A3621F113DA97A66F89E6A844B /* AFURLResponseSerialization.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = AFURLResponseSerialization.m; path = AFNetworking/AFURLResponseSerialization.m; sourceTree = ""; }; + CF1281E58AA1045D4B7F33FC56691C42 /* SDWebImage-SDWebImage */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; name = "SDWebImage-SDWebImage"; path = SDWebImage.bundle; sourceTree = BUILT_PRODUCTS_DIR; }; + D0275B47D80FC8AE3A59DFAEA8C65E1C /* MJRefresh-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "MJRefresh-Info.plist"; sourceTree = ""; }; + D0B1FCAC31B9EF58F1FD85B83EA55B1C /* SDWebImageIndicator.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWebImageIndicator.h; path = SDWebImage/Core/SDWebImageIndicator.h; sourceTree = ""; }; + D13BE3E84BFB9462CF54B22B35F89ADC /* SDFileAttributeHelper.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDFileAttributeHelper.h; path = SDWebImage/Private/SDFileAttributeHelper.h; sourceTree = ""; }; + D28BB6B7AF2BC47AA045CB28AE578B56 /* MASViewConstraint.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MASViewConstraint.m; path = Masonry/MASViewConstraint.m; sourceTree = ""; }; + D513B9FE4981B810C5EBD34AAD6D0CD7 /* MJRefreshStateHeader.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MJRefreshStateHeader.m; path = MJRefresh/Custom/Header/MJRefreshStateHeader.m; sourceTree = ""; }; + D742A7EF918BC67B0884AF366F7415FD /* Pods-CustomKeyboard-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-CustomKeyboard-acknowledgements.plist"; sourceTree = ""; }; + D875CFB5AA1591E80BD3A95A94255894 /* AFNetworkActivityIndicatorManager.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AFNetworkActivityIndicatorManager.h; path = "UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h"; sourceTree = ""; }; + D915858ABB2794C80C0D2328483F75C4 /* NSObject+MJKeyValue.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSObject+MJKeyValue.h"; path = "MJExtension/NSObject+MJKeyValue.h"; sourceTree = ""; }; + D99D7FCB3FD62B8D8BF11087E1D6E47F /* SDWebImageDownloaderResponseModifier.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWebImageDownloaderResponseModifier.h; path = SDWebImage/Core/SDWebImageDownloaderResponseModifier.h; sourceTree = ""; }; + DBEED872AB83B013F34A14A1823F4820 /* SDImageCodersManager.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDImageCodersManager.h; path = SDWebImage/Core/SDImageCodersManager.h; sourceTree = ""; }; + DBFD2ECA52ECDAAA78246FE8B02312A9 /* SDFileAttributeHelper.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDFileAttributeHelper.m; path = SDWebImage/Private/SDFileAttributeHelper.m; sourceTree = ""; }; + DC6CF0A46A4D9FFFBA2057678DF1978B /* SDAnimatedImage.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDAnimatedImage.m; path = SDWebImage/Core/SDAnimatedImage.m; sourceTree = ""; }; + DC6DB03243923516662807D789FF26B1 /* UIView+WebCacheState.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIView+WebCacheState.h"; path = "SDWebImage/Core/UIView+WebCacheState.h"; sourceTree = ""; }; + DCA062FD08AC9694D8D781B3492421C5 /* Pods-keyBoard */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = "Pods-keyBoard"; path = Pods_keyBoard.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + DCFE00F3CC8CED67258D7F7DD13F3156 /* Pods-keyBoard-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-keyBoard-frameworks.sh"; sourceTree = ""; }; + DDAE741F085915AF2475C918F1A17466 /* ImageIO.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = ImageIO.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS18.0.sdk/System/Library/Frameworks/ImageIO.framework; sourceTree = DEVELOPER_DIR; }; + DDC08D9E69C76309DA07F96C62824633 /* NSData+ImageContentType.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSData+ImageContentType.h"; path = "SDWebImage/Core/NSData+ImageContentType.h"; sourceTree = ""; }; + DE966A3AAABAC126A570DC36F74E07AE /* NSLayoutConstraint+MASDebugAdditions.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSLayoutConstraint+MASDebugAdditions.m"; path = "Masonry/NSLayoutConstraint+MASDebugAdditions.m"; sourceTree = ""; }; + DEAC3EFF66D7CCDC2824B18A44FDBB3B /* MJRefresh.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = MJRefresh.modulemap; sourceTree = ""; }; + DF80C56AF1D41887B8622FAC95138810 /* MJRefresh.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = MJRefresh.release.xcconfig; sourceTree = ""; }; + DFD5A14F9DC74814903A901B625C5A94 /* SDImageAWebPCoder.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDImageAWebPCoder.m; path = SDWebImage/Core/SDImageAWebPCoder.m; sourceTree = ""; }; + E0E66128C9FA5581B5257A03454E3761 /* MJExtension.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = MJExtension.modulemap; sourceTree = ""; }; + E135DFBB6A830F84DCF4A1D31534EE65 /* View+MASAdditions.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "View+MASAdditions.m"; path = "Masonry/View+MASAdditions.m"; sourceTree = ""; }; + E200433A892F1843DD9B8C05E3C226BE /* NSObject+MJCoding.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSObject+MJCoding.h"; path = "MJExtension/NSObject+MJCoding.h"; sourceTree = ""; }; + E214C17CF404D45BDF92DD6C18D371FA /* Pods-keyBoard-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-keyBoard-acknowledgements.markdown"; sourceTree = ""; }; + E28F3972E6749440E493F6BCD8198F4F /* MJExtension-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "MJExtension-Info.plist"; sourceTree = ""; }; + E2EAE5E554B07101C740E6CB128A93A0 /* SDImageIOAnimatedCoder.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDImageIOAnimatedCoder.m; path = SDWebImage/Core/SDImageIOAnimatedCoder.m; sourceTree = ""; }; + E310A44D757B0556FA6F2882D1565A8C /* NSString+MJExtension.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSString+MJExtension.m"; path = "MJExtension/NSString+MJExtension.m"; sourceTree = ""; }; + E49D6D248DD1CEE584E6776B9164A1B2 /* MJRefresh */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = MJRefresh; path = MJRefresh.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + E553AE6B35449F8CB4BAA4FFE1DCAFAC /* MJRefreshComponent.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJRefreshComponent.h; path = MJRefresh/Base/MJRefreshComponent.h; sourceTree = ""; }; + E5886305209187E582C024335BD55AE9 /* View+MASShorthandAdditions.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "View+MASShorthandAdditions.h"; path = "Masonry/View+MASShorthandAdditions.h"; sourceTree = ""; }; + E5AEFA07EBF944C0387D10A7BD7BC85F /* MASViewAttribute.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MASViewAttribute.m; path = Masonry/MASViewAttribute.m; sourceTree = ""; }; + E7D9B8C39A19DDF2CE7619D44758B033 /* MJRefreshNormalHeader.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MJRefreshNormalHeader.m; path = MJRefresh/Custom/Header/MJRefreshNormalHeader.m; sourceTree = ""; }; + E8780E8A7822982224C2ACEBBC3B52B8 /* AFImageDownloader.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AFImageDownloader.h; path = "UIKit+AFNetworking/AFImageDownloader.h"; sourceTree = ""; }; + E97276CEE18BF4611E1C1D42736F6EAB /* SDMemoryCache.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDMemoryCache.h; path = SDWebImage/Core/SDMemoryCache.h; sourceTree = ""; }; + EA1E48B813787CAC28E89E7F260BFCD4 /* UIImage+MemoryCacheCost.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIImage+MemoryCacheCost.m"; path = "SDWebImage/Core/UIImage+MemoryCacheCost.m"; sourceTree = ""; }; + EA46C1DE7820870BF842553EA6A951F9 /* UIImage+ForceDecode.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIImage+ForceDecode.h"; path = "SDWebImage/Core/UIImage+ForceDecode.h"; sourceTree = ""; }; + EAE5F401F42AA242D6CAE9E463DE5CD4 /* UIProgressView+AFNetworking.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIProgressView+AFNetworking.h"; path = "UIKit+AFNetworking/UIProgressView+AFNetworking.h"; sourceTree = ""; }; + EAFBBF7E1270693113CDF0C1D9CBB512 /* MJRefreshFooter.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MJRefreshFooter.m; path = MJRefresh/Base/MJRefreshFooter.m; sourceTree = ""; }; + F0300A3A30BF1560E306C61ACCE11C1A /* UIButton+AFNetworking.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIButton+AFNetworking.m"; path = "UIKit+AFNetworking/UIButton+AFNetworking.m"; sourceTree = ""; }; + F0C38163E5AA6D4BEAA1C7E79C82A930 /* SDAnimatedImageView.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDAnimatedImageView.m; path = SDWebImage/Core/SDAnimatedImageView.m; sourceTree = ""; }; + F0CEEBB5DD628DB121172299787A25A9 /* SDImageCachesManager.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDImageCachesManager.m; path = SDWebImage/Core/SDImageCachesManager.m; sourceTree = ""; }; + F104350C0F7D19687DAC6BD75101DA7F /* SDWebImageDownloader.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDWebImageDownloader.m; path = SDWebImage/Core/SDWebImageDownloader.m; sourceTree = ""; }; + F104F9FC5C4BB399EC2C2B96BD7714B8 /* SDWebImage-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "SDWebImage-Info.plist"; sourceTree = ""; }; + F37857D4A0467A12B54C180612695C52 /* AFNetworking-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "AFNetworking-prefix.pch"; sourceTree = ""; }; + F4E10DADB58D42AEAD6CD268CEB583E8 /* MJRefreshGifHeader.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJRefreshGifHeader.h; path = MJRefresh/Custom/Header/MJRefreshGifHeader.h; sourceTree = ""; }; + F62E78180455B791A034CFBD4F4CE6A3 /* SDImageCoderHelper.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDImageCoderHelper.m; path = SDWebImage/Core/SDImageCoderHelper.m; sourceTree = ""; }; + F68941BD4F4913D60B00D4A8F049112A /* UIImage+MultiFormat.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIImage+MultiFormat.m"; path = "SDWebImage/Core/UIImage+MultiFormat.m"; sourceTree = ""; }; + F74EE2D92793519D84E4B72CD6AB0C63 /* MJRefreshHeader.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MJRefreshHeader.m; path = MJRefresh/Base/MJRefreshHeader.m; sourceTree = ""; }; + F76369243ECD96D54BBB9C4A97EB6946 /* NSImage+Compatibility.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSImage+Compatibility.h"; path = "SDWebImage/Core/NSImage+Compatibility.h"; sourceTree = ""; }; + F7A20DE3DDDA450D1997F9A3184CD3C6 /* SDImageAssetManager.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDImageAssetManager.h; path = SDWebImage/Private/SDImageAssetManager.h; sourceTree = ""; }; + F7E0DB23007E49794165F74548446C13 /* SDWebImageCacheKeyFilter.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDWebImageCacheKeyFilter.m; path = SDWebImage/Core/SDWebImageCacheKeyFilter.m; sourceTree = ""; }; + F934ACD20FEDAB980427B3D001DF8312 /* NSArray+MASAdditions.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSArray+MASAdditions.m"; path = "Masonry/NSArray+MASAdditions.m"; sourceTree = ""; }; + F9CEF650A6E8658ECF7704A7EE2E7452 /* MASConstraintMaker.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MASConstraintMaker.h; path = Masonry/MASConstraintMaker.h; sourceTree = ""; }; + FB47049112F4F8EEA8F6068CB0393B3F /* SDAnimatedImageRep.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDAnimatedImageRep.h; path = SDWebImage/Core/SDAnimatedImageRep.h; sourceTree = ""; }; + FB792580573132155A61C027392EF360 /* MJExtension-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "MJExtension-dummy.m"; sourceTree = ""; }; + FB988F307C9B24539A026F84144A0402 /* MJRefreshComponent.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MJRefreshComponent.m; path = MJRefresh/Base/MJRefreshComponent.m; sourceTree = ""; }; + FF09658FCA5560C3552AF5B4B7E7C6ED /* SDImageIOCoder.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDImageIOCoder.h; path = SDWebImage/Core/SDImageIOCoder.h; sourceTree = ""; }; + FF49D60AE2D0E7C2857D88C5353083C3 /* SDAsyncBlockOperation.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDAsyncBlockOperation.m; path = SDWebImage/Private/SDAsyncBlockOperation.m; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 0DDBBB716811E63091A5A45D29A5FEFA /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 08DF3A0323B44ABF3FAAE0F291F8566E /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 11690A588400BBB164423D5F86311C35 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 83A4F2816C1B3F072E1A26A34C3BC4AC /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 12A799DC8ABB2C283ADDDED4421A5EAB /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + D663837F4347AF58660EE6F7FD426ECE /* Foundation.framework in Frameworks */, + 4571A0EA37DC84F39E3830D38A1531AB /* UIKit.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 2195E2C2C2334091D023B7EB98B24603 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 37145BAEB1B97BA7ADD7D6C3E86E99BD /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + EABCB60A26B06BF576E50BBD2F89A385 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 3A5330E1BD187252F408EBB46F1BDC42 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 8414CFEEB64ACA817EB88D2FEADDA3B3 /* Foundation.framework in Frameworks */, + 3777CD89D444CBBB48AE323B303F3FC7 /* ImageIO.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 5F8D0AA57E07244D2E43526654F67443 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 83DE9F788F7FEF1F8FBE5407651F444D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + DC87E6C5364DC59641BC8A0676B5EA55 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 9E666AF8497E0DE090335A642D5B84EC /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 2567FE276DB76481DEFC7DDFE7D775CC /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + E62253CBB3499DA4547AF2A780EC3E2F /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 016CE3C0DE69FA6E7375F8B485359AE7 /* Support Files */ = { + isa = PBXGroup; + children = ( + DEAC3EFF66D7CCDC2824B18A44FDBB3B /* MJRefresh.modulemap */, + C71B36DE1531E30C6C8E2592C55C0ED5 /* MJRefresh-dummy.m */, + D0275B47D80FC8AE3A59DFAEA8C65E1C /* MJRefresh-Info.plist */, + 72789BA685A26A276A98609F54509572 /* MJRefresh-prefix.pch */, + AECAC2F59ABD4A78D2B73C898E485890 /* MJRefresh-umbrella.h */, + 74CC813EBCFDBA413D1E8F2AE302E41A /* MJRefresh.debug.xcconfig */, + DF80C56AF1D41887B8622FAC95138810 /* MJRefresh.release.xcconfig */, + 852C84F2242375BE5446ADE5B9509933 /* ResourceBundle-MJRefresh.Privacy-MJRefresh-Info.plist */, + ); + name = "Support Files"; + path = "../Target Support Files/MJRefresh"; + sourceTree = ""; + }; + 03C5C200A0787E300053CFA8F53CA094 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 2859475DD957B3C624425C23759DE609 /* iOS */, + ); + name = Frameworks; + sourceTree = ""; + }; + 18AF1EE6F6DA0C51E0452AA62EF8B8ED /* Masonry */ = { + isa = PBXGroup; + children = ( + 104166B53DA0CBE95AF12518EB609B7A /* MASCompositeConstraint.h */, + 0F7E589343BFFDCABC0FCDF6E321CDA2 /* MASCompositeConstraint.m */, + 71C9A7FB9BC0D7C0FA902D0643B08962 /* MASConstraint.h */, + 7C1791A7C256B13C227BF8DAE4C2EFE9 /* MASConstraint.m */, + 5AC074355067D4E88EB993DD28E44948 /* MASConstraint+Private.h */, + F9CEF650A6E8658ECF7704A7EE2E7452 /* MASConstraintMaker.h */, + 8ABF0BFFB097FE97D207EBE5498289D3 /* MASConstraintMaker.m */, + 52AD4C798F619843C6425BB666EE43A0 /* MASLayoutConstraint.h */, + 047628989EB45DFAC6DD4B6DDC61C1D7 /* MASLayoutConstraint.m */, + 23D13EEFDD6A912D7922FE8AE4E23D60 /* Masonry.h */, + 3F58F61640AAFD16139A83CC4EA55B1D /* MASUtilities.h */, + 2CCE60F6B1B48663415E0A4BC9662B33 /* MASViewAttribute.h */, + E5AEFA07EBF944C0387D10A7BD7BC85F /* MASViewAttribute.m */, + 266F6A7CA0ABF9B26D746459A14BAEBA /* MASViewConstraint.h */, + D28BB6B7AF2BC47AA045CB28AE578B56 /* MASViewConstraint.m */, + 93EB15003C1E2452E5C21AD7FF38A39D /* NSArray+MASAdditions.h */, + F934ACD20FEDAB980427B3D001DF8312 /* NSArray+MASAdditions.m */, + 1DA8FCC29DBFD3824ADEAD9F14A76E86 /* NSArray+MASShorthandAdditions.h */, + 5679D7FEFDE3E519C17C0EAAA7867122 /* NSLayoutConstraint+MASDebugAdditions.h */, + DE966A3AAABAC126A570DC36F74E07AE /* NSLayoutConstraint+MASDebugAdditions.m */, + 88799C33D6D0AAE2D395A1496F3A9E5D /* View+MASAdditions.h */, + E135DFBB6A830F84DCF4A1D31534EE65 /* View+MASAdditions.m */, + E5886305209187E582C024335BD55AE9 /* View+MASShorthandAdditions.h */, + 6EB624EDC7B2F6F92D5F6AEF8AAA4356 /* ViewController+MASAdditions.h */, + 33EBB93597383ED9EEA18C0A9BCE3B84 /* ViewController+MASAdditions.m */, + B9D225EE05CF747670C5F4383D1D8D95 /* Support Files */, + ); + name = Masonry; + path = Masonry; + sourceTree = ""; + }; + 19D8D3FE289D2B2C36E0B1D672C942C8 /* Reachability */ = { + isa = PBXGroup; + children = ( + 523BDC065F0AF63F170A84FAF905FD26 /* AFNetworkReachabilityManager.h */, + B7BBB3446628A3BC637B9F57A5C49901 /* AFNetworkReachabilityManager.m */, + ); + name = Reachability; + sourceTree = ""; + }; + 1B700D6AB864A19F1C70168CC9BAAEC5 /* Serialization */ = { + isa = PBXGroup; + children = ( + 5DD19473CA2658646B964B6124A31FB9 /* AFURLRequestSerialization.h */, + 74446596F2A689B17D9187482A194EEC /* AFURLRequestSerialization.m */, + 517973DC2D89829B73698FF20240431A /* AFURLResponseSerialization.h */, + CEC061A3621F113DA97A66F89E6A844B /* AFURLResponseSerialization.m */, + ); + name = Serialization; + sourceTree = ""; + }; + 1F956714C6A7CF7B7999AEB4E29D418F /* MJExtension */ = { + isa = PBXGroup; + children = ( + 569FA95248CF0B824C3928196386FFC2 /* MJExtension.h */, + 2D68500D4C2F7DB8B114E62F888BDD85 /* MJExtensionConst.h */, + 31F5F018A672BC56D29258EEBC019C32 /* MJExtensionConst.m */, + 0AFFFE7105483F8A94BFD883AD56221D /* MJFoundation.h */, + 4830CF5BA96EF2AA3AC7496D62A49A0D /* MJFoundation.m */, + 7D8FF130378AA0390E3754AB93673319 /* MJProperty.h */, + 87A1195922F05E5D23FF9A3C4509A854 /* MJProperty.m */, + 250848691A5C0FC662F372FB71E83AE5 /* MJPropertyKey.h */, + 12CCB648397BE0600012171A844509DE /* MJPropertyKey.m */, + 950F7A4DEA1A2D31E4A650C9526788F7 /* MJPropertyType.h */, + 7842E350E0D12563DE7C0EB363356BF8 /* MJPropertyType.m */, + 25ABF76DAF311B44A4F41DD3F9F04644 /* NSObject+MJClass.h */, + 5A50D4A4631B759E5D73FDFF78C8BF75 /* NSObject+MJClass.m */, + E200433A892F1843DD9B8C05E3C226BE /* NSObject+MJCoding.h */, + 9D403D54754F62E7ECBA2668B217E5FD /* NSObject+MJCoding.m */, + D915858ABB2794C80C0D2328483F75C4 /* NSObject+MJKeyValue.h */, + C23DF793769699E27A02E0B30615EF6F /* NSObject+MJKeyValue.m */, + 0C8185E7D34531047F63FFFBB2C6C9D3 /* NSObject+MJProperty.h */, + 4AFCF05D160C4A925AEC624ED1CD826F /* NSObject+MJProperty.m */, + 0A6C15EE27B77ABD56B0A0807D581260 /* NSString+MJExtension.h */, + E310A44D757B0556FA6F2882D1565A8C /* NSString+MJExtension.m */, + C006D91CB7EF7E3CDD3E746411DCC861 /* Resources */, + 93847A1A2F274DFFE13AFE589395B53B /* Support Files */, + ); + name = MJExtension; + path = MJExtension; + sourceTree = ""; + }; + 2859475DD957B3C624425C23759DE609 /* iOS */ = { + isa = PBXGroup; + children = ( + 18BF12DFF6188AFC43E6F26853B048F9 /* Foundation.framework */, + DDAE741F085915AF2475C918F1A17466 /* ImageIO.framework */, + 5BA0325112AB8CA7AB613D1A8ED2DB65 /* UIKit.framework */, + ); + name = iOS; + sourceTree = ""; + }; + 2FC4867627CDCD8FC332BB686C62FDE4 /* Core */ = { + isa = PBXGroup; + children = ( + 7A46DCA8F7BDEE6453116CAF6CBBAC40 /* NSBezierPath+SDRoundedCorners.h */, + B147B49E855B11A35493E26865607BDF /* NSBezierPath+SDRoundedCorners.m */, + 11F1BA773620708277D240BE4CD304E4 /* NSButton+WebCache.h */, + 008AD8F77F87E2DC5C0DB4CD71AC5858 /* NSButton+WebCache.m */, + DDC08D9E69C76309DA07F96C62824633 /* NSData+ImageContentType.h */, + 90687AA744E720C17FD8600B60F43FF5 /* NSData+ImageContentType.m */, + F76369243ECD96D54BBB9C4A97EB6946 /* NSImage+Compatibility.h */, + 9C040DD9465E298ACD105143A3265009 /* NSImage+Compatibility.m */, + 2CCDC185ACCEFD6ACB87234F081FC1A1 /* SDAnimatedImage.h */, + DC6CF0A46A4D9FFFBA2057678DF1978B /* SDAnimatedImage.m */, + 81D5F6E26D64BB94294CEC208FAEEBE2 /* SDAnimatedImagePlayer.h */, + B20A669086F5506692603D3336437ABD /* SDAnimatedImagePlayer.m */, + FB47049112F4F8EEA8F6068CB0393B3F /* SDAnimatedImageRep.h */, + 9954286F43C39384A1EADABA9AAE0B0D /* SDAnimatedImageRep.m */, + 8AACAEAAD31005B66599055215ADA658 /* SDAnimatedImageView.h */, + F0C38163E5AA6D4BEAA1C7E79C82A930 /* SDAnimatedImageView.m */, + 371EEAE238A16CCB71633D3E6EF40F2B /* SDAnimatedImageView+WebCache.h */, + 0C6DD7AD3672258C4407B4269B490F27 /* SDAnimatedImageView+WebCache.m */, + 34E2AA501576A0C5221012B9066EC56A /* SDAssociatedObject.h */, + 0C838D64A8654D1DDA15A6DDC98360A9 /* SDAssociatedObject.m */, + 42134A400043398C196C2BDF73B21075 /* SDAsyncBlockOperation.h */, + FF49D60AE2D0E7C2857D88C5353083C3 /* SDAsyncBlockOperation.m */, + 678A010D7D73785C1E08D97B5F67AAAA /* SDCallbackQueue.h */, + AF26D1DF8BE4D63027161EEBE6FDE7AE /* SDCallbackQueue.m */, + AC2514CF7A7B043E035CFB079E6FB5A0 /* SDDeviceHelper.h */, + 4090C24D16A324EB9D2A6747886BD217 /* SDDeviceHelper.m */, + 6DFD30C63C15966EA8BF3CAD55EB97F8 /* SDDiskCache.h */, + A113F5BE027C0A2BC1CC3F420069F969 /* SDDiskCache.m */, + 078FC3682AC6F2B8020DD6D0F6A1A818 /* SDDisplayLink.h */, + 48E4A519DF8188F67D6109DB1AF82FF9 /* SDDisplayLink.m */, + D13BE3E84BFB9462CF54B22B35F89ADC /* SDFileAttributeHelper.h */, + DBFD2ECA52ECDAAA78246FE8B02312A9 /* SDFileAttributeHelper.m */, + 5FD6594A1D1613C90FF5EF2CBD5CE123 /* SDGraphicsImageRenderer.h */, + 661BCD3C752D21E81C83DA14D3C4502A /* SDGraphicsImageRenderer.m */, + 7C38C5957F4EAC459AB28A71622C865C /* SDImageAPNGCoder.h */, + BF154B0F2EB8913A8674795FD63311D2 /* SDImageAPNGCoder.m */, + F7A20DE3DDDA450D1997F9A3184CD3C6 /* SDImageAssetManager.h */, + 19F5C3BFE7C9E2977EB241266B257ABE /* SDImageAssetManager.m */, + 7315702A1F332F57A8765F720EE5B18F /* SDImageAWebPCoder.h */, + DFD5A14F9DC74814903A901B625C5A94 /* SDImageAWebPCoder.m */, + 93D1581B25C7E0154AE410EBB56CE516 /* SDImageCache.h */, + 8332CB32D0FA2CE8D910AA5A9BE18D8B /* SDImageCache.m */, + 19E0C6994863739B688E61DCE0E025C3 /* SDImageCacheConfig.h */, + C5D645FDA53D7713D436C992B2BC3E96 /* SDImageCacheConfig.m */, + 97F65BC08A412ED6706647722A834532 /* SDImageCacheDefine.h */, + 9AF4B903EB65570DDDE8731659809CA1 /* SDImageCacheDefine.m */, + 0ACA8E457A64FBC07F850B4E390020D4 /* SDImageCachesManager.h */, + F0CEEBB5DD628DB121172299787A25A9 /* SDImageCachesManager.m */, + 9DBD448EB576D346FBA1D20A1BD13F1D /* SDImageCachesManagerOperation.h */, + 305FF55ADA3393924EFC2D4B6D38166D /* SDImageCachesManagerOperation.m */, + B3A54C7306CBDB1BC3189CCF492C92DE /* SDImageCoder.h */, + 01F1EC51FF11D8BE91D0807E9CB714CC /* SDImageCoder.m */, + 176CBDEEAB52421C3AA5CB3917B54885 /* SDImageCoderHelper.h */, + F62E78180455B791A034CFBD4F4CE6A3 /* SDImageCoderHelper.m */, + DBEED872AB83B013F34A14A1823F4820 /* SDImageCodersManager.h */, + C3EC2E3BBB3895884BB4AA3B74A54476 /* SDImageCodersManager.m */, + AB8EC26A51378B3F4C5559E371607480 /* SDImageFrame.h */, + 9B7D77CB378449CF4A7041A3EA89C102 /* SDImageFrame.m */, + 12C162655386843E5BE2582AC09CA762 /* SDImageFramePool.h */, + BF3675A98BB80F2630D08AB3BE31E1B7 /* SDImageFramePool.m */, + B60142D76441D9D2B7BA4991E7523577 /* SDImageGIFCoder.h */, + 42FE2C6A18379D9944FBBA606FB88133 /* SDImageGIFCoder.m */, + 34CEE2DA708B82493E132F274E2E9493 /* SDImageGraphics.h */, + 830D06A83C1E8E77E539514107F83812 /* SDImageGraphics.m */, + 8430A616C01FADC1B0DB9E5D08A03C35 /* SDImageHEICCoder.h */, + 20B21087EF80825B8FC789A191A95BAA /* SDImageHEICCoder.m */, + 13F0EE17165FE326BF8D348C181A1E71 /* SDImageIOAnimatedCoder.h */, + E2EAE5E554B07101C740E6CB128A93A0 /* SDImageIOAnimatedCoder.m */, + 0CB3E312C9D65596A37072C76944B850 /* SDImageIOAnimatedCoderInternal.h */, + FF09658FCA5560C3552AF5B4B7E7C6ED /* SDImageIOCoder.h */, + 21EE020A32A9ADF76D7C1AF1A9B28D63 /* SDImageIOCoder.m */, + 50DC89AF710F42BFF3D4C048EFAC8BB7 /* SDImageLoader.h */, + 7869EB02C0774141B550180F17DBF9F0 /* SDImageLoader.m */, + 80E9D6278C5650A6AD05F331651F6DEB /* SDImageLoadersManager.h */, + A1ECACF57484B51D17735566ED038104 /* SDImageLoadersManager.m */, + 2C0A8B13D619D89C3E57F4B83ACBF157 /* SDImageTransformer.h */, + 6E7A746456C4F5E2C887572055F6A833 /* SDImageTransformer.m */, + A294AA5EAB4FD3CAF8C4A072117591C1 /* SDInternalMacros.h */, + 06A2AED69705719F9BEBAEDC9D1D18C6 /* SDInternalMacros.m */, + E97276CEE18BF4611E1C1D42736F6EAB /* SDMemoryCache.h */, + A6CCAA7B0AD1373217438DACF7AB456C /* SDMemoryCache.m */, + 61B4061AC178FEE58C9618133524CF08 /* SDmetamacros.h */, + 1F0E8534D3C055E4D5D27EBF7422DA74 /* SDWeakProxy.h */, + 93A3B9C517383784D38DA222632F5FFB /* SDWeakProxy.m */, + 67DDCFED9CF39A1F995D9E7B12E35A7E /* SDWebImage.h */, + 9802609AB0266E444A1BD29FA119D9BC /* SDWebImageCacheKeyFilter.h */, + F7E0DB23007E49794165F74548446C13 /* SDWebImageCacheKeyFilter.m */, + 4A71363040CF6A8E6D918CEF79A555D5 /* SDWebImageCacheSerializer.h */, + 6C4CAA32BF7068345545D717BAAF7069 /* SDWebImageCacheSerializer.m */, + 7B6867FF0B2276E04032D8E5C44B4EB9 /* SDWebImageCompat.h */, + 7980625AB48FABAF33EDB825FF587011 /* SDWebImageCompat.m */, + 19C379703ED728112C6AD8D69CB97193 /* SDWebImageDefine.h */, + 6DE36A434A8BD3593CCBD95090373332 /* SDWebImageDefine.m */, + 00031196DD7FBA552243DCF5CEB19ABD /* SDWebImageDownloader.h */, + F104350C0F7D19687DAC6BD75101DA7F /* SDWebImageDownloader.m */, + 8A926EA8E3863425810DDC585C464587 /* SDWebImageDownloaderConfig.h */, + 1E8EE46DFF5945CB5FDB220509F5E1A0 /* SDWebImageDownloaderConfig.m */, + 29834704EC1453F0ACBDF5CAA435E7B0 /* SDWebImageDownloaderDecryptor.h */, + 1C27DC7D5FFFA31A8EA1C7B95F3079E1 /* SDWebImageDownloaderDecryptor.m */, + A1D6DA8B66269F171ED8918C664075F4 /* SDWebImageDownloaderOperation.h */, + 825CA08D9974B4E876CAFA68A0F53F93 /* SDWebImageDownloaderOperation.m */, + 969BDA148FEBCD19E1B7701E7F70E539 /* SDWebImageDownloaderRequestModifier.h */, + 06B71FC03BF92D5C7E3E050752C0E06C /* SDWebImageDownloaderRequestModifier.m */, + D99D7FCB3FD62B8D8BF11087E1D6E47F /* SDWebImageDownloaderResponseModifier.h */, + 4F51691B6717B6D9E4E3FE0977CF3163 /* SDWebImageDownloaderResponseModifier.m */, + 646B483EDAD1F8B7F96981EB5E185F2E /* SDWebImageError.h */, + B509365346F676352BBC6630F5F1FADB /* SDWebImageError.m */, + D0B1FCAC31B9EF58F1FD85B83EA55B1C /* SDWebImageIndicator.h */, + 0FC44A2AEE9BAA02332A14994FF0E2E0 /* SDWebImageIndicator.m */, + 02379CD5F0D938EE2DBABC8871CB17E5 /* SDWebImageManager.h */, + 09C03827CE30DECF1B8884688B6651D8 /* SDWebImageManager.m */, + 33152C1C1E9FE19D1E9C8D8BF0C963DA /* SDWebImageOperation.h */, + 76F97ACAD92849B1F665FD0FF282B3C8 /* SDWebImageOperation.m */, + B9DF6B027952E0BE3781007ECC6436E7 /* SDWebImageOptionsProcessor.h */, + ADF1D8C19CC2D66E65B4B1746316FFC5 /* SDWebImageOptionsProcessor.m */, + 0DC8E0CC70A7B84D1A1E1FAAF5AF5A4D /* SDWebImagePrefetcher.h */, + 916FC91BADACF2A6F0FF12F1385FC1D4 /* SDWebImagePrefetcher.m */, + 575E3DAA2F5DDC8FBD895B8BEA5FB8C6 /* SDWebImageTransition.h */, + A11030FED687E26E2A7953D880C8DDD7 /* SDWebImageTransition.m */, + 755B7205B482C6B79DEAE02978E7FD20 /* SDWebImageTransitionInternal.h */, + 9E2F76F628A20AA296860E039C6A51DE /* UIButton+WebCache.h */, + 4638EBD469283AF4DC5CBD3CE927D254 /* UIButton+WebCache.m */, + 851329DB564FCDDAD9A52952F487E28D /* UIColor+SDHexString.h */, + 10E420AEEA134E4CDDBAA68DEA103561 /* UIColor+SDHexString.m */, + 377FB4D51134D774594E6EAF0BB4DFAA /* UIImage+ExtendedCacheData.h */, + 8FC489301C2534B7DD53B90720E80BF3 /* UIImage+ExtendedCacheData.m */, + EA46C1DE7820870BF842553EA6A951F9 /* UIImage+ForceDecode.h */, + 840FE4FBC8DFDB4B1238B06FEA5AF259 /* UIImage+ForceDecode.m */, + 429C09B93893D24656048D336CE95D59 /* UIImage+GIF.h */, + 24F6DCD61BBDE3823CE167416B3799D1 /* UIImage+GIF.m */, + 4797723C6D7C918B816F46FCFB028F6F /* UIImage+MemoryCacheCost.h */, + EA1E48B813787CAC28E89E7F260BFCD4 /* UIImage+MemoryCacheCost.m */, + 03DE7669ACCB33ED7598791177D4881A /* UIImage+Metadata.h */, + 46F91B0801CEBD1D73003708566CC913 /* UIImage+Metadata.m */, + 897B6BFD5EA50E7440FD4FA3769B3C78 /* UIImage+MultiFormat.h */, + F68941BD4F4913D60B00D4A8F049112A /* UIImage+MultiFormat.m */, + AF6FBF6EC0693B752A91650764E380C8 /* UIImage+Transform.h */, + 14C4334FE2177757C132CBBCD17C11B5 /* UIImage+Transform.m */, + 982D370CD4E116E0C1917E832541C530 /* UIImageView+HighlightedWebCache.h */, + 56347C360CEDAA8246A01A213DEBBF8B /* UIImageView+HighlightedWebCache.m */, + 23078E14E88B14332A0B4BE57A2A9488 /* UIImageView+WebCache.h */, + C6C465F665338FA163A2F6623C933047 /* UIImageView+WebCache.m */, + A87E9EA0B6E9AB8C1E29A3AE50F278CB /* UIView+WebCache.h */, + 7D3CFDF279C9B9946089A89EFB72A50D /* UIView+WebCache.m */, + AED6E178EFE04C18394DE24CF7E24E01 /* UIView+WebCacheOperation.h */, + 3D5935FEEF657D48BF93BE04A41CF816 /* UIView+WebCacheOperation.m */, + DC6DB03243923516662807D789FF26B1 /* UIView+WebCacheState.h */, + 197BBC12418F4C1E7719181019D1E9EA /* UIView+WebCacheState.m */, + 96966FAF94AEBEB4718998C79115AD0F /* Resources */, + ); + name = Core; + sourceTree = ""; + }; + 3128165374A2707E315E77D530A52B15 /* MJRefresh */ = { + isa = PBXGroup; + children = ( + 2D2A2C7E78B1029B85E812A9CC5D4F58 /* MJRefresh.h */, + 7D4327E5DC3980134C42B829E8798AA4 /* MJRefreshAutoFooter.h */, + 568638C925360332377ACFB503131A76 /* MJRefreshAutoFooter.m */, + 1D9CC7A1A5CD78BA5BDFC0C1D94B2D4D /* MJRefreshAutoGifFooter.h */, + 2514349975FAC97A668A1C6665BD754F /* MJRefreshAutoGifFooter.m */, + 0073EB182F9CC003B9721B132AC0082F /* MJRefreshAutoNormalFooter.h */, + 7E6DD5C54D7EC67B674C64E88446BAA7 /* MJRefreshAutoNormalFooter.m */, + 3526591F674CF19FB39EF872089A7F49 /* MJRefreshAutoStateFooter.h */, + CCDB436E5F20F839485E728CEF386187 /* MJRefreshAutoStateFooter.m */, + 3126B87E909122AFEE37CA26F800E7D9 /* MJRefreshBackFooter.h */, + 19839A21E0B314D9E8C99EBD5D071916 /* MJRefreshBackFooter.m */, + 29AFC65F883E204F73DDE040C829BC77 /* MJRefreshBackGifFooter.h */, + 32EACA7B3E95EF3C511EEAED34B5C23A /* MJRefreshBackGifFooter.m */, + 087882A7DEA5E7EECA5B73EB89E95C00 /* MJRefreshBackNormalFooter.h */, + 14C952AD321D89B78D085CA0FBC817D9 /* MJRefreshBackNormalFooter.m */, + 1F8526067D06A009E96461455DBA1B40 /* MJRefreshBackStateFooter.h */, + 71B30FE27ADA94703A3F06804277A5C0 /* MJRefreshBackStateFooter.m */, + E553AE6B35449F8CB4BAA4FFE1DCAFAC /* MJRefreshComponent.h */, + FB988F307C9B24539A026F84144A0402 /* MJRefreshComponent.m */, + BEC2871B1357A63D88FCC0144C7847CD /* MJRefreshConfig.h */, + 2EFA72948DE45F4B6CAD9DA5C625D259 /* MJRefreshConfig.m */, + BE6C3AB94897685F9464AA252C4EFB17 /* MJRefreshConst.h */, + 8BECBF70665658E16C4E9DDD74C7161A /* MJRefreshConst.m */, + 53392BC7B7115E12AC2077F4447BF455 /* MJRefreshFooter.h */, + EAFBBF7E1270693113CDF0C1D9CBB512 /* MJRefreshFooter.m */, + F4E10DADB58D42AEAD6CD268CEB583E8 /* MJRefreshGifHeader.h */, + 275A2D66E7913A4B508816E187F4D3C3 /* MJRefreshGifHeader.m */, + 724FB5172055CF20AE6E6F4D007D8038 /* MJRefreshHeader.h */, + F74EE2D92793519D84E4B72CD6AB0C63 /* MJRefreshHeader.m */, + 5713367A1E361064DE338AB389631FF5 /* MJRefreshNormalHeader.h */, + E7D9B8C39A19DDF2CE7619D44758B033 /* MJRefreshNormalHeader.m */, + 73D1ED74B2085AA85B8213943DE4AD83 /* MJRefreshNormalTrailer.h */, + 8E7292A83C005323B245A7EF2737878F /* MJRefreshNormalTrailer.m */, + A20073D67775A184A6AEF2667BC7628C /* MJRefreshStateHeader.h */, + D513B9FE4981B810C5EBD34AAD6D0CD7 /* MJRefreshStateHeader.m */, + 036A5C31DE156FE1001CC60EF1E3E122 /* MJRefreshStateTrailer.h */, + 34B9AAE9B2C02781F4AC71AEDB56A439 /* MJRefreshStateTrailer.m */, + B6011963612818816E2CF40CED8B0112 /* MJRefreshTrailer.h */, + B1CE88DD0007C23B107D2BD3A6AB545B /* MJRefreshTrailer.m */, + 2E459098B6FF83AA9172F97696B64090 /* NSBundle+MJRefresh.h */, + 37DCC80FE271D2095A398F8D8F22C7E7 /* NSBundle+MJRefresh.m */, + 24B89B49F862DFF8218AA2D11CEDFD3E /* UICollectionViewLayout+MJRefresh.h */, + BCC0677B77FA6DFFDE007551F1660B1E /* UICollectionViewLayout+MJRefresh.m */, + C55407E10212267DCB2FC49D3260EF48 /* UIScrollView+MJExtension.h */, + 3B4BB6924504E595528A838685E1B608 /* UIScrollView+MJExtension.m */, + 4C64CBB1952BF537420E489E4AF7DED5 /* UIScrollView+MJRefresh.h */, + 8AF059A8B1C2B3EE76BCDE329D0C926E /* UIScrollView+MJRefresh.m */, + 35F55EE8682F170A101CA85DD55D1B58 /* UIView+MJExtension.h */, + 06B650CAE141ABD90E360415151BC9B9 /* UIView+MJExtension.m */, + 33D98C7E27F657F30141071B1B662940 /* Resources */, + 016CE3C0DE69FA6E7375F8B485359AE7 /* Support Files */, + ); + name = MJRefresh; + path = MJRefresh; + sourceTree = ""; + }; + 33D98C7E27F657F30141071B1B662940 /* Resources */ = { + isa = PBXGroup; + children = ( + 5FDFD2C717749B65FE64DACB99DF72A3 /* MJRefresh.bundle */, + 94F556719E0728E491D5BDF953E9A668 /* PrivacyInfo.xcprivacy */, + ); + name = Resources; + sourceTree = ""; + }; + 347AB39793E933B72AA519D8A60C8AFD /* NSURLSession */ = { + isa = PBXGroup; + children = ( + 2B8247E0ADA45F5408F3DE8313900894 /* AFCompatibilityMacros.h */, + 1C60E3EC4F7CE664E3A6586ED2AC0ED5 /* AFHTTPSessionManager.h */, + 8C0AB8960CBA6D24923E096B9378691C /* AFHTTPSessionManager.m */, + A95F96D9DAA700949C3A302C92FD9231 /* AFURLSessionManager.h */, + 7506ED7F0118C1C5FE230328CCC6543E /* AFURLSessionManager.m */, + ); + name = NSURLSession; + sourceTree = ""; + }; + 4098ED899C8DF8E013F9F260ECFAA236 /* Pods-keyBoard */ = { + isa = PBXGroup; + children = ( + 0E732C0D026ACBC7DBD039DC3BDC2BCE /* Pods-keyBoard.modulemap */, + E214C17CF404D45BDF92DD6C18D371FA /* Pods-keyBoard-acknowledgements.markdown */, + 5327DD01C6533D102D66E1636B3827F3 /* Pods-keyBoard-acknowledgements.plist */, + 969A9A842778EFB5D62826500DFF4E11 /* Pods-keyBoard-dummy.m */, + DCFE00F3CC8CED67258D7F7DD13F3156 /* Pods-keyBoard-frameworks.sh */, + 0C4AE62ED97252893F28F670D61AFB24 /* Pods-keyBoard-Info.plist */, + A2D8E1EB42D41EA6B94901E5B68C9011 /* Pods-keyBoard-umbrella.h */, + 35BFA337F4E1FDE67C773A82CCDFD6DA /* Pods-keyBoard.debug.xcconfig */, + A6E8FF241173D596A21D4D4B7D86A810 /* Pods-keyBoard.release.xcconfig */, + ); + name = "Pods-keyBoard"; + path = "Target Support Files/Pods-keyBoard"; + sourceTree = ""; + }; + 47B776543D6613BCB6FB72308F863018 /* Pods-CustomKeyboard */ = { + isa = PBXGroup; + children = ( + CAD1D653361EAFCC0E4FFD8252FC1E74 /* Pods-CustomKeyboard.modulemap */, + 281686F4C9CC2C718B45E1DEB7E63948 /* Pods-CustomKeyboard-acknowledgements.markdown */, + D742A7EF918BC67B0884AF366F7415FD /* Pods-CustomKeyboard-acknowledgements.plist */, + 3CB13D51E717D347023EEB57263E3072 /* Pods-CustomKeyboard-dummy.m */, + 641251D3092FFCF2B6259BF8676A212E /* Pods-CustomKeyboard-Info.plist */, + 9DDD0462C32F55EF5E9CB1056459809F /* Pods-CustomKeyboard-umbrella.h */, + 0D6215D1BCCE125B8DF73E38013CBBDC /* Pods-CustomKeyboard.debug.xcconfig */, + 1D774D8146EBC82B4A77204A273761B8 /* Pods-CustomKeyboard.release.xcconfig */, + ); + name = "Pods-CustomKeyboard"; + path = "Target Support Files/Pods-CustomKeyboard"; + sourceTree = ""; + }; + 502B3DC21E7D9121A0C4B98D3286C994 /* Bugly */ = { + isa = PBXGroup; + children = ( + 88D3451B2C2D8161F934A9C946E320E9 /* Frameworks */, + E09502DD4B1D7ABBB4407C6ED07C0666 /* Support Files */, + ); + name = Bugly; + path = Bugly; + sourceTree = ""; + }; + 6365FA12681868274FAA98E6F51817F6 /* Support Files */ = { + isa = PBXGroup; + children = ( + 7E72BDE0490314836A44AFEE2FD465C2 /* AFNetworking.modulemap */, + CC69297E62F679246B8FE5B49D774CF4 /* AFNetworking-dummy.m */, + 98E94877A92313B71CB6789264CC6752 /* AFNetworking-Info.plist */, + F37857D4A0467A12B54C180612695C52 /* AFNetworking-prefix.pch */, + 14D8DE9600B7E469FA4A83E84C149E08 /* AFNetworking-umbrella.h */, + 78744B8D1235EE30BFB429D8C13D63F4 /* AFNetworking.debug.xcconfig */, + 23D6F4D8D5B6512D7A50FF1054426C09 /* AFNetworking.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/AFNetworking"; + sourceTree = ""; + }; + 72657A79EE3B081E5F0D7C1166237E68 /* AFNetworking */ = { + isa = PBXGroup; + children = ( + BE440D8DEC29075E20FE83DB3AB2620D /* AFNetworking.h */, + 347AB39793E933B72AA519D8A60C8AFD /* NSURLSession */, + 19D8D3FE289D2B2C36E0B1D672C942C8 /* Reachability */, + D1B9DC187765592AAEEACCE698694E27 /* Security */, + 1B700D6AB864A19F1C70168CC9BAAEC5 /* Serialization */, + 6365FA12681868274FAA98E6F51817F6 /* Support Files */, + A63CD7E158D91CCE464486A00A29695D /* UIKit */, + ); + name = AFNetworking; + path = AFNetworking; + sourceTree = ""; + }; + 72EAC702A61A19B6EC92D70B6CA9D4E8 /* Support Files */ = { + isa = PBXGroup; + children = ( + 2356B7A3F963324EEBA83CB0C527CC22 /* ResourceBundle-SDWebImage-SDWebImage-Info.plist */, + 38A043FDCD06C3C9914C9A22FB6B1D28 /* SDWebImage.modulemap */, + 34F1A2FD98EEB8019052FBD5528585C9 /* SDWebImage-dummy.m */, + F104F9FC5C4BB399EC2C2B96BD7714B8 /* SDWebImage-Info.plist */, + 801C19E603261CA9778C89D068D49697 /* SDWebImage-prefix.pch */, + 70330531B46EEB4398625F2AFC6683E5 /* SDWebImage-umbrella.h */, + 20B1DAD84F32D1AF296F0D63C5DEE9AB /* SDWebImage.debug.xcconfig */, + 25119C155F0BB240A5DDFB8155627C04 /* SDWebImage.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/SDWebImage"; + sourceTree = ""; + }; + 88D3451B2C2D8161F934A9C946E320E9 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 9784638759F544FA3CC67A7E0CA9454B /* Bugly.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + 93847A1A2F274DFFE13AFE589395B53B /* Support Files */ = { + isa = PBXGroup; + children = ( + E0E66128C9FA5581B5257A03454E3761 /* MJExtension.modulemap */, + FB792580573132155A61C027392EF360 /* MJExtension-dummy.m */, + E28F3972E6749440E493F6BCD8198F4F /* MJExtension-Info.plist */, + B61705A318B7E4CE5BB4A9A618397777 /* MJExtension-prefix.pch */, + C5D0E76AC56695893DB1713CA7212B8C /* MJExtension-umbrella.h */, + 3316E3BF456739AB7A0F0FD1920F5F6B /* MJExtension.debug.xcconfig */, + 4B22EE0B7D2C1D1066750C4AB84FDA27 /* MJExtension.release.xcconfig */, + 1AFEE2DD6CE0A6302F3235AF172A2B77 /* ResourceBundle-MJExtension-MJExtension-Info.plist */, + ); + name = "Support Files"; + path = "../Target Support Files/MJExtension"; + sourceTree = ""; + }; + 96966FAF94AEBEB4718998C79115AD0F /* Resources */ = { + isa = PBXGroup; + children = ( + A9F5CF889820DAD55268C3832155A2E1 /* PrivacyInfo.xcprivacy */, + ); + name = Resources; + sourceTree = ""; + }; + A63CD7E158D91CCE464486A00A29695D /* UIKit */ = { + isa = PBXGroup; + children = ( + 246841FAF82F0BA847818A9594B81CCB /* AFAutoPurgingImageCache.h */, + 3FBCEF9827DD721BAF021C98F7311D30 /* AFAutoPurgingImageCache.m */, + E8780E8A7822982224C2ACEBBC3B52B8 /* AFImageDownloader.h */, + 61D0A0EB33F4B0A380D6DE9E8E5D56D7 /* AFImageDownloader.m */, + D875CFB5AA1591E80BD3A95A94255894 /* AFNetworkActivityIndicatorManager.h */, + 859BA7601F83844D2D2ABC395E386663 /* AFNetworkActivityIndicatorManager.m */, + 29DD9709CE876731037B630B8F1370DA /* UIActivityIndicatorView+AFNetworking.h */, + 4C41FE7B076060F0600FEC9D5AFF762A /* UIActivityIndicatorView+AFNetworking.m */, + 7AE552655E7E703CCEDD4BE44EFA5662 /* UIButton+AFNetworking.h */, + F0300A3A30BF1560E306C61ACCE11C1A /* UIButton+AFNetworking.m */, + AB321552F4E1B0F80966FCA9AF11848F /* UIImageView+AFNetworking.h */, + AF94F3E24B633799AB0B2B75B193A4F3 /* UIImageView+AFNetworking.m */, + 2008561C63F2B5CE8C1C38CF97F13753 /* UIKit+AFNetworking.h */, + EAE5F401F42AA242D6CAE9E463DE5CD4 /* UIProgressView+AFNetworking.h */, + 018B520CB407C3492F13C3767C15E377 /* UIProgressView+AFNetworking.m */, + 0044E51493E8CC5F8C46E1EC18F97722 /* UIRefreshControl+AFNetworking.h */, + B070DCCCA22D6ECC24DC0BD5CCEF5372 /* UIRefreshControl+AFNetworking.m */, + 9E3334C24AC0A37A21A6D9B9ECA94AB2 /* WKWebView+AFNetworking.h */, + 71A4B6E144674403F50435C67561B1BB /* WKWebView+AFNetworking.m */, + ); + name = UIKit; + sourceTree = ""; + }; + AA7E5CA260B4C52744905877A30A95DD /* Products */ = { + isa = PBXGroup; + children = ( + A4FA15D44DF6BAC7550EDEED10862AA3 /* AFNetworking */, + 1FFED36A657123030ABB700256D73F15 /* Masonry */, + 2B276B0A79173A1D6E83C9B4FB9A4A57 /* MJExtension */, + 43EAAD2AB7E6B407E80E95F643F93D22 /* MJExtension-MJExtension */, + E49D6D248DD1CEE584E6776B9164A1B2 /* MJRefresh */, + 7E3097CFEFDA621E9FB0E62009FF87FC /* MJRefresh-MJRefresh.Privacy */, + 0B4AAC15A428CDC2A62AF9CC27BEA609 /* Pods-CustomKeyboard */, + DCA062FD08AC9694D8D781B3492421C5 /* Pods-keyBoard */, + B0B214D775196BA7CA8E17E53048A493 /* SDWebImage */, + CF1281E58AA1045D4B7F33FC56691C42 /* SDWebImage-SDWebImage */, + ); + name = Products; + sourceTree = ""; + }; + B9D225EE05CF747670C5F4383D1D8D95 /* Support Files */ = { + isa = PBXGroup; + children = ( + 1170792DCF45BF664C43019D3E77D80F /* Masonry.modulemap */, + 5E8106411081DD6C7F5FE7804947412C /* Masonry-dummy.m */, + 9ADF16A9C4A54B7486F74B1F31DE3947 /* Masonry-Info.plist */, + 1C3E83B47A120437F73D41A878F182D1 /* Masonry-prefix.pch */, + 92D14A3D3FA826806436A8CFCBD915DA /* Masonry-umbrella.h */, + 4EF47C40D45E06BA89946B4C9F04A546 /* Masonry.debug.xcconfig */, + 396F4E7921EA26CDE8AAEADDD8CFBB49 /* Masonry.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/Masonry"; + sourceTree = ""; + }; + C006D91CB7EF7E3CDD3E746411DCC861 /* Resources */ = { + isa = PBXGroup; + children = ( + 970B39752136D5831550118975DC4A91 /* PrivacyInfo.xcprivacy */, + ); + name = Resources; + sourceTree = ""; + }; + CF1408CF629C7361332E53B88F7BD30C = { + isa = PBXGroup; + children = ( + 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */, + 03C5C200A0787E300053CFA8F53CA094 /* Frameworks */, + DCE595EEF85D396533FF4892F3008A92 /* Pods */, + AA7E5CA260B4C52744905877A30A95DD /* Products */, + F7ED90CD818DD0484BF7DB0E1E3B9AB2 /* Targets Support Files */, + ); + sourceTree = ""; + }; + D1B9DC187765592AAEEACCE698694E27 /* Security */ = { + isa = PBXGroup; + children = ( + 85AD1C60C75A73E360E4320DD271A77D /* AFSecurityPolicy.h */, + 52AA08F30FFF4D9FF32F48E3AC195A6A /* AFSecurityPolicy.m */, + ); + name = Security; + sourceTree = ""; + }; + D4CA9D10912142FCCA40F947B4FC5D1C /* SDWebImage */ = { + isa = PBXGroup; + children = ( + 2FC4867627CDCD8FC332BB686C62FDE4 /* Core */, + 72EAC702A61A19B6EC92D70B6CA9D4E8 /* Support Files */, + ); + name = SDWebImage; + path = SDWebImage; + sourceTree = ""; + }; + DCE595EEF85D396533FF4892F3008A92 /* Pods */ = { + isa = PBXGroup; + children = ( + 72657A79EE3B081E5F0D7C1166237E68 /* AFNetworking */, + 502B3DC21E7D9121A0C4B98D3286C994 /* Bugly */, + 18AF1EE6F6DA0C51E0452AA62EF8B8ED /* Masonry */, + 1F956714C6A7CF7B7999AEB4E29D418F /* MJExtension */, + 3128165374A2707E315E77D530A52B15 /* MJRefresh */, + D4CA9D10912142FCCA40F947B4FC5D1C /* SDWebImage */, + ); + name = Pods; + sourceTree = ""; + }; + E09502DD4B1D7ABBB4407C6ED07C0666 /* Support Files */ = { + isa = PBXGroup; + children = ( + 4CD2E3B8C4EBAB8CE1F46D4D7B1B5CAA /* Bugly.debug.xcconfig */, + 6134DA50CBB0F618C7502B9B4E23963F /* Bugly.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/Bugly"; + sourceTree = ""; + }; + F7ED90CD818DD0484BF7DB0E1E3B9AB2 /* Targets Support Files */ = { + isa = PBXGroup; + children = ( + 47B776543D6613BCB6FB72308F863018 /* Pods-CustomKeyboard */, + 4098ED899C8DF8E013F9F260ECFAA236 /* Pods-keyBoard */, + ); + name = "Targets Support Files"; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + 0A3C36B0909C1076801B26E74787825A /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 61857C821395B868C65A8FFE4DA1B4E3 /* MJExtension.h in Headers */, + 14943D0EE97A4966510A86F5C3FC66A5 /* MJExtension-umbrella.h in Headers */, + A3EA39A13714B3103B82F4066A642F53 /* MJExtensionConst.h in Headers */, + BF0C3D2782FE1425C2F1F8827132A94B /* MJFoundation.h in Headers */, + 9358FC6C6DA728AEE250D8E7DD236946 /* MJProperty.h in Headers */, + 288CD3416B265CAC1300D7938167AE66 /* MJPropertyKey.h in Headers */, + 56D8A7EAE4D72FF6C23421CAB6F21504 /* MJPropertyType.h in Headers */, + 71538A1D21015F459964BA625D5EE90A /* NSObject+MJClass.h in Headers */, + 1EA011B45EC780B434507AFB3D9647ED /* NSObject+MJCoding.h in Headers */, + D2AF9A7FD73B95960FDA4FD06C4BED08 /* NSObject+MJKeyValue.h in Headers */, + A1DC9EFDF50DF0EAF24D9D7C219AD2C1 /* NSObject+MJProperty.h in Headers */, + EED016DE8173CD38CC01D88CD2628984 /* NSString+MJExtension.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 0EF2526B5CC15C0E915F32190565F64C /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + BA904ABA8ED36CC4E5EB2B2004CA1F18 /* MASCompositeConstraint.h in Headers */, + 37B890ABDC7DD441E6AA662325D412E6 /* MASConstraint.h in Headers */, + 7C5505A2D3F2A697A5F324787061F4B7 /* MASConstraint+Private.h in Headers */, + 813BE4C96A6D39C13EC50C6CD164F0AF /* MASConstraintMaker.h in Headers */, + B680C2604BD8BC9644AE7C67BC46B9BB /* MASLayoutConstraint.h in Headers */, + EC9B34262AED632D7EFB49804337648E /* Masonry.h in Headers */, + B59E60FBC9665FC1061B88B8E6FD9FAF /* Masonry-umbrella.h in Headers */, + C2068AEACC2D9C7F1FFE41AA25B12A68 /* MASUtilities.h in Headers */, + 05E2B7C1DB7528A0BBEA1521BE0DBAF1 /* MASViewAttribute.h in Headers */, + 5F45735DF355530CC955066D3C007E19 /* MASViewConstraint.h in Headers */, + BF22D137EF6324675FA50080C5D93C00 /* NSArray+MASAdditions.h in Headers */, + 61507E402F1F7C58BF119995A0479A22 /* NSArray+MASShorthandAdditions.h in Headers */, + DBA9500CBBA5FF6FCBBA115AE4D12152 /* NSLayoutConstraint+MASDebugAdditions.h in Headers */, + AE7B02645B8F769CA5F215EE8F7CC5B0 /* View+MASAdditions.h in Headers */, + 772CF8E9CD02ECA4275B6173E2110E80 /* View+MASShorthandAdditions.h in Headers */, + 8C6C7E25C5A24C936F81823978190E96 /* ViewController+MASAdditions.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 22C4F6C2D1258108CF5B6E74F03D0EB2 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 7989A6E79BFA78440C39F568D972305C /* MJRefresh.h in Headers */, + 325CA20B9271F3E008234E1518B79061 /* MJRefresh-umbrella.h in Headers */, + 561420A20DC0A84258A902E9EB69A15A /* MJRefreshAutoFooter.h in Headers */, + EC8E84A8FFADDCA562A8608D141D9027 /* MJRefreshAutoGifFooter.h in Headers */, + 7902D28FC9EF5AFEB452F508C7F266B1 /* MJRefreshAutoNormalFooter.h in Headers */, + 5BB6B99986FD7111B3AEBE931C7F507B /* MJRefreshAutoStateFooter.h in Headers */, + 45E1583D7EF53489B82C4CA2AD1AD0CF /* MJRefreshBackFooter.h in Headers */, + 475B4F3E71C293065AAFDB1888696CF6 /* MJRefreshBackGifFooter.h in Headers */, + 9A7FB1E975A5955C896E6B195C521804 /* MJRefreshBackNormalFooter.h in Headers */, + 08719ABCE689ED74FE7486B1E49DAA6C /* MJRefreshBackStateFooter.h in Headers */, + 69345CBCB31076EBF8A2C5885AF973AB /* MJRefreshComponent.h in Headers */, + 4DCA75BFE1558CE59DFC56607E49B3D2 /* MJRefreshConfig.h in Headers */, + 28BA9702905AA2B4C1E9E4878032D4E4 /* MJRefreshConst.h in Headers */, + D90DED0F5638B1C44F4B6C62D600D240 /* MJRefreshFooter.h in Headers */, + 61461B0D9D7B81C3F8D24066D9A19DCE /* MJRefreshGifHeader.h in Headers */, + 442F468E261A1106C291BF52BDBF9DB7 /* MJRefreshHeader.h in Headers */, + EE6E8FE636D2C02E3D2FC1E8555B4612 /* MJRefreshNormalHeader.h in Headers */, + BC2F9B1D6986FEB23B4FB1288B512538 /* MJRefreshNormalTrailer.h in Headers */, + 5DFCBADAC7D0FAC82C84A6C8E7BF1DA6 /* MJRefreshStateHeader.h in Headers */, + F60F90EAF35CFF40DF1C33557965787D /* MJRefreshStateTrailer.h in Headers */, + 523235228A1C021C67F2E3776A922DC5 /* MJRefreshTrailer.h in Headers */, + 81A5635CEA2AD9623E30CAE9AFC3BF65 /* NSBundle+MJRefresh.h in Headers */, + 5163FC6D715F6881B1FA1AB13DCEF870 /* UICollectionViewLayout+MJRefresh.h in Headers */, + 22516EA77E7120000632C30BD9A03927 /* UIScrollView+MJExtension.h in Headers */, + 69E353C99C6EEA3C93CCF2E526460B9D /* UIScrollView+MJRefresh.h in Headers */, + 3A2FCB914F6EADED828FF05F7E9132AE /* UIView+MJExtension.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33783D69751B087D045FCF1FCA02E724 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 9B9343E8599EE5196BA75E842DCB48B7 /* NSBezierPath+SDRoundedCorners.h in Headers */, + A839428F403C52D8AA3466B65E20C27A /* NSButton+WebCache.h in Headers */, + 8AF38EDB1E9BF0D334AEB23C488870B8 /* NSData+ImageContentType.h in Headers */, + 34B28D4F0168194B6EFAC0520EB7A7F4 /* NSImage+Compatibility.h in Headers */, + 9B3420DEB8A0CCB9E1241A669AEFCA8E /* SDAnimatedImage.h in Headers */, + BDBE494BAC544843982C3CA96A6C41DD /* SDAnimatedImagePlayer.h in Headers */, + DEA09692CF813A23899CD4949A9B6801 /* SDAnimatedImageRep.h in Headers */, + C1DD8C6A64F948E4C53560C76B995DA4 /* SDAnimatedImageView.h in Headers */, + D7B3E8948DB04BD8FB6748419DA03EA9 /* SDAnimatedImageView+WebCache.h in Headers */, + 5C8279C226EB028B044C5A0F4AC5A91A /* SDAssociatedObject.h in Headers */, + 20D618EF3EA5E3BE96DA24D36E3CA9EF /* SDAsyncBlockOperation.h in Headers */, + ED8F64FF98CFAE0B12CF60A1B0E6BAF8 /* SDCallbackQueue.h in Headers */, + 042D40751BD2F51FBE9FECD4707CBBE9 /* SDDeviceHelper.h in Headers */, + 928371B066E1211CE87089668D5BCB4C /* SDDiskCache.h in Headers */, + 7074EA7FCC90B4967A437F5C43496828 /* SDDisplayLink.h in Headers */, + 0453019EC6578A67B82CF569EC765546 /* SDFileAttributeHelper.h in Headers */, + 5E10328A83E05D0015D7459FAAEF121D /* SDGraphicsImageRenderer.h in Headers */, + 165F1C9CBD621828C788A3018D0426C5 /* SDImageAPNGCoder.h in Headers */, + 4B2C2AE16AE3DDA7417AFCF7952588F1 /* SDImageAssetManager.h in Headers */, + B4F231C5CBAB3D4A184699D0066E0E83 /* SDImageAWebPCoder.h in Headers */, + D662C83ECE8BEDA5FFB52F3575CA3E1A /* SDImageCache.h in Headers */, + 14CA284AC4FF1EED75E785641EE98034 /* SDImageCacheConfig.h in Headers */, + ABCB80C4813C849FC93D57676820C907 /* SDImageCacheDefine.h in Headers */, + F53BE4449AE5896F76325E4DCB6D0B13 /* SDImageCachesManager.h in Headers */, + 1C8B70C74291A3076746C3B18781568E /* SDImageCachesManagerOperation.h in Headers */, + 09A2ACBC8CE1761652EAA20886AEFE10 /* SDImageCoder.h in Headers */, + F68889CD481716EE5D6B75EBD8FD53A6 /* SDImageCoderHelper.h in Headers */, + B741DBE2A466E6211F879EF997D9322D /* SDImageCodersManager.h in Headers */, + 6B5C3592B5E911E833D067D0BC785B1A /* SDImageFrame.h in Headers */, + 44CD842019B1CEA681F820F37A30B7C4 /* SDImageFramePool.h in Headers */, + 1B6CE67196EE181E6B56788EFC7E00D3 /* SDImageGIFCoder.h in Headers */, + B331CE2D3DEB461E738B886086A365F9 /* SDImageGraphics.h in Headers */, + E76969F9B01139118427505B18F9CD21 /* SDImageHEICCoder.h in Headers */, + 089F3C4BAA46A37EC5763DD312771021 /* SDImageIOAnimatedCoder.h in Headers */, + 676775CB29378BB6CA3CA5992E9C6A99 /* SDImageIOAnimatedCoderInternal.h in Headers */, + D2CD8848F856EC9942A76610AAE66F0A /* SDImageIOCoder.h in Headers */, + C6A100159974349FEAAC99B82BE0F872 /* SDImageLoader.h in Headers */, + 10017B43AC38C3A89D7AC1376C6E7066 /* SDImageLoadersManager.h in Headers */, + EF6A6C725598F572A70C5FCEE328C184 /* SDImageTransformer.h in Headers */, + 2DDD48230ED9E8068C7E439D79B99A8E /* SDInternalMacros.h in Headers */, + 88473AE7C22F952DACB39FA0758D1624 /* SDMemoryCache.h in Headers */, + 3A1AD84C0DC3C256418CC46739024E96 /* SDmetamacros.h in Headers */, + 58F7CE37BB4CB3BE806B68A502E6E1A7 /* SDWeakProxy.h in Headers */, + 711D32EF4A9901567A488291603BF906 /* SDWebImage.h in Headers */, + D62A672EEB252581BD972DDA862BE1DD /* SDWebImage-umbrella.h in Headers */, + 53433003112C4FE271EC985803862B61 /* SDWebImageCacheKeyFilter.h in Headers */, + 3C8F2F868D0C361CAF43E53CDB8EB631 /* SDWebImageCacheSerializer.h in Headers */, + 4688743B7B845309486559EB7BD5D147 /* SDWebImageCompat.h in Headers */, + EA82B6D97C9C5D0558047AF552D63203 /* SDWebImageDefine.h in Headers */, + 29F7F0E98FD26A96364DBACD7D5F237A /* SDWebImageDownloader.h in Headers */, + 854807558DCB972EDDFC1D00032BA6E4 /* SDWebImageDownloaderConfig.h in Headers */, + 91E8B94F8E02ABF5197DF5AE7D0B3934 /* SDWebImageDownloaderDecryptor.h in Headers */, + B66356D4E7E43B3D15324569AA7EBB05 /* SDWebImageDownloaderOperation.h in Headers */, + BCEFDE57BB0E0B36731C8D39FFA1BE2C /* SDWebImageDownloaderRequestModifier.h in Headers */, + 18AD90784D549657DF51BC8377DA3085 /* SDWebImageDownloaderResponseModifier.h in Headers */, + 7C45DBA62EE045C4922404182F6393B8 /* SDWebImageError.h in Headers */, + F49CB22863CCFEC7817D259F27F91C57 /* SDWebImageIndicator.h in Headers */, + A9A49E4A3BE8882F60DF32BAF39DE191 /* SDWebImageManager.h in Headers */, + 9DF446F8CA5BC4D4098766EC9063012C /* SDWebImageOperation.h in Headers */, + 3C7815EEC599DD7D42FDEF19B2FF1563 /* SDWebImageOptionsProcessor.h in Headers */, + AC14E56ECA7A4980A8E1CA68E800B12C /* SDWebImagePrefetcher.h in Headers */, + 6E66305665DBCFBCF5B2480BF705D500 /* SDWebImageTransition.h in Headers */, + 91AAF555B286FBF53E4F98D092B406BD /* SDWebImageTransitionInternal.h in Headers */, + BADA31750A2136D073EDA4461DBE1EEA /* UIButton+WebCache.h in Headers */, + 71BEB1D9532900291A5A24B1C038516F /* UIColor+SDHexString.h in Headers */, + 1830558A4D2D63C8E76BC3136D8213F9 /* UIImage+ExtendedCacheData.h in Headers */, + 75771A97B77FA30A0175A81B480F80EF /* UIImage+ForceDecode.h in Headers */, + A1560247914C760D9EE5F7A2392CC06C /* UIImage+GIF.h in Headers */, + 4ED05DB3E43FF6AE1FA22130B2B50F05 /* UIImage+MemoryCacheCost.h in Headers */, + 5DCBA14510E091D6A1CE499B08B794B5 /* UIImage+Metadata.h in Headers */, + 3C7EAECB8C573E714C818BA04EB33773 /* UIImage+MultiFormat.h in Headers */, + 8D8AD606ECD8E1F247965CD43956D412 /* UIImage+Transform.h in Headers */, + 6A19379E3B0370EDA447743C9B1A1379 /* UIImageView+HighlightedWebCache.h in Headers */, + 32ACEDCEBE0507A82D6323114A1C74F1 /* UIImageView+WebCache.h in Headers */, + 36F4B09E7C71DCC5CEC6057814033C37 /* UIView+WebCache.h in Headers */, + B5AF87C11A465F666473F6191D173905 /* UIView+WebCacheOperation.h in Headers */, + 69AB6A513D5F36D7360FEF4FDA1D60D0 /* UIView+WebCacheState.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 66226021984AAF2F39AE410BEA754D6C /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 3FE4CEC187728FF5B98CECE3D92744E7 /* Pods-CustomKeyboard-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6EFC0393FC31641E19E2060FE077490A /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + BCFA1CA56CA625A754714006E0032750 /* Pods-keyBoard-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + C6390AB04A018D57637AAB0718C31A83 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + B030B558BE97E0225652EFB8C8FA431F /* AFAutoPurgingImageCache.h in Headers */, + 9D422527A25BAE6A207DEFE11958ABBC /* AFCompatibilityMacros.h in Headers */, + 506FC58999564A737C745F2590E9B4D5 /* AFHTTPSessionManager.h in Headers */, + FDACBA49610EA6F39CABB7FE44B137D1 /* AFImageDownloader.h in Headers */, + 7FF8A56511E71D6FEC966BF9FEE135B5 /* AFNetworkActivityIndicatorManager.h in Headers */, + E1BF615DD0422B06C97542F03C879D41 /* AFNetworking.h in Headers */, + BC5458210A973BC7A29D1F45D458A14B /* AFNetworking-umbrella.h in Headers */, + F1D845E22D5B8FC6AFC3C2E41DA1B6DF /* AFNetworkReachabilityManager.h in Headers */, + DBD9152526A180771BF7D7CD209B957E /* AFSecurityPolicy.h in Headers */, + 724991CA89C46BAFBC08264D94D86484 /* AFURLRequestSerialization.h in Headers */, + F2AD91050B1FE3C8BC78567F1FDE3ED5 /* AFURLResponseSerialization.h in Headers */, + 3B8EDFF69A68ABD3735E0C6931CA5C95 /* AFURLSessionManager.h in Headers */, + 860CB3A5D2E13B946CD2EFB7F749C4CF /* UIActivityIndicatorView+AFNetworking.h in Headers */, + E3FC6BEE41652C0500F57E0CB83B347F /* UIButton+AFNetworking.h in Headers */, + EB3DF628891F7D6AB114718AF760CB2A /* UIImageView+AFNetworking.h in Headers */, + DDA16FB9C21AD941442357DAE6939530 /* UIKit+AFNetworking.h in Headers */, + 5AF22814CD055B553AD9D78BE54B94E1 /* UIProgressView+AFNetworking.h in Headers */, + 7F886FC2763F0BF1625A24EE4F94C04D /* UIRefreshControl+AFNetworking.h in Headers */, + C0D7926E41A294ACA98D7B033B283919 /* WKWebView+AFNetworking.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + 0130B3724283586C0E9D2A112D4F2AA1 /* AFNetworking */ = { + isa = PBXNativeTarget; + buildConfigurationList = 7CEB2E47380AD51987AA02ECD4DFBCD9 /* Build configuration list for PBXNativeTarget "AFNetworking" */; + buildPhases = ( + C6390AB04A018D57637AAB0718C31A83 /* Headers */, + D08DDDF416AB9EEE26C8FFEE674F7A12 /* Sources */, + 37145BAEB1B97BA7ADD7D6C3E86E99BD /* Frameworks */, + 9BB224D4E89ABC2539ABBEBDC9696C8F /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = AFNetworking; + productName = AFNetworking; + productReference = A4FA15D44DF6BAC7550EDEED10862AA3 /* AFNetworking */; + productType = "com.apple.product-type.framework"; + }; + 18BD026D2210082A239FC15D072FD5BF /* Pods-keyBoard */ = { + isa = PBXNativeTarget; + buildConfigurationList = FCE3E8712CE5CB67BC702E493D7E2243 /* Build configuration list for PBXNativeTarget "Pods-keyBoard" */; + buildPhases = ( + 6EFC0393FC31641E19E2060FE077490A /* Headers */, + AFB5D9B93B578996ABD51507560BD64E /* Sources */, + 83DE9F788F7FEF1F8FBE5407651F444D /* Frameworks */, + 9CB9573035BE4B2A4B846ACC7B123B63 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 0721A67E09079773C9FD71FC8AD5FC9D /* PBXTargetDependency */, + 42FDF14E242A83A309A5E0E9AD872BFB /* PBXTargetDependency */, + 3A51A97E9A7AF97FA982A4106AD313E7 /* PBXTargetDependency */, + 3B75BE7D78DA9D8EB2007A2C8507D93E /* PBXTargetDependency */, + A0F34F7F072B46F24802F53958145C52 /* PBXTargetDependency */, + 10BF5B7304DB404D9CB72D3A79065773 /* PBXTargetDependency */, + ); + name = "Pods-keyBoard"; + productName = Pods_keyBoard; + productReference = DCA062FD08AC9694D8D781B3492421C5 /* Pods-keyBoard */; + productType = "com.apple.product-type.framework"; + }; + 3847153A6E5EEFB86565BA840768F429 /* SDWebImage */ = { + isa = PBXNativeTarget; + buildConfigurationList = 2F9E94B5F79E365095CB33D3D3FCA6A2 /* Build configuration list for PBXNativeTarget "SDWebImage" */; + buildPhases = ( + 33783D69751B087D045FCF1FCA02E724 /* Headers */, + 090ABC49CEE6AE75BCDDAAED6457F183 /* Sources */, + 3A5330E1BD187252F408EBB46F1BDC42 /* Frameworks */, + 44B3C0D7DDF289331B7732E9D87126DB /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 88E2D8F9CA39C89731F3AE8B00D15E67 /* PBXTargetDependency */, + ); + name = SDWebImage; + productName = SDWebImage; + productReference = B0B214D775196BA7CA8E17E53048A493 /* SDWebImage */; + productType = "com.apple.product-type.framework"; + }; + 4D3BA58D0583DF37575CACAB3DDADC85 /* MJExtension */ = { + isa = PBXNativeTarget; + buildConfigurationList = 547AC2DDC5CDD1783E0827EEA7D453E1 /* Build configuration list for PBXNativeTarget "MJExtension" */; + buildPhases = ( + 0A3C36B0909C1076801B26E74787825A /* Headers */, + 090A96B9D443BC38DD5A251A9EE646AE /* Sources */, + 9E666AF8497E0DE090335A642D5B84EC /* Frameworks */, + 1B0BF833FF02F4B145B7A6461734A0F1 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 394032A92C21422B814C089279FA7D6F /* PBXTargetDependency */, + ); + name = MJExtension; + productName = MJExtension; + productReference = 2B276B0A79173A1D6E83C9B4FB9A4A57 /* MJExtension */; + productType = "com.apple.product-type.framework"; + }; + 55AF53E6C77A10ED4985E04D74A8878E /* Masonry */ = { + isa = PBXNativeTarget; + buildConfigurationList = AAA1F8799DB68036C3BE983C05FAA2C7 /* Build configuration list for PBXNativeTarget "Masonry" */; + buildPhases = ( + 0EF2526B5CC15C0E915F32190565F64C /* Headers */, + DA0B6A6F9B3EDF226BF081DAC7E777E7 /* Sources */, + 12A799DC8ABB2C283ADDDED4421A5EAB /* Frameworks */, + ECD6B9A8E754DF142B323DF2D7E0D112 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Masonry; + productName = Masonry; + productReference = 1FFED36A657123030ABB700256D73F15 /* Masonry */; + productType = "com.apple.product-type.framework"; + }; + 6868056D761E163D10FDAF8CF1C4D9B8 /* MJRefresh */ = { + isa = PBXNativeTarget; + buildConfigurationList = 29BB59B7B51BC6194771995E3356CF70 /* Build configuration list for PBXNativeTarget "MJRefresh" */; + buildPhases = ( + 22C4F6C2D1258108CF5B6E74F03D0EB2 /* Headers */, + E01EA717D0A0AF8E12D145A5F2252FD2 /* Sources */, + 11690A588400BBB164423D5F86311C35 /* Frameworks */, + 4A4F8947EF95B9D0D1FCFC1296740510 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + F4DB95A938613EB239394D9BC7D85E47 /* PBXTargetDependency */, + ); + name = MJRefresh; + productName = MJRefresh; + productReference = E49D6D248DD1CEE584E6776B9164A1B2 /* MJRefresh */; + productType = "com.apple.product-type.framework"; + }; + 94CFBA7D633ECA58DF85C327B035E6A3 /* SDWebImage-SDWebImage */ = { + isa = PBXNativeTarget; + buildConfigurationList = 3A3BFFB46D4AE092AC96BD3D9D624546 /* Build configuration list for PBXNativeTarget "SDWebImage-SDWebImage" */; + buildPhases = ( + 14B98376E3B2827487D1B5BA7E349E67 /* Sources */, + 5F8D0AA57E07244D2E43526654F67443 /* Frameworks */, + F94894A2558471C720587EA6709F2019 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "SDWebImage-SDWebImage"; + productName = SDWebImage; + productReference = CF1281E58AA1045D4B7F33FC56691C42 /* SDWebImage-SDWebImage */; + productType = "com.apple.product-type.bundle"; + }; + B26054DF1DEA11585A231AF6D1D80D5E /* MJRefresh-MJRefresh.Privacy */ = { + isa = PBXNativeTarget; + buildConfigurationList = 68B32BA86F0CEE6E06F49B0F2C62CD73 /* Build configuration list for PBXNativeTarget "MJRefresh-MJRefresh.Privacy" */; + buildPhases = ( + A1FDE66B11377A083FC25DE4671B3305 /* Sources */, + 2195E2C2C2334091D023B7EB98B24603 /* Frameworks */, + FF140DFA44CFFB4A12C0595EC42174A6 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "MJRefresh-MJRefresh.Privacy"; + productName = MJRefresh.Privacy; + productReference = 7E3097CFEFDA621E9FB0E62009FF87FC /* MJRefresh-MJRefresh.Privacy */; + productType = "com.apple.product-type.bundle"; + }; + B32AF3F43989CBA171BB1FB3957A4509 /* MJExtension-MJExtension */ = { + isa = PBXNativeTarget; + buildConfigurationList = 4650649B39AEE2A0C6FEE8FF9B18E065 /* Build configuration list for PBXNativeTarget "MJExtension-MJExtension" */; + buildPhases = ( + 83E45E911DCE522BC4265AAB5CBA73D3 /* Sources */, + E62253CBB3499DA4547AF2A780EC3E2F /* Frameworks */, + AA2ABB6111F2F1BE117241EC515B268B /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "MJExtension-MJExtension"; + productName = MJExtension; + productReference = 43EAAD2AB7E6B407E80E95F643F93D22 /* MJExtension-MJExtension */; + productType = "com.apple.product-type.bundle"; + }; + D9B2DB11933DB55A80A118934E6680AB /* Pods-CustomKeyboard */ = { + isa = PBXNativeTarget; + buildConfigurationList = DA39DBDB0F7D05D976CC7C6A67459F5F /* Build configuration list for PBXNativeTarget "Pods-CustomKeyboard" */; + buildPhases = ( + 66226021984AAF2F39AE410BEA754D6C /* Headers */, + 253ADC0B42FA607A67D61C10A572535E /* Sources */, + 0DDBBB716811E63091A5A45D29A5FEFA /* Frameworks */, + E41CF6701928D5454D4C51832F5D994D /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "Pods-CustomKeyboard"; + productName = Pods_CustomKeyboard; + productReference = 0B4AAC15A428CDC2A62AF9CC27BEA609 /* Pods-CustomKeyboard */; + productType = "com.apple.product-type.framework"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + BFDFE7DC352907FC980B868725387E98 /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 1600; + LastUpgradeCheck = 1600; + }; + buildConfigurationList = 4821239608C13582E20E6DA73FD5F1F9 /* Build configuration list for PBXProject "Pods" */; + compatibilityVersion = "Xcode 16.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + Base, + en, + ); + mainGroup = CF1408CF629C7361332E53B88F7BD30C; + minimizedProjectReferenceProxies = 0; + preferredProjectObjectVersion = 77; + productRefGroup = AA7E5CA260B4C52744905877A30A95DD /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 0130B3724283586C0E9D2A112D4F2AA1 /* AFNetworking */, + 4A68CFD979D413A619DF631BB121D98F /* Bugly */, + 55AF53E6C77A10ED4985E04D74A8878E /* Masonry */, + 4D3BA58D0583DF37575CACAB3DDADC85 /* MJExtension */, + B32AF3F43989CBA171BB1FB3957A4509 /* MJExtension-MJExtension */, + 6868056D761E163D10FDAF8CF1C4D9B8 /* MJRefresh */, + B26054DF1DEA11585A231AF6D1D80D5E /* MJRefresh-MJRefresh.Privacy */, + D9B2DB11933DB55A80A118934E6680AB /* Pods-CustomKeyboard */, + 18BD026D2210082A239FC15D072FD5BF /* Pods-keyBoard */, + 3847153A6E5EEFB86565BA840768F429 /* SDWebImage */, + 94CFBA7D633ECA58DF85C327B035E6A3 /* SDWebImage-SDWebImage */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 1B0BF833FF02F4B145B7A6461734A0F1 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 7873F2F89CD0A435FAB776BC27BFB56A /* MJExtension-MJExtension in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 44B3C0D7DDF289331B7732E9D87126DB /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 16D7DCB7CC985C33EEC41B371C029C84 /* SDWebImage-SDWebImage in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 4A4F8947EF95B9D0D1FCFC1296740510 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + D90DF1376DF5E2EA644313BCD2E03058 /* MJRefresh.bundle in Resources */, + 327BA3DDA513422E632D3DA4A8FC60EC /* MJRefresh-MJRefresh.Privacy in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 9BB224D4E89ABC2539ABBEBDC9696C8F /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 9CB9573035BE4B2A4B846ACC7B123B63 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + AA2ABB6111F2F1BE117241EC515B268B /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 1C73BC7EEF39CC3D3A21EACAD858413D /* PrivacyInfo.xcprivacy in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + E41CF6701928D5454D4C51832F5D994D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + ECD6B9A8E754DF142B323DF2D7E0D112 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + F94894A2558471C720587EA6709F2019 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 0BADC710EA22BBCD76E59748C2A56ECF /* PrivacyInfo.xcprivacy in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FF140DFA44CFFB4A12C0595EC42174A6 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + AF1A6353DEDBE196A10C8897F94DDA8E /* PrivacyInfo.xcprivacy in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 090A96B9D443BC38DD5A251A9EE646AE /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 2055774CD703B52DABFB1CC588394A94 /* MJExtension-dummy.m in Sources */, + F3263D294D688533EB974E37C61F1E24 /* MJExtensionConst.m in Sources */, + 126496714AD564062A8C10787CC01B8B /* MJFoundation.m in Sources */, + AC710813CB6A1DAEEE45914402F864D2 /* MJProperty.m in Sources */, + DED9ADFC8CC65243FC54E008A853742C /* MJPropertyKey.m in Sources */, + 512B9661FC34235E0EEB3A6D3E319B88 /* MJPropertyType.m in Sources */, + 5174DD2019966DFDC21B8864453ED3DE /* NSObject+MJClass.m in Sources */, + 321F87DA34863DC5C977323BAEDB2B55 /* NSObject+MJCoding.m in Sources */, + 7FA8C78DB021A7731D30D80C102DE042 /* NSObject+MJKeyValue.m in Sources */, + B48A975992E58328254C494F133DE467 /* NSObject+MJProperty.m in Sources */, + 1ECC5F320AEFB120081358B4FFB7442F /* NSString+MJExtension.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 090ABC49CEE6AE75BCDDAAED6457F183 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + FA3021DED76B9B182CC9195A60EB1209 /* NSBezierPath+SDRoundedCorners.m in Sources */, + 48916DE9521F627589300512ECC2D4A5 /* NSButton+WebCache.m in Sources */, + 416DA8B2997381F954DBA6E6A53DA4A2 /* NSData+ImageContentType.m in Sources */, + 88A23DF6F5638AC66C28C4102824E8B5 /* NSImage+Compatibility.m in Sources */, + 1708C1D28B421C4AD310426D1695CE77 /* SDAnimatedImage.m in Sources */, + 7A4EB9ED5D4E03170FFE61FCB299687B /* SDAnimatedImagePlayer.m in Sources */, + 5111A0A0934551CD2B9DDB1A1CA79FA7 /* SDAnimatedImageRep.m in Sources */, + 62FE895DF9D65A2955A275D909ECBE18 /* SDAnimatedImageView.m in Sources */, + 67178A8153B1A2F1D0D544B8093E23C5 /* SDAnimatedImageView+WebCache.m in Sources */, + C93E972E75F84674690300123984EC43 /* SDAssociatedObject.m in Sources */, + 0B0E6CECDF516BC83756C1D5515A725B /* SDAsyncBlockOperation.m in Sources */, + 69A06A02F52EB26259FAD1DF6B121BE1 /* SDCallbackQueue.m in Sources */, + 526485EF6D2B62B24DB59122FB94BD42 /* SDDeviceHelper.m in Sources */, + 9CE425B89294BE2C13E70A86E75B15CF /* SDDiskCache.m in Sources */, + 5308E660E723C11E7691D311FD59C459 /* SDDisplayLink.m in Sources */, + 9345137ED10358B60E37D05FB6165759 /* SDFileAttributeHelper.m in Sources */, + 71F2B8CBB99087F348C472230200586F /* SDGraphicsImageRenderer.m in Sources */, + ECE64B732F9FA7C402DDEEC58DCB9D98 /* SDImageAPNGCoder.m in Sources */, + 6B0978C9398336656EE309E62060AEAB /* SDImageAssetManager.m in Sources */, + 597E390C0BBB75B8045B651C487C2034 /* SDImageAWebPCoder.m in Sources */, + 0FF9F459ED16719292443A4C99B52B20 /* SDImageCache.m in Sources */, + FCDEC6A53CF5517E1AF5B331FD65F6D9 /* SDImageCacheConfig.m in Sources */, + FEA8BA4F82CCBD1D28DCC7EF39FB4096 /* SDImageCacheDefine.m in Sources */, + 33D3587AF629B2FA21554DA002D6ACB8 /* SDImageCachesManager.m in Sources */, + 55F7C7F055A18044497F8C88CAE34118 /* SDImageCachesManagerOperation.m in Sources */, + E8AB529B9E0B4C23921344F6C4ABFEA4 /* SDImageCoder.m in Sources */, + B2704AFFC5CC053154839DB44924D255 /* SDImageCoderHelper.m in Sources */, + 4D2C79AB2D24CFEC864F08D913CE7692 /* SDImageCodersManager.m in Sources */, + 24E8E4ED0B5D988E3346E6638619F4E4 /* SDImageFrame.m in Sources */, + 320DE42AF3CFE11FF785FEB1A7E6547B /* SDImageFramePool.m in Sources */, + 83530BF68848CD2C4A79A1FD69B304A5 /* SDImageGIFCoder.m in Sources */, + E50613C67DD02AF6EA825DA0B31EFFAD /* SDImageGraphics.m in Sources */, + 18660FA595DBE133BB784E813A7122A8 /* SDImageHEICCoder.m in Sources */, + 288D796F3F7B9F42690E24A3B1018B2C /* SDImageIOAnimatedCoder.m in Sources */, + 717F76926C7BCB5B10C3037AD9239084 /* SDImageIOCoder.m in Sources */, + 6EFEEE3AE22E97DCEC4F5A3B88F56FC7 /* SDImageLoader.m in Sources */, + 85C0B4EE334B9972299E62DE61A4BB56 /* SDImageLoadersManager.m in Sources */, + 3D0BBFEC1921CE71BC240DC18D8BE540 /* SDImageTransformer.m in Sources */, + 864972FB0DF4B464B1B505AA5F788E91 /* SDInternalMacros.m in Sources */, + E0BCF21E9FA59F638C13ECCECC4D9690 /* SDMemoryCache.m in Sources */, + CA1E0DCDF679EA2DE2ED0915426E1D04 /* SDWeakProxy.m in Sources */, + 96E97174F4614FFA0649085022CB4AFE /* SDWebImage-dummy.m in Sources */, + B95C63A039D9D08896421291DEBD3AEB /* SDWebImageCacheKeyFilter.m in Sources */, + D06BB547D59D183FD1DDD84DEBAC9EE8 /* SDWebImageCacheSerializer.m in Sources */, + 1BC44E2FDD197D5210A23C9CCF1A906B /* SDWebImageCompat.m in Sources */, + 31DC2EC78AD1F8241AE6051EF9E73B0A /* SDWebImageDefine.m in Sources */, + 752822FE3F5092322D18FEC4533B79A9 /* SDWebImageDownloader.m in Sources */, + 74E069F8C9E22C0E37F261A5AB03A613 /* SDWebImageDownloaderConfig.m in Sources */, + 32F2B91621A2F8F9AD7C8E2B224D73F6 /* SDWebImageDownloaderDecryptor.m in Sources */, + AA1EA8F0F0470F1596B1FFA58ABF3375 /* SDWebImageDownloaderOperation.m in Sources */, + 00DAE48C9A4FBCD1FCAA922CA57B45F9 /* SDWebImageDownloaderRequestModifier.m in Sources */, + 2F6D9BEA582A2DBB70A6C3B2FC2DB91E /* SDWebImageDownloaderResponseModifier.m in Sources */, + 425C9EA28FBEB7F7FC09A3F4A88C5955 /* SDWebImageError.m in Sources */, + CFF8D1A5E4C2097EF05E1021FE112886 /* SDWebImageIndicator.m in Sources */, + 97235408E59E16C18B6BDA1D29E1CB26 /* SDWebImageManager.m in Sources */, + 1754DD5511A7BF462B116F70B0D4006A /* SDWebImageOperation.m in Sources */, + 906DCE66CD5BD236081D468616199BB7 /* SDWebImageOptionsProcessor.m in Sources */, + 0F1D0F5DCC8C94A4C684DF846D14F436 /* SDWebImagePrefetcher.m in Sources */, + 3187FF0C251D1B78BE87F64F6F6E944A /* SDWebImageTransition.m in Sources */, + A92AB5E65CA85947368E46E6627F1BFB /* UIButton+WebCache.m in Sources */, + 6F3637EE643EABB1DE9212EA68649A64 /* UIColor+SDHexString.m in Sources */, + E4F1B478580D6D7328BC29607BDE46F6 /* UIImage+ExtendedCacheData.m in Sources */, + 08D50C5AC969A3701B6F9137CF3A10F1 /* UIImage+ForceDecode.m in Sources */, + C2840BF1950FF7EE2DCD6D55F768A49C /* UIImage+GIF.m in Sources */, + 596180E0EC9F46D12BA840DC4AA62659 /* UIImage+MemoryCacheCost.m in Sources */, + 694B8697854A776E32032999B2EF1FEA /* UIImage+Metadata.m in Sources */, + BCDC1E1D46DD124B5726A064D2EE66A3 /* UIImage+MultiFormat.m in Sources */, + 06C4E233E7977DB81A24482E69B2D7D7 /* UIImage+Transform.m in Sources */, + FCEE5BD645E95FF55468C4AB6D17CFDA /* UIImageView+HighlightedWebCache.m in Sources */, + 38938E604A7D708E6378A44063EF3512 /* UIImageView+WebCache.m in Sources */, + 616A8338C42FB01748DF1BDDA944858D /* UIView+WebCache.m in Sources */, + 97385A64CA020489951EF769392C6DCF /* UIView+WebCacheOperation.m in Sources */, + 74C474676C69A80BEC29B0F55FDF4D19 /* UIView+WebCacheState.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 14B98376E3B2827487D1B5BA7E349E67 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 253ADC0B42FA607A67D61C10A572535E /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + A3148D9EB39C7BFAF4F85E3378F3EF80 /* Pods-CustomKeyboard-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 83E45E911DCE522BC4265AAB5CBA73D3 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A1FDE66B11377A083FC25DE4671B3305 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + AFB5D9B93B578996ABD51507560BD64E /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 3CE201A6CFF26BD49792F9A8E4C822A5 /* Pods-keyBoard-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + D08DDDF416AB9EEE26C8FFEE674F7A12 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 6CA0B4A9E7B2957063163BC673F355CD /* AFAutoPurgingImageCache.m in Sources */, + 5A6D3BE92C77ED70C397567996DFAEB9 /* AFHTTPSessionManager.m in Sources */, + F7623E7C314AA5010D8D0BD6ED4AAAD4 /* AFImageDownloader.m in Sources */, + BACAA91A92F35CD7E7795232A83F21D1 /* AFNetworkActivityIndicatorManager.m in Sources */, + D5C046C46961BE465293625D6B870620 /* AFNetworking-dummy.m in Sources */, + FE07C069C2E3543002CEB5D751ABA9AC /* AFNetworkReachabilityManager.m in Sources */, + F9789D86D3279D71B398B550F27C3EFF /* AFSecurityPolicy.m in Sources */, + 564714D075CF51356D3D8437846AA6EB /* AFURLRequestSerialization.m in Sources */, + ED8991A8AE7C04362C2BED3875DC1656 /* AFURLResponseSerialization.m in Sources */, + 3331A013D48A5063B483A51B7E9068ED /* AFURLSessionManager.m in Sources */, + DE5A78F116018E2AC54714238276574D /* UIActivityIndicatorView+AFNetworking.m in Sources */, + E55B3151D86660E28CEABC3CDE6B1508 /* UIButton+AFNetworking.m in Sources */, + A0E0DC76F51300E7EB1EBA5492DE854D /* UIImageView+AFNetworking.m in Sources */, + 3FF7252DD60182221BB1E5A167C41A07 /* UIProgressView+AFNetworking.m in Sources */, + 6C85CA8D99E50C137D056B6057DAC58A /* UIRefreshControl+AFNetworking.m in Sources */, + 7F10C0D094C74F2FA4CD38C7FD77B0A8 /* WKWebView+AFNetworking.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + DA0B6A6F9B3EDF226BF081DAC7E777E7 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 8FF7B6477BFA6E6ABA168E1417291D5F /* MASCompositeConstraint.m in Sources */, + DF2B15402CE105F5A8CE48BBDCFFD5DD /* MASConstraint.m in Sources */, + F6D1C960368EB1E067ABD0BFF707FC56 /* MASConstraintMaker.m in Sources */, + C9E19D164C26414115CC969ED9A303C1 /* MASLayoutConstraint.m in Sources */, + 56E800EB3B2BE8AE0BA45A30974D7920 /* Masonry-dummy.m in Sources */, + E930A5612DC6D120BE040AD17C6D1BCD /* MASViewAttribute.m in Sources */, + C2FE60A10C792613E45031AE6E851ECB /* MASViewConstraint.m in Sources */, + 5B08596E856E4CC2F34A8A2372F9F764 /* NSArray+MASAdditions.m in Sources */, + C8EC35DFB0945DBE2F2FF9ECFE6D9711 /* NSLayoutConstraint+MASDebugAdditions.m in Sources */, + D788BA4B9E8186271BA75CA52B30502C /* View+MASAdditions.m in Sources */, + C857B8D2D0BAA5A8A764F9E1C4B85807 /* ViewController+MASAdditions.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + E01EA717D0A0AF8E12D145A5F2252FD2 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + DE98ECCCA7106A4EA575EF34830D41FF /* MJRefresh-dummy.m in Sources */, + 11C929E6BFB46F981685446F26DCE605 /* MJRefreshAutoFooter.m in Sources */, + E5B057BC87284367918B2DB9CA084B4E /* MJRefreshAutoGifFooter.m in Sources */, + 6DE6C7F0FA965828E4FCE687BF75FBBE /* MJRefreshAutoNormalFooter.m in Sources */, + 8872BEB0954C0254A792469F4DBC9891 /* MJRefreshAutoStateFooter.m in Sources */, + F3AECEF6D3BB919B3E7392942E1BC58B /* MJRefreshBackFooter.m in Sources */, + A1E44277704AD68E867FD7C955A6632D /* MJRefreshBackGifFooter.m in Sources */, + 955B87902E039163281C4F47C95DB851 /* MJRefreshBackNormalFooter.m in Sources */, + B09F08548ACA8379445F6525011EE219 /* MJRefreshBackStateFooter.m in Sources */, + C60DB44F719853DE3B7157960DAF9270 /* MJRefreshComponent.m in Sources */, + 2DC44A09A6C9D6DC7D1BDA2DFCF99EE3 /* MJRefreshConfig.m in Sources */, + 54E268C32915CF908E7AA776909B45EB /* MJRefreshConst.m in Sources */, + 186B573F1BEB8A23419A02814A7741DB /* MJRefreshFooter.m in Sources */, + FEE883575278D5BE8F185437AB5DB3BB /* MJRefreshGifHeader.m in Sources */, + 85AB23275E9D19394969235E5DC2300E /* MJRefreshHeader.m in Sources */, + 0EF10747EF2A02413E84BD5EF7C87A4B /* MJRefreshNormalHeader.m in Sources */, + D90607B4E56247B19B14462E487BA86E /* MJRefreshNormalTrailer.m in Sources */, + A078A275FFFA48D620074790DA3CA6CE /* MJRefreshStateHeader.m in Sources */, + 452C940762F65B125C216F73B369F583 /* MJRefreshStateTrailer.m in Sources */, + 5BD5D9B8F61C124A62C75D9AC36A07BD /* MJRefreshTrailer.m in Sources */, + 24E963C1D6245F98BAC8A0ACCB7DE987 /* NSBundle+MJRefresh.m in Sources */, + BD30193C1E3D7B1F17B1B1F3F08BE655 /* UICollectionViewLayout+MJRefresh.m in Sources */, + E1DE69F6BB6235A6EDB6C99A184BEDB4 /* UIScrollView+MJExtension.m in Sources */, + A86CC1AFDFDD692DC4EE66F57C0F39E6 /* UIScrollView+MJRefresh.m in Sources */, + 5FDC4239F7B651092BF582D0F460BAD4 /* UIView+MJExtension.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 0721A67E09079773C9FD71FC8AD5FC9D /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = AFNetworking; + target = 0130B3724283586C0E9D2A112D4F2AA1 /* AFNetworking */; + targetProxy = F4298358FEAF506C773B2D34F3DF6B12 /* PBXContainerItemProxy */; + }; + 10BF5B7304DB404D9CB72D3A79065773 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = SDWebImage; + target = 3847153A6E5EEFB86565BA840768F429 /* SDWebImage */; + targetProxy = F236FEF1E37470AFA015925961D566A3 /* PBXContainerItemProxy */; + }; + 394032A92C21422B814C089279FA7D6F /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "MJExtension-MJExtension"; + target = B32AF3F43989CBA171BB1FB3957A4509 /* MJExtension-MJExtension */; + targetProxy = 23C4ACB33CF11EF7F294BFEFDFEE525F /* PBXContainerItemProxy */; + }; + 3A51A97E9A7AF97FA982A4106AD313E7 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = MJExtension; + target = 4D3BA58D0583DF37575CACAB3DDADC85 /* MJExtension */; + targetProxy = D31947E4B8C395A2964CC7C4CA10B4B3 /* PBXContainerItemProxy */; + }; + 3B75BE7D78DA9D8EB2007A2C8507D93E /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = MJRefresh; + target = 6868056D761E163D10FDAF8CF1C4D9B8 /* MJRefresh */; + targetProxy = D00922B5D33413CCF1E3D4753D9B5522 /* PBXContainerItemProxy */; + }; + 42FDF14E242A83A309A5E0E9AD872BFB /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Bugly; + target = 4A68CFD979D413A619DF631BB121D98F /* Bugly */; + targetProxy = ED8283C03EBD084126ED5759CD5B7EF5 /* PBXContainerItemProxy */; + }; + 88E2D8F9CA39C89731F3AE8B00D15E67 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "SDWebImage-SDWebImage"; + target = 94CFBA7D633ECA58DF85C327B035E6A3 /* SDWebImage-SDWebImage */; + targetProxy = 8C46BC742135C578AA462516574ECF6A /* PBXContainerItemProxy */; + }; + A0F34F7F072B46F24802F53958145C52 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Masonry; + target = 55AF53E6C77A10ED4985E04D74A8878E /* Masonry */; + targetProxy = 7F4A11CEA9C42F01CCC8FD8CF31E0D31 /* PBXContainerItemProxy */; + }; + F4DB95A938613EB239394D9BC7D85E47 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "MJRefresh-MJRefresh.Privacy"; + target = B26054DF1DEA11585A231AF6D1D80D5E /* MJRefresh-MJRefresh.Privacy */; + targetProxy = 74C35E0C9F3979D774EBA89927D5F9BE /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 03A5A25907B9F099CB1930F2C4AA0E3F /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 4B22EE0B7D2C1D1066750C4AB84FDA27 /* MJExtension.release.xcconfig */; + buildSettings = { + CODE_SIGNING_ALLOWED = NO; + CONFIGURATION_BUILD_DIR = "$(BUILD_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/MJExtension"; + IBSC_MODULE = MJExtension; + INFOPLIST_FILE = "Target Support Files/MJExtension/ResourceBundle-MJExtension-MJExtension-Info.plist"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + PRODUCT_NAME = MJExtension; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + WRAPPER_EXTENSION = bundle; + }; + name = Release; + }; + 0A6B03880AA76C2476846FABA9DAB99A /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 74CC813EBCFDBA413D1E8F2AE302E41A /* MJRefresh.debug.xcconfig */; + buildSettings = { + CODE_SIGNING_ALLOWED = NO; + CONFIGURATION_BUILD_DIR = "$(BUILD_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/MJRefresh"; + IBSC_MODULE = MJRefresh; + INFOPLIST_FILE = "Target Support Files/MJRefresh/ResourceBundle-MJRefresh.Privacy-MJRefresh-Info.plist"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + PRODUCT_NAME = MJRefresh.Privacy; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + WRAPPER_EXTENSION = bundle; + }; + name = Debug; + }; + 16DD238F86190BFED9FB2F16A83B2A56 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 20B1DAD84F32D1AF296F0D63C5DEE9AB /* SDWebImage.debug.xcconfig */; + buildSettings = { + CODE_SIGNING_ALLOWED = NO; + CONFIGURATION_BUILD_DIR = "$(BUILD_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/SDWebImage"; + IBSC_MODULE = SDWebImage; + INFOPLIST_FILE = "Target Support Files/SDWebImage/ResourceBundle-SDWebImage-SDWebImage-Info.plist"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + PRODUCT_NAME = SDWebImage; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + WRAPPER_EXTENSION = bundle; + }; + name = Debug; + }; + 2D1085CA7BD144CABF012FC10C6C9120 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 4EF47C40D45E06BA89946B4C9F04A546 /* Masonry.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_MODULE_VERIFIER = NO; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_PREFIX_HEADER = "Target Support Files/Masonry/Masonry-prefix.pch"; + GENERATE_INFOPLIST_FILE = NO; + INFOPLIST_FILE = "Target Support Files/Masonry/Masonry-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/Masonry/Masonry.modulemap"; + PRODUCT_MODULE_NAME = Masonry; + PRODUCT_NAME = Masonry; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_INSTALL_OBJC_HEADER = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 4CF8CD0C5349DA6326EF3FCF43C53402 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 35BFA337F4E1FDE67C773A82CCDFD6DA /* Pods-keyBoard.debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_MODULE_VERIFIER = NO; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + INFOPLIST_FILE = "Target Support Files/Pods-keyBoard/Pods-keyBoard-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-keyBoard/Pods-keyBoard.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 51753BD6FE635BB9421BCA4C05F63C6A /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = DF80C56AF1D41887B8622FAC95138810 /* MJRefresh.release.xcconfig */; + buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_MODULE_VERIFIER = NO; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_PREFIX_HEADER = "Target Support Files/MJRefresh/MJRefresh-prefix.pch"; + GENERATE_INFOPLIST_FILE = NO; + INFOPLIST_FILE = "Target Support Files/MJRefresh/MJRefresh-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/MJRefresh/MJRefresh.modulemap"; + PRODUCT_MODULE_NAME = MJRefresh; + PRODUCT_NAME = MJRefresh; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_INSTALL_OBJC_HEADER = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 5B8933506DB0D0650A36E47F8AB90C24 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 3316E3BF456739AB7A0F0FD1920F5F6B /* MJExtension.debug.xcconfig */; + buildSettings = { + CODE_SIGNING_ALLOWED = NO; + CONFIGURATION_BUILD_DIR = "$(BUILD_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/MJExtension"; + IBSC_MODULE = MJExtension; + INFOPLIST_FILE = "Target Support Files/MJExtension/ResourceBundle-MJExtension-MJExtension-Info.plist"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + PRODUCT_NAME = MJExtension; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + WRAPPER_EXTENSION = bundle; + }; + name = Debug; + }; + 5EB0D7D4CF48681DA30DD58C2E33B044 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = A6E8FF241173D596A21D4D4B7D86A810 /* Pods-keyBoard.release.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_MODULE_VERIFIER = NO; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + INFOPLIST_FILE = "Target Support Files/Pods-keyBoard/Pods-keyBoard-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-keyBoard/Pods-keyBoard.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 614F7847ADAD2F1EEC9E48FAEC955108 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 74CC813EBCFDBA413D1E8F2AE302E41A /* MJRefresh.debug.xcconfig */; + buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_MODULE_VERIFIER = NO; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_PREFIX_HEADER = "Target Support Files/MJRefresh/MJRefresh-prefix.pch"; + GENERATE_INFOPLIST_FILE = NO; + INFOPLIST_FILE = "Target Support Files/MJRefresh/MJRefresh-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/MJRefresh/MJRefresh.modulemap"; + PRODUCT_MODULE_NAME = MJRefresh; + PRODUCT_NAME = MJRefresh; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_INSTALL_OBJC_HEADER = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 8DE5143C03248BB6CD542DE3963D6F3A /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_DEBUG=1", + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + STRIP_INSTALLED_PRODUCT = NO; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Debug; + }; + 8F0B92FB18A57B370BAEDBF212E77B0A /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 1D774D8146EBC82B4A77204A273761B8 /* Pods-CustomKeyboard.release.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_MODULE_VERIFIER = NO; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + INFOPLIST_FILE = "Target Support Files/Pods-CustomKeyboard/Pods-CustomKeyboard-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-CustomKeyboard/Pods-CustomKeyboard.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 91762687457A2879115FDE4E6963488E /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = DF80C56AF1D41887B8622FAC95138810 /* MJRefresh.release.xcconfig */; + buildSettings = { + CODE_SIGNING_ALLOWED = NO; + CONFIGURATION_BUILD_DIR = "$(BUILD_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/MJRefresh"; + IBSC_MODULE = MJRefresh; + INFOPLIST_FILE = "Target Support Files/MJRefresh/ResourceBundle-MJRefresh.Privacy-MJRefresh-Info.plist"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + PRODUCT_NAME = MJRefresh.Privacy; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + WRAPPER_EXTENSION = bundle; + }; + name = Release; + }; + 9E406C6AAF85E580207CD97B0044DEAB /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_RELEASE=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + STRIP_INSTALLED_PRODUCT = NO; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + SWIFT_VERSION = 5.0; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Release; + }; + 9E9FB1E032B56896F9380263D45A0F9A /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 4B22EE0B7D2C1D1066750C4AB84FDA27 /* MJExtension.release.xcconfig */; + buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_MODULE_VERIFIER = NO; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_PREFIX_HEADER = "Target Support Files/MJExtension/MJExtension-prefix.pch"; + GENERATE_INFOPLIST_FILE = NO; + INFOPLIST_FILE = "Target Support Files/MJExtension/MJExtension-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/MJExtension/MJExtension.modulemap"; + PRODUCT_MODULE_NAME = MJExtension; + PRODUCT_NAME = MJExtension; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_INSTALL_OBJC_HEADER = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 9F519E5162C0E51D10B7E999E2FD0125 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 25119C155F0BB240A5DDFB8155627C04 /* SDWebImage.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_MODULE_VERIFIER = NO; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_PREFIX_HEADER = "Target Support Files/SDWebImage/SDWebImage-prefix.pch"; + GENERATE_INFOPLIST_FILE = NO; + INFOPLIST_FILE = "Target Support Files/SDWebImage/SDWebImage-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/SDWebImage/SDWebImage.modulemap"; + PRODUCT_MODULE_NAME = SDWebImage; + PRODUCT_NAME = SDWebImage; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_INSTALL_OBJC_HEADER = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + B04295D726C1883ADA40A304483D7E33 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 20B1DAD84F32D1AF296F0D63C5DEE9AB /* SDWebImage.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_MODULE_VERIFIER = NO; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_PREFIX_HEADER = "Target Support Files/SDWebImage/SDWebImage-prefix.pch"; + GENERATE_INFOPLIST_FILE = NO; + INFOPLIST_FILE = "Target Support Files/SDWebImage/SDWebImage-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/SDWebImage/SDWebImage.modulemap"; + PRODUCT_MODULE_NAME = SDWebImage; + PRODUCT_NAME = SDWebImage; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_INSTALL_OBJC_HEADER = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + B26FBB655ABB114E4C0D589843814D6C /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 6134DA50CBB0F618C7502B9B4E23963F /* Bugly.release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + BDDCA6E1F27BB61FB8D92F4302765543 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 0D6215D1BCCE125B8DF73E38013CBBDC /* Pods-CustomKeyboard.debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_MODULE_VERIFIER = NO; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + INFOPLIST_FILE = "Target Support Files/Pods-CustomKeyboard/Pods-CustomKeyboard-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-CustomKeyboard/Pods-CustomKeyboard.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + CBAFED52B4B51F600FAF2141BA449F2E /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 4CD2E3B8C4EBAB8CE1F46D4D7B1B5CAA /* Bugly.debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + CEE7FEC0A1B23DE7053203A448EEB294 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 78744B8D1235EE30BFB429D8C13D63F4 /* AFNetworking.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_MODULE_VERIFIER = NO; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_PREFIX_HEADER = "Target Support Files/AFNetworking/AFNetworking-prefix.pch"; + GENERATE_INFOPLIST_FILE = NO; + INFOPLIST_FILE = "Target Support Files/AFNetworking/AFNetworking-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/AFNetworking/AFNetworking.modulemap"; + PRODUCT_MODULE_NAME = AFNetworking; + PRODUCT_NAME = AFNetworking; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_INSTALL_OBJC_HEADER = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + D0AB0AEF4014B926FCD853D3AE0A370A /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 396F4E7921EA26CDE8AAEADDD8CFBB49 /* Masonry.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_MODULE_VERIFIER = NO; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_PREFIX_HEADER = "Target Support Files/Masonry/Masonry-prefix.pch"; + GENERATE_INFOPLIST_FILE = NO; + INFOPLIST_FILE = "Target Support Files/Masonry/Masonry-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/Masonry/Masonry.modulemap"; + PRODUCT_MODULE_NAME = Masonry; + PRODUCT_NAME = Masonry; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_INSTALL_OBJC_HEADER = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + DA533AA9B577872DAFB44EF2CF26C49A /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 23D6F4D8D5B6512D7A50FF1054426C09 /* AFNetworking.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_MODULE_VERIFIER = NO; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_PREFIX_HEADER = "Target Support Files/AFNetworking/AFNetworking-prefix.pch"; + GENERATE_INFOPLIST_FILE = NO; + INFOPLIST_FILE = "Target Support Files/AFNetworking/AFNetworking-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/AFNetworking/AFNetworking.modulemap"; + PRODUCT_MODULE_NAME = AFNetworking; + PRODUCT_NAME = AFNetworking; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_INSTALL_OBJC_HEADER = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + E41C0991D6353467CA87E00582A5976C /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 25119C155F0BB240A5DDFB8155627C04 /* SDWebImage.release.xcconfig */; + buildSettings = { + CODE_SIGNING_ALLOWED = NO; + CONFIGURATION_BUILD_DIR = "$(BUILD_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/SDWebImage"; + IBSC_MODULE = SDWebImage; + INFOPLIST_FILE = "Target Support Files/SDWebImage/ResourceBundle-SDWebImage-SDWebImage-Info.plist"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + PRODUCT_NAME = SDWebImage; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + WRAPPER_EXTENSION = bundle; + }; + name = Release; + }; + EC66105EE15F9DC9B6F20F58FB67957D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 3316E3BF456739AB7A0F0FD1920F5F6B /* MJExtension.debug.xcconfig */; + buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_MODULE_VERIFIER = NO; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_PREFIX_HEADER = "Target Support Files/MJExtension/MJExtension-prefix.pch"; + GENERATE_INFOPLIST_FILE = NO; + INFOPLIST_FILE = "Target Support Files/MJExtension/MJExtension-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/MJExtension/MJExtension.modulemap"; + PRODUCT_MODULE_NAME = MJExtension; + PRODUCT_NAME = MJExtension; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_INSTALL_OBJC_HEADER = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 29BB59B7B51BC6194771995E3356CF70 /* Build configuration list for PBXNativeTarget "MJRefresh" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 614F7847ADAD2F1EEC9E48FAEC955108 /* Debug */, + 51753BD6FE635BB9421BCA4C05F63C6A /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 2F9E94B5F79E365095CB33D3D3FCA6A2 /* Build configuration list for PBXNativeTarget "SDWebImage" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + B04295D726C1883ADA40A304483D7E33 /* Debug */, + 9F519E5162C0E51D10B7E999E2FD0125 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 3A3BFFB46D4AE092AC96BD3D9D624546 /* Build configuration list for PBXNativeTarget "SDWebImage-SDWebImage" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 16DD238F86190BFED9FB2F16A83B2A56 /* Debug */, + E41C0991D6353467CA87E00582A5976C /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 4650649B39AEE2A0C6FEE8FF9B18E065 /* Build configuration list for PBXNativeTarget "MJExtension-MJExtension" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 5B8933506DB0D0650A36E47F8AB90C24 /* Debug */, + 03A5A25907B9F099CB1930F2C4AA0E3F /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 4821239608C13582E20E6DA73FD5F1F9 /* Build configuration list for PBXProject "Pods" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 8DE5143C03248BB6CD542DE3963D6F3A /* Debug */, + 9E406C6AAF85E580207CD97B0044DEAB /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 547AC2DDC5CDD1783E0827EEA7D453E1 /* Build configuration list for PBXNativeTarget "MJExtension" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + EC66105EE15F9DC9B6F20F58FB67957D /* Debug */, + 9E9FB1E032B56896F9380263D45A0F9A /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 68B32BA86F0CEE6E06F49B0F2C62CD73 /* Build configuration list for PBXNativeTarget "MJRefresh-MJRefresh.Privacy" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 0A6B03880AA76C2476846FABA9DAB99A /* Debug */, + 91762687457A2879115FDE4E6963488E /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 7CEB2E47380AD51987AA02ECD4DFBCD9 /* Build configuration list for PBXNativeTarget "AFNetworking" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + CEE7FEC0A1B23DE7053203A448EEB294 /* Debug */, + DA533AA9B577872DAFB44EF2CF26C49A /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 9CC7AA793D9397C15E010F8242EE1046 /* Build configuration list for PBXAggregateTarget "Bugly" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + CBAFED52B4B51F600FAF2141BA449F2E /* Debug */, + B26FBB655ABB114E4C0D589843814D6C /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + AAA1F8799DB68036C3BE983C05FAA2C7 /* Build configuration list for PBXNativeTarget "Masonry" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 2D1085CA7BD144CABF012FC10C6C9120 /* Debug */, + D0AB0AEF4014B926FCD853D3AE0A370A /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + DA39DBDB0F7D05D976CC7C6A67459F5F /* Build configuration list for PBXNativeTarget "Pods-CustomKeyboard" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + BDDCA6E1F27BB61FB8D92F4302765543 /* Debug */, + 8F0B92FB18A57B370BAEDBF212E77B0A /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + FCE3E8712CE5CB67BC702E493D7E2243 /* Build configuration list for PBXNativeTarget "Pods-keyBoard" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 4CF8CD0C5349DA6326EF3FCF43C53402 /* Debug */, + 5EB0D7D4CF48681DA30DD58C2E33B044 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = BFDFE7DC352907FC980B868725387E98 /* Project object */; +} diff --git a/Pods/Pods.xcodeproj/xcuserdata/mac.xcuserdatad/xcschemes/AFNetworking.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/mac.xcuserdatad/xcschemes/AFNetworking.xcscheme new file mode 100644 index 0000000..0a091cb --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/mac.xcuserdatad/xcschemes/AFNetworking.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/mac.xcuserdatad/xcschemes/Bugly.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/mac.xcuserdatad/xcschemes/Bugly.xcscheme new file mode 100644 index 0000000..50e8f13 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/mac.xcuserdatad/xcschemes/Bugly.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/mac.xcuserdatad/xcschemes/MJExtension-MJExtension.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/mac.xcuserdatad/xcschemes/MJExtension-MJExtension.xcscheme new file mode 100644 index 0000000..e9de14f --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/mac.xcuserdatad/xcschemes/MJExtension-MJExtension.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/mac.xcuserdatad/xcschemes/MJExtension.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/mac.xcuserdatad/xcschemes/MJExtension.xcscheme new file mode 100644 index 0000000..75fa5cf --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/mac.xcuserdatad/xcschemes/MJExtension.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/mac.xcuserdatad/xcschemes/MJRefresh-MJRefresh.Privacy.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/mac.xcuserdatad/xcschemes/MJRefresh-MJRefresh.Privacy.xcscheme new file mode 100644 index 0000000..dcdc097 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/mac.xcuserdatad/xcschemes/MJRefresh-MJRefresh.Privacy.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/mac.xcuserdatad/xcschemes/MJRefresh.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/mac.xcuserdatad/xcschemes/MJRefresh.xcscheme new file mode 100644 index 0000000..d7bb9d4 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/mac.xcuserdatad/xcschemes/MJRefresh.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/mac.xcuserdatad/xcschemes/Masonry.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/mac.xcuserdatad/xcschemes/Masonry.xcscheme new file mode 100644 index 0000000..bc45702 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/mac.xcuserdatad/xcschemes/Masonry.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/mac.xcuserdatad/xcschemes/Pods-CustomKeyboard.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/mac.xcuserdatad/xcschemes/Pods-CustomKeyboard.xcscheme new file mode 100644 index 0000000..53a3c91 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/mac.xcuserdatad/xcschemes/Pods-CustomKeyboard.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/mac.xcuserdatad/xcschemes/Pods-keyBoard.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/mac.xcuserdatad/xcschemes/Pods-keyBoard.xcscheme new file mode 100644 index 0000000..ceb60a4 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/mac.xcuserdatad/xcschemes/Pods-keyBoard.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/mac.xcuserdatad/xcschemes/SDWebImage-SDWebImage.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/mac.xcuserdatad/xcschemes/SDWebImage-SDWebImage.xcscheme new file mode 100644 index 0000000..ec2596b --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/mac.xcuserdatad/xcschemes/SDWebImage-SDWebImage.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/mac.xcuserdatad/xcschemes/SDWebImage.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/mac.xcuserdatad/xcschemes/SDWebImage.xcscheme new file mode 100644 index 0000000..a567bf3 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/mac.xcuserdatad/xcschemes/SDWebImage.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/SDWebImage/LICENSE b/Pods/SDWebImage/LICENSE new file mode 100644 index 0000000..2f5785d --- /dev/null +++ b/Pods/SDWebImage/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2009-2020 Olivier Poitrey rs@dailymotion.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. + diff --git a/Pods/SDWebImage/README.md b/Pods/SDWebImage/README.md new file mode 100644 index 0000000..302e054 --- /dev/null +++ b/Pods/SDWebImage/README.md @@ -0,0 +1,446 @@ +

+ +

+ + +[![Build Status](https://github.com/SDWebImage/SDWebImage/actions/workflows/CI.yml/badge.svg)](https://github.com/SDWebImage/SDWebImage/actions/workflows/CI.yml) +[![Pod Version](http://img.shields.io/cocoapods/v/SDWebImage.svg?style=flat)](http://cocoadocs.org/docsets/SDWebImage/) +[![Pod Platform](http://img.shields.io/cocoapods/p/SDWebImage.svg?style=flat)](http://cocoadocs.org/docsets/SDWebImage/) +[![Pod License](http://img.shields.io/cocoapods/l/SDWebImage.svg?style=flat)](https://www.apache.org/licenses/LICENSE-2.0.html) +[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-brightgreen.svg)](https://github.com/SDWebImage/SDWebImage) +[![SwiftPM compatible](https://img.shields.io/badge/SwiftPM-compatible-brightgreen.svg)](https://swift.org/package-manager/) +[![Mac Catalyst compatible](https://img.shields.io/badge/Catalyst-compatible-brightgreen.svg)](https://developer.apple.com/documentation/xcode/creating_a_mac_version_of_your_ipad_app/) +[![codecov](https://codecov.io/gh/SDWebImage/SDWebImage/branch/master/graph/badge.svg)](https://codecov.io/gh/SDWebImage/SDWebImage) + +This library provides an async image downloader with cache support. For convenience, we added categories for UI elements like `UIImageView`, `UIButton`, `MKAnnotationView`. + +> 💡NOTE: `SD` is the prefix for **Simple Design** (which is the team name in Daily Motion company from the author Olivier Poitrey) + +## Features + +- [x] Categories for `UIImageView`, `UIButton`, `MKAnnotationView` adding web image and cache management +- [x] An asynchronous image downloader +- [x] An asynchronous memory + disk image caching with automatic cache expiration handling +- [x] A background image decompression to avoid frame rate drop +- [x] [Progressive image loading](https://github.com/SDWebImage/SDWebImage/wiki/Advanced-Usage#progressive-animation) (including animated image, like GIF showing in Web browser) +- [x] [Thumbnail image decoding](https://github.com/SDWebImage/SDWebImage/wiki/Advanced-Usage#thumbnail-decoding-550) to save CPU && Memory for large images +- [x] [Extendable image coder](https://github.com/SDWebImage/SDWebImage/wiki/Advanced-Usage#custom-coder-420) to support massive image format, like WebP +- [x] [Full-stack solution for animated images](https://github.com/SDWebImage/SDWebImage/wiki/Advanced-Usage#animated-image-50) which keep a balance between CPU && Memory +- [x] [Customizable and composable transformations](https://github.com/SDWebImage/SDWebImage/wiki/Advanced-Usage#transformer-50) can be applied to the images right after download +- [x] [Customizable and multiple caches system](https://github.com/SDWebImage/SDWebImage/wiki/Advanced-Usage#custom-cache-50) +- [x] [Customizable and multiple loaders system](https://github.com/SDWebImage/SDWebImage/wiki/Advanced-Usage#custom-loader-50) to expand the capabilities, like [Photos Library](https://github.com/SDWebImage/SDWebImagePhotosPlugin) +- [x] [Image loading indicators](https://github.com/SDWebImage/SDWebImage/wiki/How-to-use#use-view-indicator-50) +- [x] [Image loading transition animation](https://github.com/SDWebImage/SDWebImage/wiki/Advanced-Usage#image-transition-430) +- [x] A guarantee that the same URL won't be downloaded several times +- [x] A guarantee that bogus URLs won't be retried again and again +- [x] A guarantee that main thread will never be blocked +- [x] Modern Objective-C and better Swift support +- [x] Performances! + +## For Apple visionOS + +From 5.19+, SDWebImage supports visionOS on all Package Managers (include CocoaPods/Carthage/SPM). Upgrade the related tools if you're facing issues. + +For 5.18+, SDWebImage can be compiled for visionOS platform. However, it's still in beta and may contains issues unlike the stable iOS UIKit support. Welcome to have a try and [report issue](https://github.com/SDWebImage/SDWebImage/issues). + +To build on visionOS, currently we only support the standard Xcode integration. + +See `Installation with Swift Package Manager` and `Manual Installation Guide` below. + +## Supported Image Formats + +- Image formats supported by Apple system (JPEG, PNG, TIFF, BMP, ...), including [GIF](https://github.com/SDWebImage/SDWebImage/wiki/Advanced-Usage#gif-coder)/[APNG](https://github.com/SDWebImage/SDWebImage/wiki/Advanced-Usage#apng-coder) animated image +- HEIC format from iOS 11/macOS 10.13, including animated HEIC from iOS 13/macOS 10.15 via [SDWebImageHEICCoder](https://github.com/SDWebImage/SDWebImage/wiki/Advanced-Usage#heic-coder). For lower firmware, use coder plugin [SDWebImageHEIFCoder](https://github.com/SDWebImage/SDWebImageHEIFCoder) +- WebP format from iOS 14/macOS 11.0 via [SDWebImageAWebPCoder](https://github.com/SDWebImage/SDWebImage/wiki/Advanced-Usage#awebp-coder). For lower firmware, use coder plugin [SDWebImageWebPCoder](https://github.com/SDWebImage/SDWebImageWebPCoder) +- JPEG-XL format from iOS 17/macOS 14.0 built-in. For lower firmware, use coder plugin [SDWebImageJPEGXLCoder](https://github.com/SDWebImage/SDWebImageJPEGXLCoder) +- Support extendable coder plugins for new image formats like BPG, AVIF. And vector format like PDF, SVG. See all the list in [Image coder plugin List](https://github.com/SDWebImage/SDWebImage/wiki/Coder-Plugin-List) + +> 💡NOTE: For new user + +SDWebImage use [Coder Plugin System](https://github.com/SDWebImage/SDWebImage/wiki/Coder-Plugin-List) to support both Apple's built-in and external image format. For static image we always use Apple's built-in as fallback, but not for animated image. Currently (updated to 5.19.x version) we only register traditional animated format like GIF/APNG by default, without the modern format like AWebP/HEICS/AVIF, even on the latest firmware. + +If you want these animated image format support, simply register by yourself with one-line code, see more in [WebP Coder](https://github.com/SDWebImage/SDWebImage/wiki/Advanced-Usage#awebp-coder) and [HEIC Coder](https://github.com/SDWebImage/SDWebImage/wiki/Advanced-Usage#heic-coder) + +In future we will change this behavior by always registering all Apple's built-in animated image format, to make it easy for new user to integrate. + +## Additional modules and Ecosystem + +In order to keep SDWebImage focused and limited to the core features, but also allow extensibility and custom behaviors, during the 5.0 refactoring we focused on modularizing the library. +As such, we have moved/built new modules to [SDWebImage org](https://github.com/SDWebImage). + +#### SwiftUI +[SwiftUI](https://developer.apple.com/xcode/swiftui/) is an innovative UI framework written in Swift to build user interfaces across all Apple platforms. + +We support SwiftUI by building a brand new framework called [SDWebImageSwiftUI](https://github.com/SDWebImage/SDWebImageSwiftUI), which is built on top of SDWebImage core functions (caching, loading and animation). + +The new framework introduce two View structs `WebImage` and `AnimatedImage` for SwiftUI world, `ImageIndicator` modifier for any View, `ImageManager` observable object for data source. Supports iOS 13+/macOS 10.15+/tvOS 13+/watchOS 6+ and Swift 5.1. Have a nice try and provide feedback! + +#### Coders for additional image formats +- [SDWebImageWebPCoder](https://github.com/SDWebImage/SDWebImageWebPCoder) - coder for WebP format. iOS 9+/macOS 10.11+. Based on [libwebp](https://chromium.googlesource.com/webm/libwebp) +- [SDWebImageHEIFCoder](https://github.com/SDWebImage/SDWebImageHEIFCoder) - coder for HEIF format, iOS 9+/macOS 10.11+ support. Based on [libheif](https://github.com/strukturag/libheif) +- [SDWebImageBPGCoder](https://github.com/SDWebImage/SDWebImageBPGCoder) - coder for BPG format. Based on [libbpg](https://github.com/mirrorer/libbpg) +- [SDWebImageFLIFCoder](https://github.com/SDWebImage/SDWebImageFLIFCoder) - coder for FLIF format. Based on [libflif](https://github.com/FLIF-hub/FLIF) +- [SDWebImageAVIFCoder](https://github.com/SDWebImage/SDWebImageAVIFCoder) - coder for AVIF (AV1-based) format. Based on [libavif](https://github.com/AOMediaCodec/libavif) +- [SDWebImagePDFCoder](https://github.com/SDWebImage/SDWebImagePDFCoder) - coder for PDF vector format. Using built-in frameworks +- [SDWebImageSVGCoder](https://github.com/SDWebImage/SDWebImageSVGCoder) - coder for SVG vector format. Using built-in frameworks +- [SDWebImageSVGNativeCoder](https://github.com/SDWebImage/SDWebImageSVGNativeCoder) - coder for SVG-Native vector format. Based on [svg-native](https://github.com/adobe/svg-native-viewer) +- [SDWebImageLottieCoder](https://github.com/SDWebImage/SDWebImageLottieCoder) - coder for Lottie animation format. Based on [rlottie](https://github.com/Samsung/rlottie) +- [SDWebImageJPEGXLCoder](https://github.com/SDWebImage/SDWebImageJPEGXLCoder) - coder for JPEG-XL format. iOS 9+/macOS 10.11+. Based on [libjxl](https://github.com/libjxl/libjxl) +- and more from community! + +#### Custom Caches +- [SDWebImageYYPlugin](https://github.com/SDWebImage/SDWebImageYYPlugin) - plugin to support caching images with [YYCache](https://github.com/ibireme/YYCache) +- [SDWebImagePINPlugin](https://github.com/SDWebImage/SDWebImagePINPlugin) - plugin to support caching images with [PINCache](https://github.com/pinterest/PINCache) + +#### Custom Loaders +- [SDWebImagePhotosPlugin](https://github.com/SDWebImage/SDWebImagePhotosPlugin) - plugin to support loading images from Photos (using `Photos.framework`) +- [SDWebImageLinkPlugin](https://github.com/SDWebImage/SDWebImageLinkPlugin) - plugin to support loading images from rich link url, as well as `LPLinkView` (using `LinkPresentation.framework`) + +#### Integration with 3rd party libraries +- [SDWebImageLottiePlugin](https://github.com/SDWebImage/SDWebImageLottiePlugin) - plugin to support [Lottie-iOS](https://github.com/airbnb/lottie-ios), vector animation rending with remote JSON files +- [SDWebImageSVGKitPlugin](https://github.com/SDWebImage/SDWebImageSVGKitPlugin) - plugin to support [SVGKit](https://github.com/SVGKit/SVGKit), SVG rendering using Core Animation, iOS 9+/macOS 10.11+ support +- [SDWebImageFLPlugin](https://github.com/SDWebImage/SDWebImageFLPlugin) - plugin to support [FLAnimatedImage](https://github.com/Flipboard/FLAnimatedImage) as the engine for animated GIFs +- [SDWebImageYYPlugin](https://github.com/SDWebImage/SDWebImageYYPlugin) - plugin to integrate [YYImage](https://github.com/ibireme/YYImage) & [YYCache](https://github.com/ibireme/YYCache) for image rendering & caching + +#### Community driven popular libraries +- [FirebaseUI](https://github.com/firebase/FirebaseUI-iOS) - Firebase Storage binding for query images, based on SDWebImage loader system +- [react-native-fast-image](https://github.com/DylanVann/react-native-fast-image) - React Native fast image component, based on SDWebImage Animated Image solution +- [flutter_image_compress](https://github.com/OpenFlutter/flutter_image_compress) - Flutter compresses image plugin, based on SDWebImage WebP coder plugin + +#### Make our lives easier +- [libwebp-Xcode](https://github.com/SDWebImage/libwebp-Xcode) - A wrapper for [libwebp](https://chromium.googlesource.com/webm/libwebp) + an Xcode project. +- [libheif-Xcode](https://github.com/SDWebImage/libheif-Xcode) - A wrapper for [libheif](https://github.com/strukturag/libheif) + an Xcode project. +- [libavif-Xcode](https://github.com/SDWebImage/libavif-Xcode) - A wrapper for [libavif](https://github.com/AOMediaCodec/libavif) + an Xcode project. +- and more third-party C/C++ image codec libraries with CocoaPods/Carthage/SwiftPM support. + +You can use those directly, or create similar components of your own, by using the customizable architecture of SDWebImage. + +## Requirements + +- iOS 9.0 or later +- tvOS 9.0 or later +- watchOS 2.0 or later +- macOS 10.11 or later (10.15 for Catalyst) +- visionOS 1.0 or later +- Xcode 15.0 or later + +#### Backwards compatibility + +- For iOS 8, macOS 10.10 or Xcode < 11, use [any 5.x version up to 5.9.5](https://github.com/SDWebImage/SDWebImage/releases/tag/5.9.5) +- For iOS 7, macOS 10.9 or Xcode < 8, use [any 4.x version up to 4.4.6](https://github.com/SDWebImage/SDWebImage/releases/tag/4.4.6) +- For macOS 10.8, use [any 4.x version up to 4.3.0](https://github.com/SDWebImage/SDWebImage/releases/tag/4.3.0) +- For iOS 5 and 6, use [any 3.x version up to 3.7.6](https://github.com/SDWebImage/SDWebImage/releases/tag/3.7.6) +- For iOS < 5.0, please use the last [2.0 version](https://github.com/SDWebImage/SDWebImage/tree/2.0-compat). + +## Getting Started + +- Read this Readme doc +- Read the [How to use section](https://github.com/SDWebImage/SDWebImage#how-to-use) +- Read the [Latest Documentation](https://sdwebimage.github.io/) and [CocoaDocs for old version](http://cocoadocs.org/docsets/SDWebImage/) +- Try the example by downloading the project from Github or even easier using CocoaPods try `pod try SDWebImage` +- Read the [Installation Guide](https://github.com/SDWebImage/SDWebImage/wiki/Installation-Guide) +- Read the [SDWebImage 5.0 Migration Guide](https://github.com/SDWebImage/SDWebImage/blob/master/Docs/SDWebImage-5.0-Migration-guide.md) to get an idea of the changes from 4.x to 5.x +- Read the [SDWebImage 4.0 Migration Guide](https://github.com/SDWebImage/SDWebImage/blob/master/Docs/SDWebImage-4.0-Migration-guide.md) to get an idea of the changes from 3.x to 4.x +- Read the [Common Problems](https://github.com/SDWebImage/SDWebImage/wiki/Common-Problems) to find the solution for common problems +- Go to the [Wiki Page](https://github.com/SDWebImage/SDWebImage/wiki) for more information such as [Advanced Usage](https://github.com/SDWebImage/SDWebImage/wiki/Advanced-Usage) + +## Who Uses It +- Find out [who uses SDWebImage](https://github.com/SDWebImage/SDWebImage/wiki/Who-Uses-SDWebImage) and add your app to the list. + +## Communication + +- If you **need help**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/sdwebimage). (Tag 'sdwebimage') +- If you'd like to **ask a general question**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/sdwebimage). +- If you **found a bug**, open an issue. +- If you **have a feature request**, open an issue. +- If you **need IRC channel**, use [Gitter](https://gitter.im/SDWebImage/community). + +## Contribution + +- If you **want to contribute**, read the [Contributing Guide](https://github.com/SDWebImage/SDWebImage/blob/master/.github/CONTRIBUTING.md) +- For **development contribution guide**, read the [How-To-Contribute](https://github.com/SDWebImage/SDWebImage/wiki/How-to-Contribute) +- For **understanding code architecture**, read the [Code Architecture Analysis](https://github.com/SDWebImage/SDWebImage/wiki/5.6-Code-Architecture-Analysis) + +## How To Use + +* Objective-C + +```objective-c +#import +... +[imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"] + placeholderImage:[UIImage imageNamed:@"placeholder.png"]]; +``` + +* Swift + +```swift +import SDWebImage + +imageView.sd_setImage(with: URL(string: "http://www.domain.com/path/to/image.jpg"), placeholderImage: UIImage(named: "placeholder.png")) +``` + +- For details about how to use the library and clear examples, see [The detailed How to use](https://github.com/SDWebImage/SDWebImage/blob/master/Docs/HowToUse.md) + +## Animated Images (GIF) support + +In 5.0, we introduced a brand new mechanism for supporting animated images. This includes animated image loading, rendering, decoding, and also supports customizations (for advanced users). + +This animated image solution is available for `iOS`/`tvOS`/`macOS`. The `SDAnimatedImage` is subclass of `UIImage/NSImage`, and `SDAnimatedImageView` is subclass of `UIImageView/NSImageView`, to make them compatible with the common frameworks APIs. + +The `SDAnimatedImageView` supports the familiar image loading category methods, works like drop-in replacement for `UIImageView/NSImageView`. + +Don't have `UIView` (like `WatchKit` or `CALayer`)? you can still use `SDAnimatedPlayer` the player engine for advanced playback and rendering. + +See [Animated Image](https://github.com/SDWebImage/SDWebImage/wiki/Advanced-Usage#animated-image-50) for more detailed information. + +* Objective-C + +```objective-c +SDAnimatedImageView *imageView = [SDAnimatedImageView new]; +SDAnimatedImage *animatedImage = [SDAnimatedImage imageNamed:@"image.gif"]; +imageView.image = animatedImage; +``` + +* Swift + +```swift +let imageView = SDAnimatedImageView() +let animatedImage = SDAnimatedImage(named: "image.gif") +imageView.image = animatedImage +``` + +#### FLAnimatedImage integration has its own dedicated repo +In order to clean up things and make our core project do less things, we decided that the `FLAnimatedImage` integration does not belong here. From 5.0, this will still be available, but under a dedicated repo [SDWebImageFLPlugin](https://github.com/SDWebImage/SDWebImageFLPlugin). + +## Installation + +There are 5 ways to use SDWebImage in your project: +- using CocoaPods +- using Carthage +- using Swift Package Manager +- download binary XCFramework +- manual install (build frameworks or embed Xcode Project) + +### Installation with CocoaPods + +[CocoaPods](http://cocoapods.org/) is a dependency manager for Objective-C, which automates and simplifies the process of using 3rd-party libraries in your projects. See the [Get Started](http://cocoapods.org/#get_started) section for more details. + +#### Podfile +``` +platform :ios, '8.0' +pod 'SDWebImage', '~> 5.0' +``` + +##### Swift and static framework + +Swift project previously had to use `use_frameworks!` to make all Pods into dynamic framework to let CocoaPods work. + +However, starting with `CocoaPods 1.5.0+` (with `Xcode 9+`), which supports to build both Objective-C && Swift code into static framework. You can use modular headers to use SDWebImage as static framework, without the need of `use_frameworks!`: + +``` +platform :ios, '8.0' +# Uncomment the next line when you want all Pods as static framework +# use_modular_headers! +pod 'SDWebImage', :modular_headers => true +``` + +See more on [CocoaPods 1.5.0 — Swift Static Libraries](http://blog.cocoapods.org/CocoaPods-1.5.0/) + +If not, you still need to add `use_frameworks!` to use SDWebImage as dynamic framework: + +``` +platform :ios, '8.0' +use_frameworks! +pod 'SDWebImage' +``` + +#### Subspecs + +There are 2 subspecs available now: `Core` and `MapKit` (this means you can install only some of the SDWebImage modules. By default, you get just `Core`, so if you need `MapKit`, you need to specify it). + +Podfile example: + +``` +pod 'SDWebImage/MapKit' +``` + +### Installation with Carthage + +[Carthage](https://github.com/Carthage/Carthage) is a lightweight dependency manager for Swift and Objective-C. It leverages CocoaTouch modules and is less invasive than CocoaPods. + +To install with carthage, follow the instruction on [Carthage](https://github.com/Carthage/Carthage) + +Carthage users can point to this repository and use whichever generated framework they'd like: SDWebImage, SDWebImageMapKit or both. + +Make the following entry in your Cartfile: `github "SDWebImage/SDWebImage"` +Then run `carthage update` +If this is your first time using Carthage in the project, you'll need to go through some additional steps as explained [over at Carthage](https://github.com/Carthage/Carthage#adding-frameworks-to-an-application). + +> 💡NOTE: At this time, Carthage does not provide a way to build only specific repository subcomponents (or equivalent of CocoaPods's subspecs). All components and their dependencies will be built with the above command. However, you don't need to copy frameworks you aren't using into your project. For instance, if you aren't using `SDWebImageMapKit`, feel free to delete that framework from the Carthage Build directory after `carthage update` completes. + +> 💡NOTE: [Apple requires SDWebImage contains signatures](https://developer.apple.com/support/third-party-SDK-requirements/). So, by default the `carthage build` binary framework does not do codesign, this will cause validation error. You can sign yourself with the Apple Developer Program identity, or using the binary framework: + +``` +binary "https://github.com/SDWebImage/SDWebImage/raw/master/SDWebImage.json" +``` + +### Installation with Swift Package Manager (Xcode 11+) + +[Swift Package Manager](https://swift.org/package-manager/) (SwiftPM) is a tool for managing the distribution of Swift code as well as C-family dependency. From Xcode 11, SwiftPM got natively integrated with Xcode. + +SDWebImage support SwiftPM from version 5.1.0. To use SwiftPM, you should use Xcode 11 to open your project. Click `File` -> `Swift Packages` -> `Add Package Dependency`, enter [SDWebImage repo's URL](https://github.com/SDWebImage/SDWebImage.git). Or you can login Xcode with your GitHub account and just type `SDWebImage` to search. + +After select the package, you can choose the dependency type (tagged version, branch or commit). Then Xcode will setup all the stuff for you. + +If you're a framework author and use SDWebImage as a dependency, update your `Package.swift` file: + +```swift +let package = Package( + // 5.1.0 ..< 6.0.0 + dependencies: [ + .package(url: "https://github.com/SDWebImage/SDWebImage.git", from: "5.1.0") + ], + // ... +) +``` + +### Download binary XCFramework + +From 5.19.2, SDWebImage provide the canonical official binary XCFramework on [GitHub release pages](https://github.com/SDWebImage/SDWebImage/releases). + ++ Download XCFramework + +You can choose to download `SDWebImage-dynamic.xcframework.zip` for dynamic linked one, or `SDWebImage-static.xcframework.zip` for static-linked one. + ++ Integrate to Xcode Project + +Drag the unzipped `.xcframework` into your Xcode Project's Framework tab. + ++ Verify signature of binary XCFramework + +From Xcode 15 Apple will verify the signature of binary XCFramework, to avoid supply chain attack. + +The fingerprint currently should be `FC 3B 10 13 86 34 4C 50 DB 70 2A 9A D1 01 6F B5 1A 3E CC 8B 9D A9 B7 AE 47 A0 48 D4 D0 63 39 83` + +The certificate is stored in the repo [here](https://github.com/SDWebImage/SDWebImage/blob/master/Certificate/SDWebImage%20Signing%20Certificate.cer) + +The public key is stored in the repo [here](https://github.com/SDWebImage/SDWebImage/blob/master/Certificate/SDWebImage%20Signing%20Certificate.pem) + +See more: [Verifying the origin of your XCFrameworks](https://developer.apple.com/documentation/Xcode/verifying-the-origin-of-your-xcframeworks) + + +### Manual Installation Guide + ++ Check your command line Xcode version + +``` +sudo xcode-select -s /path/to/Xcode.app +``` + +or + +``` +export DEVELOPER_DIR=/path/to/Xcode.app/Contents/Developer +``` + ++ Run the script to build frameworks + +``` +./Scripts/build-frameworks.sh +``` + ++ Run the script to merge XCFramework + +``` +./Scripts/create-xcframework.sh +``` + ++ Use your own certificate to sign XCFramework + +``` +// https://developer.apple.com/support/third-party-SDK-requirements/ +codesign --timestamp -v --sign "your own certificate" SDWebImage.xcframework +``` + +See more on wiki: [Manual install Guide](https://github.com/SDWebImage/SDWebImage/wiki/Installation-Guide#manual-installation-guide) + +### Import headers in your source files + +In the source files where you need to use the library, import the umbrella header file: + +```objective-c +#import +``` + +It's also recommend to use the module import syntax, available for CocoaPods(enable `modular_headers`)/Carthage/SwiftPM. + +```objecitivec +@import SDWebImage; +``` + +### Build Project + +At this point your workspace should build without error. If you are having problem, post to the Issue and the +community can help you solve it. + +## Data Collection Practices + +From Xcode 15, we provide the new `PrivacyInfo.xcprivacy` file for privacy details, see [Describing data use in privacy manifests](https://developer.apple.com/documentation/bundleresources/privacy_manifest_files/describing_data_use_in_privacy_manifests?language=objc) + +You can exports the privacy report after archive your App by integrate SDWebImage via SwiftPM/XCFramework or CocoaPods (`use_frameworks` set to true). + +For old version or if you're using static ar archive, as required by the [App privacy details on the App Store](https://developer.apple.com/app-store/app-privacy-details/), here's SDWebImage's list of [Data Collection Practices](https://sdwebimage.github.io/DataCollection/index.html). + + + +## Author +- [Olivier Poitrey](https://github.com/rs) + +## Collaborators +- [Konstantinos K.](https://github.com/mythodeia) +- [Bogdan Poplauschi](https://github.com/bpoplauschi) +- [Chester Liu](https://github.com/skyline75489) +- [DreamPiggy](https://github.com/dreampiggy) +- [Wu Zhong](https://github.com/zhongwuzw) + +## Credits + +Thank you to all the people who have already contributed to SDWebImage. + +[![Contributors](https://opencollective.com/SDWebImage/contributors.svg?width=890)](https://github.com/SDWebImage/SDWebImage/graphs/contributors) + +## Licenses + +All source code is licensed under the [MIT License](https://github.com/SDWebImage/SDWebImage/blob/master/LICENSE). + +## Architecture + +To learn about SDWebImage's architecture design for contribution, read [The Core of SDWebImage v5.6 Architecture](https://github.com/SDWebImage/SDWebImage/wiki/5.6-Code-Architecture-Analysis). Thanks @looseyi for the post and translation. + +#### High Level Diagram +

+ +

+ +#### Overall Class Diagram +

+ +

+ +#### Top Level API Diagram +

+ +

+ +#### Main Sequence Diagram +

+ +

+ +#### More detailed diagrams +- [Manager API Diagram](https://raw.githubusercontent.com/SDWebImage/SDWebImage/master/Docs/Diagrams/SDWebImageManagerClassDiagram.png) +- [Coders API Diagram](https://raw.githubusercontent.com/SDWebImage/SDWebImage/master/Docs/Diagrams/SDWebImageCodersClassDiagram.png) +- [Loader API Diagram](https://raw.githubusercontent.com/SDWebImage/SDWebImage/master/Docs/Diagrams/SDWebImageLoaderClassDiagram.png) +- [Cache API Diagram](https://raw.githubusercontent.com/SDWebImage/SDWebImage/master/Docs/Diagrams/SDWebImageCacheClassDiagram.png) + diff --git a/Pods/SDWebImage/SDWebImage/Core/NSButton+WebCache.h b/Pods/SDWebImage/SDWebImage/Core/NSButton+WebCache.h new file mode 100644 index 0000000..5b8035b --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/NSButton+WebCache.h @@ -0,0 +1,340 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +#if SD_MAC + +#import "SDWebImageManager.h" + +/** + * Integrates SDWebImage async downloading and caching of remote images with NSButton. + */ +@interface NSButton (WebCache) + +#pragma mark - Image + +/** + * Get the current image URL. + */ +@property (nonatomic, strong, readonly, nullable) NSURL *sd_currentImageURL; + +/** + * Set the button `image` with an `url`. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url NS_REFINED_FOR_SWIFT; + +/** + * Set the button `image` with an `url` and a placeholder. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @see sd_setImageWithURL:placeholderImage:options: + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder NS_REFINED_FOR_SWIFT; + +/** + * Set the button `image` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options NS_REFINED_FOR_SWIFT; + +/** + * Set the button `image` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context; + +/** + * Set the button `image` with an `url`. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the button `image` with an `url`, placeholder. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + completed:(nullable SDExternalCompletionBlock)completedBlock NS_REFINED_FOR_SWIFT; + +/** + * Set the button `image` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the button `image` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param progressBlock A block called while image is downloading + * @note the progress block is executed on a background queue + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the button `image` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + * @param progressBlock A block called while image is downloading + * @note the progress block is executed on a background queue + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock; + +#pragma mark - Alternate Image + +/** + * Get the current alternateImage URL. + */ +@property (nonatomic, strong, readonly, nullable) NSURL *sd_currentAlternateImageURL; + +/** + * Set the button `alternateImage` with an `url`. + * + * The download is asynchronous and cached. + * + * @param url The url for the alternateImage. + */ +- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url NS_REFINED_FOR_SWIFT; + +/** + * Set the button `alternateImage` with an `url` and a placeholder. + * + * The download is asynchronous and cached. + * + * @param url The url for the alternateImage. + * @param placeholder The alternateImage to be set initially, until the alternateImage request finishes. + * @see sd_setAlternateImageWithURL:placeholderImage:options: + */ +- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder NS_REFINED_FOR_SWIFT; + +/** + * Set the button `alternateImage` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the alternateImage. + * @param placeholder The alternateImage to be set initially, until the alternateImage request finishes. + * @param options The options to use when downloading the alternateImage. @see SDWebImageOptions for the possible values. + */ +- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options NS_REFINED_FOR_SWIFT; + +/** + * Set the button `alternateImage` with an `url`, placeholder, custom options and context. + * + * The download is asynchronous and cached. + * + * @param url The url for the alternateImage. + * @param placeholder The alternateImage to be set initially, until the alternateImage request finishes. + * @param options The options to use when downloading the alternateImage. @see SDWebImageOptions for the possible values. + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + */ +- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context; + +/** + * Set the button `alternateImage` with an `url`. + * + * The download is asynchronous and cached. + * + * @param url The url for the alternateImage. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the alternateImage parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the alternateImage was retrieved from the local cache or from the network. + * The fourth parameter is the original alternateImage url. + */ +- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the button `alternateImage` with an `url`, placeholder. + * + * The download is asynchronous and cached. + * + * @param url The url for the alternateImage. + * @param placeholder The alternateImage to be set initially, until the alternateImage request finishes. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the alternateImage parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the alternateImage was retrieved from the local cache or from the network. + * The fourth parameter is the original alternateImage url. + */ +- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + completed:(nullable SDExternalCompletionBlock)completedBlock NS_REFINED_FOR_SWIFT; + +/** + * Set the button `alternateImage` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the alternateImage. + * @param placeholder The alternateImage to be set initially, until the alternateImage request finishes. + * @param options The options to use when downloading the alternateImage. @see SDWebImageOptions for the possible values. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the alternateImage parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the alternateImage was retrieved from the local cache or from the network. + * The fourth parameter is the original alternateImage url. + */ +- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the button `alternateImage` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the alternateImage. + * @param placeholder The alternateImage to be set initially, until the alternateImage request finishes. + * @param options The options to use when downloading the alternateImage. @see SDWebImageOptions for the possible values. + * @param progressBlock A block called while alternateImage is downloading + * @note the progress block is executed on a background queue + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the alternateImage parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the alternateImage was retrieved from the local cache or from the network. + * The fourth parameter is the original alternateImage url. + */ +- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the button `alternateImage` with an `url`, placeholder, custom options and context. + * + * The download is asynchronous and cached. + * + * @param url The url for the alternateImage. + * @param placeholder The alternateImage to be set initially, until the alternateImage request finishes. + * @param options The options to use when downloading the alternateImage. @see SDWebImageOptions for the possible values. + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + * @param progressBlock A block called while alternateImage is downloading + * @note the progress block is executed on a background queue + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the alternateImage parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the alternateImage was retrieved from the local cache or from the network. + * The fourth parameter is the original alternateImage url. + */ +- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock; + +#pragma mark - Cancel + +/** + * Cancel the current image download + */ +- (void)sd_cancelCurrentImageLoad; + +/** + * Cancel the current alternateImage download + */ +- (void)sd_cancelCurrentAlternateImageLoad; + +@end + +#endif diff --git a/Pods/SDWebImage/SDWebImage/Core/NSButton+WebCache.m b/Pods/SDWebImage/SDWebImage/Core/NSButton+WebCache.m new file mode 100644 index 0000000..953baf1 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/NSButton+WebCache.m @@ -0,0 +1,162 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "NSButton+WebCache.h" + +#if SD_MAC + +#import "objc/runtime.h" +#import "UIView+WebCacheOperation.h" +#import "UIView+WebCacheState.h" +#import "UIView+WebCache.h" +#import "SDInternalMacros.h" + +@implementation NSButton (WebCache) + +#pragma mark - Image + +- (void)sd_setImageWithURL:(nullable NSURL *)url { + [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder { + [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options { + [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options context:(nullable SDWebImageContext *)context { + [self sd_setImageWithURL:url placeholderImage:placeholder options:options context:context progress:nil completed:nil]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:completedBlock]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:completedBlock]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:completedBlock]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options progress:(nullable SDImageLoaderProgressBlock)progressBlock completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setImageWithURL:url placeholderImage:placeholder options:options context:nil progress:progressBlock completed:completedBlock]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_internalSetImageWithURL:url + placeholderImage:placeholder + options:options + context:context + setImageBlock:nil + progress:progressBlock + completed:^(NSImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) { + if (completedBlock) { + completedBlock(image, error, cacheType, imageURL); + } + }]; +} + +#pragma mark - Alternate Image + +- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url { + [self sd_setAlternateImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil]; +} + +- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder { + [self sd_setAlternateImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil]; +} + +- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options { + [self sd_setAlternateImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil]; +} + +- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options context:(nullable SDWebImageContext *)context { + [self sd_setAlternateImageWithURL:url placeholderImage:placeholder options:options context:context progress:nil completed:nil]; +} + +- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setAlternateImageWithURL:url placeholderImage:nil options:0 progress:nil completed:completedBlock]; +} + +- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setAlternateImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:completedBlock]; +} + +- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setAlternateImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:completedBlock]; +} + +- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options progress:(nullable SDImageLoaderProgressBlock)progressBlock completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setAlternateImageWithURL:url placeholderImage:placeholder options:options context:nil progress:progressBlock completed:completedBlock]; +} + +- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock { + SDWebImageMutableContext *mutableContext; + if (context) { + mutableContext = [context mutableCopy]; + } else { + mutableContext = [NSMutableDictionary dictionary]; + } + mutableContext[SDWebImageContextSetImageOperationKey] = @keypath(self, alternateImage); + @weakify(self); + [self sd_internalSetImageWithURL:url + placeholderImage:placeholder + options:options + context:mutableContext + setImageBlock:^(NSImage * _Nullable image, NSData * _Nullable imageData, SDImageCacheType cacheType, NSURL * _Nullable imageURL) { + @strongify(self); + self.alternateImage = image; + } + progress:progressBlock + completed:^(NSImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) { + if (completedBlock) { + completedBlock(image, error, cacheType, imageURL); + } + }]; +} + +#pragma mark - Cancel + +- (void)sd_cancelCurrentImageLoad { + [self sd_cancelImageLoadOperationWithKey:nil]; +} + +- (void)sd_cancelCurrentAlternateImageLoad { + [self sd_cancelImageLoadOperationWithKey:@keypath(self, alternateImage)]; +} + +#pragma mark - State + +- (NSURL *)sd_currentImageURL { + return [self sd_imageLoadStateForKey:nil].url; +} + +#pragma mark - Alternate State + +- (NSURL *)sd_currentAlternateImageURL { + return [self sd_imageLoadStateForKey:@keypath(self, alternateImage)].url; +} + +@end + +#endif diff --git a/Pods/SDWebImage/SDWebImage/Core/NSData+ImageContentType.h b/Pods/SDWebImage/SDWebImage/Core/NSData+ImageContentType.h new file mode 100644 index 0000000..b9a6aa3 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/NSData+ImageContentType.h @@ -0,0 +1,63 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * (c) Fabrice Aneche + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" + +/** + You can use switch case like normal enum. It's also recommended to add a default case. You should not assume anything about the raw value. + For custom coder plugin, it can also extern the enum for supported format. See `SDImageCoder` for more detailed information. + */ +typedef NSInteger SDImageFormat NS_TYPED_EXTENSIBLE_ENUM; +static const SDImageFormat SDImageFormatUndefined = -1; +static const SDImageFormat SDImageFormatJPEG = 0; +static const SDImageFormat SDImageFormatPNG = 1; +static const SDImageFormat SDImageFormatGIF = 2; +static const SDImageFormat SDImageFormatTIFF = 3; +static const SDImageFormat SDImageFormatWebP = 4; +static const SDImageFormat SDImageFormatHEIC = 5; +static const SDImageFormat SDImageFormatHEIF = 6; +static const SDImageFormat SDImageFormatPDF = 7; +static const SDImageFormat SDImageFormatSVG = 8; +static const SDImageFormat SDImageFormatBMP = 9; +static const SDImageFormat SDImageFormatRAW = 10; + +/** + NSData category about the image content type and UTI. + */ +@interface NSData (ImageContentType) + +/** + * Return image format + * + * @param data the input image data + * + * @return the image format as `SDImageFormat` (enum) + */ ++ (SDImageFormat)sd_imageFormatForImageData:(nullable NSData *)data; + +/** + * Convert SDImageFormat to UTType + * + * @param format Format as SDImageFormat + * @return The UTType as CFStringRef + * @note For unknown format, `kSDUTTypeImage` abstract type will return + */ ++ (nonnull CFStringRef)sd_UTTypeFromImageFormat:(SDImageFormat)format CF_RETURNS_NOT_RETAINED NS_SWIFT_NAME(sd_UTType(from:)); + +/** + * Convert UTType to SDImageFormat + * + * @param uttype The UTType as CFStringRef + * @return The Format as SDImageFormat + * @note For unknown type, `SDImageFormatUndefined` will return + */ ++ (SDImageFormat)sd_imageFormatFromUTType:(nonnull CFStringRef)uttype; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/NSData+ImageContentType.m b/Pods/SDWebImage/SDWebImage/Core/NSData+ImageContentType.m new file mode 100644 index 0000000..c5f18cc --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/NSData+ImageContentType.m @@ -0,0 +1,167 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * (c) Fabrice Aneche + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "NSData+ImageContentType.h" +#if SD_MAC +#import +#else +#import +#endif +#import "SDImageIOAnimatedCoderInternal.h" + +#define kSVGTagEnd @"" + +@implementation NSData (ImageContentType) + ++ (SDImageFormat)sd_imageFormatForImageData:(nullable NSData *)data { + if (!data) { + return SDImageFormatUndefined; + } + + // File signatures table: http://www.garykessler.net/library/file_sigs.html + uint8_t c; + [data getBytes:&c length:1]; + switch (c) { + case 0xFF: + return SDImageFormatJPEG; + case 0x89: + return SDImageFormatPNG; + case 0x47: + return SDImageFormatGIF; + case 0x49: + case 0x4D: + return SDImageFormatTIFF; + case 0x42: + return SDImageFormatBMP; + case 0x52: { + if (data.length >= 12) { + //RIFF....WEBP + NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding]; + if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) { + return SDImageFormatWebP; + } + } + break; + } + case 0x00: { + if (data.length >= 12) { + //....ftypheic ....ftypheix ....ftyphevc ....ftyphevx + NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(4, 8)] encoding:NSASCIIStringEncoding]; + if ([testString isEqualToString:@"ftypheic"] + || [testString isEqualToString:@"ftypheix"] + || [testString isEqualToString:@"ftyphevc"] + || [testString isEqualToString:@"ftyphevx"]) { + return SDImageFormatHEIC; + } + //....ftypmif1 ....ftypmsf1 + if ([testString isEqualToString:@"ftypmif1"] || [testString isEqualToString:@"ftypmsf1"]) { + return SDImageFormatHEIF; + } + } + break; + } + case 0x25: { + if (data.length >= 4) { + //%PDF + NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(1, 3)] encoding:NSASCIIStringEncoding]; + if ([testString isEqualToString:@"PDF"]) { + return SDImageFormatPDF; + } + } + break; + } + case 0x3C: { + // Check end with SVG tag + if ([data rangeOfData:[kSVGTagEnd dataUsingEncoding:NSUTF8StringEncoding] options:NSDataSearchBackwards range: NSMakeRange(data.length - MIN(100, data.length), MIN(100, data.length))].location != NSNotFound) { + return SDImageFormatSVG; + } + break; + } + } + return SDImageFormatUndefined; +} + ++ (nonnull CFStringRef)sd_UTTypeFromImageFormat:(SDImageFormat)format { + CFStringRef UTType; + switch (format) { + case SDImageFormatJPEG: + UTType = kSDUTTypeJPEG; + break; + case SDImageFormatPNG: + UTType = kSDUTTypePNG; + break; + case SDImageFormatGIF: + UTType = kSDUTTypeGIF; + break; + case SDImageFormatTIFF: + UTType = kSDUTTypeTIFF; + break; + case SDImageFormatWebP: + UTType = kSDUTTypeWebP; + break; + case SDImageFormatHEIC: + UTType = kSDUTTypeHEIC; + break; + case SDImageFormatHEIF: + UTType = kSDUTTypeHEIF; + break; + case SDImageFormatPDF: + UTType = kSDUTTypePDF; + break; + case SDImageFormatSVG: + UTType = kSDUTTypeSVG; + break; + case SDImageFormatBMP: + UTType = kSDUTTypeBMP; + break; + case SDImageFormatRAW: + UTType = kSDUTTypeRAW; + break; + default: + // default is kUTTypeImage abstract type + UTType = kSDUTTypeImage; + break; + } + return UTType; +} + ++ (SDImageFormat)sd_imageFormatFromUTType:(CFStringRef)uttype { + if (!uttype) { + return SDImageFormatUndefined; + } + SDImageFormat imageFormat; + if (CFStringCompare(uttype, kSDUTTypeJPEG, 0) == kCFCompareEqualTo) { + imageFormat = SDImageFormatJPEG; + } else if (CFStringCompare(uttype, kSDUTTypePNG, 0) == kCFCompareEqualTo) { + imageFormat = SDImageFormatPNG; + } else if (CFStringCompare(uttype, kSDUTTypeGIF, 0) == kCFCompareEqualTo) { + imageFormat = SDImageFormatGIF; + } else if (CFStringCompare(uttype, kSDUTTypeTIFF, 0) == kCFCompareEqualTo) { + imageFormat = SDImageFormatTIFF; + } else if (CFStringCompare(uttype, kSDUTTypeWebP, 0) == kCFCompareEqualTo) { + imageFormat = SDImageFormatWebP; + } else if (CFStringCompare(uttype, kSDUTTypeHEIC, 0) == kCFCompareEqualTo) { + imageFormat = SDImageFormatHEIC; + } else if (CFStringCompare(uttype, kSDUTTypeHEIF, 0) == kCFCompareEqualTo) { + imageFormat = SDImageFormatHEIF; + } else if (CFStringCompare(uttype, kSDUTTypePDF, 0) == kCFCompareEqualTo) { + imageFormat = SDImageFormatPDF; + } else if (CFStringCompare(uttype, kSDUTTypeSVG, 0) == kCFCompareEqualTo) { + imageFormat = SDImageFormatSVG; + } else if (CFStringCompare(uttype, kSDUTTypeBMP, 0) == kCFCompareEqualTo) { + imageFormat = SDImageFormatBMP; + } else if (UTTypeConformsTo(uttype, kSDUTTypeRAW)) { + imageFormat = SDImageFormatRAW; + } else { + imageFormat = SDImageFormatUndefined; + } + return imageFormat; +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/NSImage+Compatibility.h b/Pods/SDWebImage/SDWebImage/Core/NSImage+Compatibility.h new file mode 100644 index 0000000..0a562cc --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/NSImage+Compatibility.h @@ -0,0 +1,67 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +#if SD_MAC + +/** + This category is provided to easily write cross-platform(AppKit/UIKit) code. For common usage, see `UIImage+Metadata.h`. + */ +@interface NSImage (Compatibility) + +/** +The underlying Core Graphics image object. This will actually use `CGImageForProposedRect` with the image size. + */ +@property (nonatomic, readonly, nullable) CGImageRef CGImage; +/** + The underlying Core Image data. This will actually use `bestRepresentationForRect` with the image size to find the `NSCIImageRep`. + */ +@property (nonatomic, readonly, nullable) CIImage *CIImage; +/** + The scale factor of the image. This wil actually use `bestRepresentationForRect` with image size and pixel size to calculate the scale factor. If failed, use the default value 1.0. Should be greater than or equal to 1.0. + */ +@property (nonatomic, readonly) CGFloat scale; + +// These are convenience methods to make AppKit's `NSImage` match UIKit's `UIImage` behavior. The scale factor should be greater than or equal to 1.0. + +/** + Returns an image object with the scale factor and orientation. The representation is created from the Core Graphics image object. + @note The difference between this and `initWithCGImage:size` is that `initWithCGImage:size` will actually create a `NSCGImageSnapshotRep` representation and always use `backingScaleFactor` as scale factor. So we should avoid it and use `NSBitmapImageRep` with `initWithCGImage:` instead. + @note The difference between this and UIKit's `UIImage` equivalent method is the way to process orientation. If the provided image orientation is not equal to Up orientation, this method will firstly rotate the CGImage to the correct orientation to work compatible with `NSImageView`. However, UIKit will not actually rotate CGImage and just store it as `imageOrientation` property. + + @param cgImage A Core Graphics image object + @param scale The image scale factor + @param orientation The orientation of the image data + @return The image object + */ +- (nonnull instancetype)initWithCGImage:(nonnull CGImageRef)cgImage scale:(CGFloat)scale orientation:(CGImagePropertyOrientation)orientation; + +/** + Initializes and returns an image object with the specified Core Image object. The representation is `NSCIImageRep`. + + @param ciImage A Core Image image object + @param scale The image scale factor + @param orientation The orientation of the image data + @return The image object + */ +- (nonnull instancetype)initWithCIImage:(nonnull CIImage *)ciImage scale:(CGFloat)scale orientation:(CGImagePropertyOrientation)orientation; + +/** + Returns an image object with the scale factor. The representation is created from the image data. + @note The difference between these this and `initWithData:` is that `initWithData:` will always use `backingScaleFactor` as scale factor. + + @param data The image data + @param scale The image scale factor + @return The image object + */ +- (nullable instancetype)initWithData:(nonnull NSData *)data scale:(CGFloat)scale; + +@end + +#endif diff --git a/Pods/SDWebImage/SDWebImage/Core/NSImage+Compatibility.m b/Pods/SDWebImage/SDWebImage/Core/NSImage+Compatibility.m new file mode 100644 index 0000000..ce67151 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/NSImage+Compatibility.m @@ -0,0 +1,120 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "NSImage+Compatibility.h" + +#if SD_MAC + +#import "SDImageCoderHelper.h" + +@implementation NSImage (Compatibility) + +- (nullable CGImageRef)CGImage { + NSRect imageRect = NSMakeRect(0, 0, self.size.width, self.size.height); + CGImageRef cgImage = [self CGImageForProposedRect:&imageRect context:nil hints:nil]; + return cgImage; +} + +- (nullable CIImage *)CIImage { + NSRect imageRect = NSMakeRect(0, 0, self.size.width, self.size.height); + NSImageRep *imageRep = [self bestRepresentationForRect:imageRect context:nil hints:nil]; + if (![imageRep isKindOfClass:NSCIImageRep.class]) { + return nil; + } + return ((NSCIImageRep *)imageRep).CIImage; +} + +- (CGFloat)scale { + CGFloat scale = 1; + NSRect imageRect = NSMakeRect(0, 0, self.size.width, self.size.height); + NSImageRep *imageRep = [self bestRepresentationForRect:imageRect context:nil hints:nil]; + CGFloat width = imageRep.size.width; + CGFloat height = imageRep.size.height; + CGFloat pixelWidth = (CGFloat)imageRep.pixelsWide; + CGFloat pixelHeight = (CGFloat)imageRep.pixelsHigh; + if (width > 0 && height > 0) { + CGFloat widthScale = pixelWidth / width; + CGFloat heightScale = pixelHeight / height; + if (widthScale == heightScale && widthScale >= 1) { + // Protect because there may be `NSImageRepMatchesDevice` (0) + scale = widthScale; + } + } + + return scale; +} + +- (instancetype)initWithCGImage:(nonnull CGImageRef)cgImage scale:(CGFloat)scale orientation:(CGImagePropertyOrientation)orientation { + NSBitmapImageRep *imageRep; + if (orientation != kCGImagePropertyOrientationUp) { + // AppKit design is different from UIKit. Where CGImage based image rep does not respect to any orientation. Only data based image rep which contains the EXIF metadata can automatically detect orientation. + // This should be nonnull, until the memory is exhausted cause `CGBitmapContextCreate` failed. + CGImageRef rotatedCGImage = [SDImageCoderHelper CGImageCreateDecoded:cgImage orientation:orientation]; + imageRep = [[NSBitmapImageRep alloc] initWithCGImage:rotatedCGImage]; + CGImageRelease(rotatedCGImage); + } else { + imageRep = [[NSBitmapImageRep alloc] initWithCGImage:cgImage]; + } + if (scale < 1) { + scale = 1; + } + CGFloat pixelWidth = imageRep.pixelsWide; + CGFloat pixelHeight = imageRep.pixelsHigh; + NSSize size = NSMakeSize(pixelWidth / scale, pixelHeight / scale); + self = [self initWithSize:size]; + if (self) { + imageRep.size = size; + [self addRepresentation:imageRep]; + } + return self; +} + +- (instancetype)initWithCIImage:(nonnull CIImage *)ciImage scale:(CGFloat)scale orientation:(CGImagePropertyOrientation)orientation { + NSCIImageRep *imageRep; + if (orientation != kCGImagePropertyOrientationUp) { + CIImage *rotatedCIImage = [ciImage imageByApplyingOrientation:orientation]; + imageRep = [[NSCIImageRep alloc] initWithCIImage:rotatedCIImage]; + } else { + imageRep = [[NSCIImageRep alloc] initWithCIImage:ciImage]; + } + if (scale < 1) { + scale = 1; + } + CGFloat pixelWidth = imageRep.pixelsWide; + CGFloat pixelHeight = imageRep.pixelsHigh; + NSSize size = NSMakeSize(pixelWidth / scale, pixelHeight / scale); + self = [self initWithSize:size]; + if (self) { + imageRep.size = size; + [self addRepresentation:imageRep]; + } + return self; +} + +- (instancetype)initWithData:(nonnull NSData *)data scale:(CGFloat)scale { + NSBitmapImageRep *imageRep = [[NSBitmapImageRep alloc] initWithData:data]; + if (!imageRep) { + return nil; + } + if (scale < 1) { + scale = 1; + } + CGFloat pixelWidth = imageRep.pixelsWide; + CGFloat pixelHeight = imageRep.pixelsHigh; + NSSize size = NSMakeSize(pixelWidth / scale, pixelHeight / scale); + self = [self initWithSize:size]; + if (self) { + imageRep.size = size; + [self addRepresentation:imageRep]; + } + return self; +} + +@end + +#endif diff --git a/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImage.h b/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImage.h new file mode 100644 index 0000000..b96027d --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImage.h @@ -0,0 +1,136 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" +#import "SDImageCoder.h" + + +/** + This is the protocol for SDAnimatedImage class only but not for SDAnimatedImageCoder. If you want to provide a custom animated image class with full advanced function, you can conform to this instead of the base protocol. + */ +@protocol SDAnimatedImage + +@required +/** + Initializes and returns the image object with the specified data, scale factor and possible animation decoding options. + @note We use this to create animated image instance for normal animation decoding. + + @param data The data object containing the image data. + @param scale The scale factor to assume when interpreting the image data. Applying 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. + @param options A dictionary containing any animation decoding options. + @return An initialized object + */ +- (nullable instancetype)initWithData:(nonnull NSData *)data scale:(CGFloat)scale options:(nullable SDImageCoderOptions *)options; + +/** + Initializes the image with an animated coder. You can use the coder to decode the image frame later. + @note We use this with animated coder which conforms to `SDProgressiveImageCoder` for progressive animation decoding. + + @param animatedCoder An animated coder which conform `SDAnimatedImageCoder` protocol + @param scale The scale factor to assume when interpreting the image data. Applying 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. + @return An initialized object + */ +- (nullable instancetype)initWithAnimatedCoder:(nonnull id)animatedCoder scale:(CGFloat)scale; + +@optional +// These methods are used for optional advanced feature, like image frame preloading. +/** + Pre-load all animated image frame into memory. Then later frame image request can directly return the frame for index without decoding. + This method may be called on background thread. + + @note If one image instance is shared by lots of imageViews, the CPU performance for large animated image will drop down because the request frame index will be random (not in order) and the decoder should take extra effort to keep it re-entrant. You can use this to reduce CPU usage if need. Attention this will consume more memory usage. + */ +- (void)preloadAllFrames; + +/** + Unload all animated image frame from memory if are already pre-loaded. Then later frame image request need decoding. You can use this to free up the memory usage if need. + */ +- (void)unloadAllFrames; + +/** + Returns a Boolean value indicating whether all animated image frames are already pre-loaded into memory. + */ +@property (nonatomic, assign, readonly, getter=isAllFramesLoaded) BOOL allFramesLoaded; + +/** + Return the animated image coder if the image is created with `initWithAnimatedCoder:scale:` method. + @note We use this with animated coder which conforms to `SDProgressiveImageCoder` for progressive animation decoding. + */ +@property (nonatomic, strong, readonly, nullable) id animatedCoder; + +@end + +/** + The image class which supports animating on `SDAnimatedImageView`. You can also use it on normal UIImageView/NSImageView. + */ +NS_SWIFT_NONISOLATED +@interface SDAnimatedImage : UIImage + +// This class override these methods from UIImage(NSImage), and it supports NSSecureCoding. +// You should use these methods to create a new animated image. Use other methods just call super instead. +// @note Before 5.19, these initializer will return nil for static image (when all candidate SDAnimatedImageCoder returns nil instance), like JPEG data. After 5.19, these initializer will retry for static image as well, so JPEG data will return non-nil instance. For vector image(PDF/SVG), always return nil. +// @note When the animated image frame count <= 1, all the `SDAnimatedImageProvider` protocol methods will return nil or 0 value, you'd better check the frame count before usage and keep fallback. ++ (nullable instancetype)imageNamed:(nonnull NSString *)name; // Cache in memory, no Asset Catalog support +#if __has_include() && !SD_WATCH ++ (nullable instancetype)imageNamed:(nonnull NSString *)name inBundle:(nullable NSBundle *)bundle compatibleWithTraitCollection:(nullable UITraitCollection *)traitCollection; // Cache in memory, no Asset Catalog support +#else ++ (nullable instancetype)imageNamed:(nonnull NSString *)name inBundle:(nullable NSBundle *)bundle; // Cache in memory, no Asset Catalog support +#endif ++ (nullable instancetype)imageWithContentsOfFile:(nonnull NSString *)path; ++ (nullable instancetype)imageWithData:(nonnull NSData *)data; ++ (nullable instancetype)imageWithData:(nonnull NSData *)data scale:(CGFloat)scale; +- (nullable instancetype)initWithContentsOfFile:(nonnull NSString *)path; +- (nullable instancetype)initWithData:(nonnull NSData *)data; +- (nullable instancetype)initWithData:(nonnull NSData *)data scale:(CGFloat)scale; + +/** + Current animated image format. + @note This format is only valid when `animatedImageData` not nil. + @note This actually just call `[NSData sd_imageFormatForImageData:self.animatedImageData]` + */ +@property (nonatomic, assign, readonly) SDImageFormat animatedImageFormat; + +/** + Current animated image data, you can use this to grab the compressed format data and create another animated image instance. + If this image instance is an animated image created by using animated image coder (which means using the API listed above or using `initWithAnimatedCoder:scale:`), this property is non-nil. + */ +@property (nonatomic, copy, readonly, nullable) NSData *animatedImageData; + +/** + The scale factor of the image. + + @note For UIKit, this just call super instead. + @note For AppKit, `NSImage` can contains multiple image representations with different scales. However, this class does not do that from the design. We process the scale like UIKit. This will actually be calculated from image size and pixel size. + */ +@property (nonatomic, readonly) CGFloat scale; + +// By default, animated image frames are returned by decoding just in time without keeping into memory. But you can choose to preload them into memory as well, See the description in `SDAnimatedImage` protocol. +// After preloaded, there is no huge difference on performance between this and UIImage's `animatedImageWithImages:duration:`. But UIImage's animation have some issues such like blanking and pausing during segue when using in `UIImageView`. It's recommend to use only if need. +/** + Pre-load all animated image frame into memory. Then later frame image request can directly return the frame for index without decoding. + This method may be called on background thread. + + @note If one image instance is shared by lots of imageViews, the CPU performance for large animated image will drop down because the request frame index will be random (not in order) and the decoder should take extra effort to keep it re-entrant. You can use this to reduce CPU usage if need. Attention this will consume more memory usage. + */ +- (void)preloadAllFrames; + +/** + Unload all animated image frame from memory if are already pre-loaded. Then later frame image request need decoding. You can use this to free up the memory usage if need. + */ +- (void)unloadAllFrames; +/** + Returns a Boolean value indicating whether all animated image frames are already pre-loaded into memory. + */ +@property (nonatomic, assign, readonly, getter=isAllFramesLoaded) BOOL allFramesLoaded; +/** + Return the animated image coder if the image is created with `initWithAnimatedCoder:scale:` method. + @note We use this with animated coder which conforms to `SDProgressiveImageCoder` for progressive animation decoding. + */ +@property (nonatomic, strong, readonly, nullable) id animatedCoder; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImage.m b/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImage.m new file mode 100644 index 0000000..4893e00 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImage.m @@ -0,0 +1,449 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDAnimatedImage.h" +#import "NSImage+Compatibility.h" +#import "SDImageCoder.h" +#import "SDImageCodersManager.h" +#import "SDImageFrame.h" +#import "UIImage+MemoryCacheCost.h" +#import "UIImage+Metadata.h" +#import "UIImage+MultiFormat.h" +#import "SDImageCoderHelper.h" +#import "SDImageAssetManager.h" +#import "objc/runtime.h" + +static CGFloat SDImageScaleFromPath(NSString *string) { + if (string.length == 0 || [string hasSuffix:@"/"]) return 1; + NSString *name = string.stringByDeletingPathExtension; + __block CGFloat scale = 1; + + NSRegularExpression *pattern = [NSRegularExpression regularExpressionWithPattern:@"@[0-9]+\\.?[0-9]*x$" options:NSRegularExpressionAnchorsMatchLines error:nil]; + [pattern enumerateMatchesInString:name options:kNilOptions range:NSMakeRange(0, name.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) { + scale = [string substringWithRange:NSMakeRange(result.range.location + 1, result.range.length - 2)].doubleValue; + }]; + + return scale; +} + +@interface SDAnimatedImage () + +@property (nonatomic, strong) id animatedCoder; +@property (atomic, copy) NSArray *loadedAnimatedImageFrames; // Mark as atomic to keep thread-safe +@property (nonatomic, assign, getter=isAllFramesLoaded) BOOL allFramesLoaded; + +@end + +@implementation SDAnimatedImage +@dynamic scale; // call super + +#pragma mark - UIImage override method ++ (instancetype)imageNamed:(NSString *)name { +#if __has_include() && !SD_WATCH + return [self imageNamed:name inBundle:nil compatibleWithTraitCollection:nil]; +#else + return [self imageNamed:name inBundle:nil]; +#endif +} + +#if __has_include() && !SD_WATCH ++ (instancetype)imageNamed:(NSString *)name inBundle:(NSBundle *)bundle compatibleWithTraitCollection:(UITraitCollection *)traitCollection { +#if SD_VISION + if (!traitCollection) { + traitCollection = UITraitCollection.currentTraitCollection; + } +#else + if (!traitCollection) { + traitCollection = UIScreen.mainScreen.traitCollection; + } +#endif + CGFloat scale = traitCollection.displayScale; + return [self imageNamed:name inBundle:bundle scale:scale]; +} +#else ++ (instancetype)imageNamed:(NSString *)name inBundle:(NSBundle *)bundle { + return [self imageNamed:name inBundle:bundle scale:0]; +} +#endif + +// 0 scale means automatically check ++ (instancetype)imageNamed:(NSString *)name inBundle:(NSBundle *)bundle scale:(CGFloat)scale { + if (!name) { + return nil; + } + if (!bundle) { + bundle = [NSBundle mainBundle]; + } + SDImageAssetManager *assetManager = [SDImageAssetManager sharedAssetManager]; + SDAnimatedImage *image = (SDAnimatedImage *)[assetManager imageForName:name]; + if ([image isKindOfClass:[SDAnimatedImage class]]) { + return image; + } + NSString *path = [assetManager getPathForName:name bundle:bundle preferredScale:&scale]; + if (!path) { + return image; + } + NSData *data = [NSData dataWithContentsOfFile:path]; + if (!data) { + return image; + } + image = [[self alloc] initWithData:data scale:scale]; + if (image) { + [assetManager storeImage:image forName:name]; + } + + return image; +} + ++ (instancetype)imageWithContentsOfFile:(NSString *)path { + return [[self alloc] initWithContentsOfFile:path]; +} + ++ (instancetype)imageWithData:(NSData *)data { + return [[self alloc] initWithData:data]; +} + ++ (instancetype)imageWithData:(NSData *)data scale:(CGFloat)scale { + return [[self alloc] initWithData:data scale:scale]; +} + +- (instancetype)initWithContentsOfFile:(NSString *)path { + NSData *data = [NSData dataWithContentsOfFile:path]; + if (!data) { + return nil; + } + CGFloat scale = SDImageScaleFromPath(path); + // path extension may be useful for coder like raw-image + NSString *fileExtensionHint = path.pathExtension; // without dot + if (fileExtensionHint.length == 0) { + // Ignore file extension which is empty + fileExtensionHint = nil; + } + SDImageCoderMutableOptions *mutableCoderOptions = [NSMutableDictionary dictionaryWithCapacity:1]; + mutableCoderOptions[SDImageCoderDecodeFileExtensionHint] = fileExtensionHint; + return [self initWithData:data scale:scale options:[mutableCoderOptions copy]]; +} + +- (instancetype)initWithData:(NSData *)data { + return [self initWithData:data scale:1]; +} + +- (instancetype)initWithData:(NSData *)data scale:(CGFloat)scale { + return [self initWithData:data scale:scale options:nil]; +} + +- (instancetype)initWithData:(NSData *)data scale:(CGFloat)scale options:(SDImageCoderOptions *)options { + if (!data || data.length == 0) { + return nil; + } + // Vector image does not supported, guard firstly + SDImageFormat format = [NSData sd_imageFormatForImageData:data]; + if (format == SDImageFormatSVG || format == SDImageFormatPDF) { + return nil; + } + + id animatedCoder = nil; + SDImageCoderMutableOptions *mutableCoderOptions; + if (options != nil) { + mutableCoderOptions = [NSMutableDictionary dictionaryWithDictionary:options]; + } else { + mutableCoderOptions = [NSMutableDictionary dictionaryWithCapacity:1]; + } + mutableCoderOptions[SDImageCoderDecodeScaleFactor] = @(scale); + options = [mutableCoderOptions copy]; + for (idcoder in [SDImageCodersManager sharedManager].coders.reverseObjectEnumerator) { + if ([coder conformsToProtocol:@protocol(SDAnimatedImageCoder)]) { + if ([coder canDecodeFromData:data]) { + animatedCoder = [[[coder class] alloc] initWithAnimatedImageData:data options:options]; + break; + } + } + } + if (animatedCoder) { + // Animated Image + return [self initWithAnimatedCoder:animatedCoder scale:scale]; + } else { + // Static Image (Before 5.19 this code path return nil) + UIImage *image = [[SDImageCodersManager sharedManager] decodedImageWithData:data options:options]; + if (!image) { + return nil; + } + // Vector image does not supported, guard secondly + if (image.sd_isVector) { + return nil; + } +#if SD_MAC + self = [super initWithCGImage:image.CGImage scale:MAX(scale, 1) orientation:kCGImagePropertyOrientationUp]; +#else + self = [super initWithCGImage:image.CGImage scale:MAX(scale, 1) orientation:image.imageOrientation]; +#endif + // Defines the associated object that holds the format for static images + super.sd_imageFormat = format; + return self; + } +} + +- (instancetype)initWithAnimatedCoder:(id)animatedCoder scale:(CGFloat)scale { + if (!animatedCoder) { + return nil; + } + UIImage *image = [animatedCoder animatedImageFrameAtIndex:0]; + if (!image) { + return nil; + } +#if SD_MAC + self = [super initWithCGImage:image.CGImage scale:MAX(scale, 1) orientation:kCGImagePropertyOrientationUp]; +#else + self = [super initWithCGImage:image.CGImage scale:MAX(scale, 1) orientation:image.imageOrientation]; +#endif + if (self) { + // Only keep the animated coder if frame count > 1, save RAM usage for non-animated image format (APNG/WebP) + if (animatedCoder.animatedImageFrameCount > 1) { + _animatedCoder = animatedCoder; + } + } + return self; +} + +- (SDImageFormat)animatedImageFormat { + return [NSData sd_imageFormatForImageData:self.animatedImageData]; +} + +#pragma mark - Preload +- (void)preloadAllFrames { + if (!_animatedCoder) { + return; + } + if (!self.isAllFramesLoaded) { + NSMutableArray *frames = [NSMutableArray arrayWithCapacity:self.animatedImageFrameCount]; + for (size_t i = 0; i < self.animatedImageFrameCount; i++) { + UIImage *image = [self animatedImageFrameAtIndex:i]; + NSTimeInterval duration = [self animatedImageDurationAtIndex:i]; + SDImageFrame *frame = [SDImageFrame frameWithImage:image duration:duration]; // through the image should be nonnull, used as nullable for `animatedImageFrameAtIndex:` + [frames addObject:frame]; + } + self.loadedAnimatedImageFrames = frames; + self.allFramesLoaded = YES; + } +} + +- (void)unloadAllFrames { + if (!_animatedCoder) { + return; + } + if (self.isAllFramesLoaded) { + self.loadedAnimatedImageFrames = nil; + self.allFramesLoaded = NO; + } +} + +#pragma mark - NSSecureCoding +- (instancetype)initWithCoder:(NSCoder *)aDecoder { + self = [super initWithCoder:aDecoder]; + if (self) { + NSData *animatedImageData = [aDecoder decodeObjectOfClass:[NSData class] forKey:NSStringFromSelector(@selector(animatedImageData))]; + if (!animatedImageData) { + return self; + } + CGFloat scale = self.scale; + id animatedCoder = nil; + for (idcoder in [SDImageCodersManager sharedManager].coders.reverseObjectEnumerator) { + if ([coder conformsToProtocol:@protocol(SDAnimatedImageCoder)]) { + if ([coder canDecodeFromData:animatedImageData]) { + animatedCoder = [[[coder class] alloc] initWithAnimatedImageData:animatedImageData options:@{SDImageCoderDecodeScaleFactor : @(scale)}]; + break; + } + } + } + if (!animatedCoder) { + return self; + } + if (animatedCoder.animatedImageFrameCount > 1) { + _animatedCoder = animatedCoder; + } + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder { + [super encodeWithCoder:aCoder]; + NSData *animatedImageData = self.animatedImageData; + if (animatedImageData) { + [aCoder encodeObject:animatedImageData forKey:NSStringFromSelector(@selector(animatedImageData))]; + } +} + ++ (BOOL)supportsSecureCoding { + return YES; +} + +#pragma mark - SDAnimatedImageProvider + +- (NSData *)animatedImageData { + return [self.animatedCoder animatedImageData]; +} + +- (NSUInteger)animatedImageLoopCount { + return [self.animatedCoder animatedImageLoopCount]; +} + +- (NSUInteger)animatedImageFrameCount { + return [self.animatedCoder animatedImageFrameCount]; +} + +- (UIImage *)animatedImageFrameAtIndex:(NSUInteger)index { + if (index >= self.animatedImageFrameCount) { + return nil; + } + if (self.isAllFramesLoaded) { + SDImageFrame *frame = [self.loadedAnimatedImageFrames objectAtIndex:index]; + return frame.image; + } + return [self.animatedCoder animatedImageFrameAtIndex:index]; +} + +- (NSTimeInterval)animatedImageDurationAtIndex:(NSUInteger)index { + if (index >= self.animatedImageFrameCount) { + return 0; + } + if (self.isAllFramesLoaded) { + SDImageFrame *frame = [self.loadedAnimatedImageFrames objectAtIndex:index]; + return frame.duration; + } + return [self.animatedCoder animatedImageDurationAtIndex:index]; +} + +@end + +@implementation SDAnimatedImage (MemoryCacheCost) + +- (NSUInteger)sd_memoryCost { + NSNumber *value = objc_getAssociatedObject(self, @selector(sd_memoryCost)); + if (value != nil) { + return value.unsignedIntegerValue; + } + + CGImageRef imageRef = self.CGImage; + if (!imageRef) { + return 0; + } + NSUInteger bytesPerFrame = CGImageGetBytesPerRow(imageRef) * CGImageGetHeight(imageRef); + NSUInteger frameCount = 1; + if (self.isAllFramesLoaded) { + frameCount = self.animatedImageFrameCount; + } + frameCount = frameCount > 0 ? frameCount : 1; + NSUInteger cost = bytesPerFrame * frameCount; + return cost; +} + +@end + +@implementation SDAnimatedImage (Metadata) + +- (BOOL)sd_isAnimated { + return self.animatedImageFrameCount > 1; +} + +- (NSUInteger)sd_imageLoopCount { + return self.animatedImageLoopCount; +} + +- (void)setSd_imageLoopCount:(NSUInteger)sd_imageLoopCount { + return; +} + +- (NSUInteger)sd_imageFrameCount { + NSUInteger frameCount = self.animatedImageFrameCount; + if (frameCount > 1) { + return frameCount; + } else { + return 1; + } +} + +- (SDImageFormat)sd_imageFormat { + NSData *animatedImageData = self.animatedImageData; + if (animatedImageData) { + return [NSData sd_imageFormatForImageData:animatedImageData]; + } else { + return [super sd_imageFormat]; + } +} + +- (BOOL)sd_isVector { + return NO; +} + +@end + +@implementation SDAnimatedImage (MultiFormat) + ++ (nullable UIImage *)sd_imageWithData:(nullable NSData *)data { + return [self sd_imageWithData:data scale:1]; +} + ++ (nullable UIImage *)sd_imageWithData:(nullable NSData *)data scale:(CGFloat)scale { + return [self sd_imageWithData:data scale:scale firstFrameOnly:NO]; +} + ++ (nullable UIImage *)sd_imageWithData:(nullable NSData *)data scale:(CGFloat)scale firstFrameOnly:(BOOL)firstFrameOnly { + if (!data) { + return nil; + } + return [[self alloc] initWithData:data scale:scale options:@{SDImageCoderDecodeFirstFrameOnly : @(firstFrameOnly)}]; +} + +- (nullable NSData *)sd_imageData { + NSData *imageData = self.animatedImageData; + if (imageData) { + return imageData; + } else { + return [self sd_imageDataAsFormat:self.animatedImageFormat]; + } +} + +- (nullable NSData *)sd_imageDataAsFormat:(SDImageFormat)imageFormat { + return [self sd_imageDataAsFormat:imageFormat compressionQuality:1]; +} + +- (nullable NSData *)sd_imageDataAsFormat:(SDImageFormat)imageFormat compressionQuality:(double)compressionQuality { + return [self sd_imageDataAsFormat:imageFormat compressionQuality:compressionQuality firstFrameOnly:NO]; +} + +- (nullable NSData *)sd_imageDataAsFormat:(SDImageFormat)imageFormat compressionQuality:(double)compressionQuality firstFrameOnly:(BOOL)firstFrameOnly { + // Protect when user input the imageFormat == self.animatedImageFormat && compressionQuality == 1 + // This should be treated as grabbing `self.animatedImageData` as well :) + NSData *imageData; + if (imageFormat == self.animatedImageFormat && compressionQuality == 1) { + imageData = self.animatedImageData; + } + if (imageData) return imageData; + + SDImageCoderOptions *options = @{SDImageCoderEncodeCompressionQuality : @(compressionQuality), SDImageCoderEncodeFirstFrameOnly : @(firstFrameOnly)}; + NSUInteger frameCount = self.animatedImageFrameCount; + if (frameCount <= 1) { + // Static image + imageData = [SDImageCodersManager.sharedManager encodedDataWithImage:self format:imageFormat options:options]; + } + if (imageData) return imageData; + + NSUInteger loopCount = self.animatedImageLoopCount; + // Keep animated image encoding, loop each frame. + NSMutableArray *frames = [NSMutableArray arrayWithCapacity:frameCount]; + for (size_t i = 0; i < frameCount; i++) { + UIImage *image = [self animatedImageFrameAtIndex:i]; + NSTimeInterval duration = [self animatedImageDurationAtIndex:i]; + SDImageFrame *frame = [SDImageFrame frameWithImage:image duration:duration]; + [frames addObject:frame]; + } + imageData = [SDImageCodersManager.sharedManager encodedDataWithFrames:frames loopCount:loopCount format:imageFormat options:options]; + return imageData; +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImagePlayer.h b/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImagePlayer.h new file mode 100644 index 0000000..77e041a --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImagePlayer.h @@ -0,0 +1,113 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import +#import "SDWebImageCompat.h" +#import "SDImageCoder.h" + +/// Animated image playback mode +typedef NS_ENUM(NSUInteger, SDAnimatedImagePlaybackMode) { + /** + * From first to last frame and stop or next loop. + */ + SDAnimatedImagePlaybackModeNormal = 0, + /** + * From last frame to first frame and stop or next loop. + */ + SDAnimatedImagePlaybackModeReverse, + /** + * From first frame to last frame and reverse again, like reciprocating. + */ + SDAnimatedImagePlaybackModeBounce, + /** + * From last frame to first frame and reverse again, like reversed reciprocating. + */ + SDAnimatedImagePlaybackModeReversedBounce, +}; + +/// A player to control the playback of animated image, which can be used to drive Animated ImageView or any rendering usage, like CALayer/WatchKit/SwiftUI rendering. +@interface SDAnimatedImagePlayer : NSObject + +/// Current playing frame image. This value is KVO Compliance. +@property (nonatomic, readonly, nullable) UIImage *currentFrame; + +/// Current frame index, zero based. This value is KVO Compliance. +@property (nonatomic, readonly) NSUInteger currentFrameIndex; + +/// Current loop count since its latest animating. This value is KVO Compliance. +@property (nonatomic, readonly) NSUInteger currentLoopCount; + +/// Total frame count for animated image rendering. Defaults is animated image's frame count. +/// @note For progressive animation, you can update this value when your provider receive more frames. +@property (nonatomic, assign) NSUInteger totalFrameCount; + +/// Total loop count for animated image rendering. Default is animated image's loop count. +@property (nonatomic, assign) NSUInteger totalLoopCount; + +/// The animation playback rate. Default is 1.0 +/// `1.0` means the normal speed. +/// `0.0` means stopping the animation. +/// `0.0-1.0` means the slow speed. +/// `> 1.0` means the fast speed. +/// `< 0.0` is not supported currently and stop animation. (may support reverse playback in the future) +@property (nonatomic, assign) double playbackRate; + +/// Asynchronous setup animation playback mode. Default mode is SDAnimatedImagePlaybackModeNormal. +@property (nonatomic, assign) SDAnimatedImagePlaybackMode playbackMode; + +/// Provide a max buffer size by bytes. This is used to adjust frame buffer count and can be useful when the decoding cost is expensive (such as Animated WebP software decoding). Default is 0. +/// `0` means automatically adjust by calculating current memory usage. +/// `1` means without any buffer cache, each of frames will be decoded and then be freed after rendering. (Lowest Memory and Highest CPU) +/// `NSUIntegerMax` means cache all the buffer. (Lowest CPU and Highest Memory) +@property (nonatomic, assign) NSUInteger maxBufferSize; + +/// You can specify a runloop mode to let it rendering. +/// Default is NSRunLoopCommonModes on multi-core device, NSDefaultRunLoopMode on single-core device +@property (nonatomic, copy, nonnull) NSRunLoopMode runLoopMode; + +/// Create a player with animated image provider. If the provider's `animatedImageFrameCount` is less than 1, returns nil. +/// The provider can be any protocol implementation, like `SDAnimatedImage`, `SDImageGIFCoder`, etc. +/// @note This provider can represent mutable content, like progressive animated loading. But you need to update the frame count by yourself +/// @param provider The animated provider +- (nullable instancetype)initWithProvider:(nonnull id)provider; + +/// Create a player with animated image provider. If the provider's `animatedImageFrameCount` is less than 1, returns nil. +/// The provider can be any protocol implementation, like `SDAnimatedImage` or `SDImageGIFCoder`, etc. +/// @note This provider can represent mutable content, like progressive animated loading. But you need to update the frame count by yourself +/// @param provider The animated provider ++ (nullable instancetype)playerWithProvider:(nonnull id)provider; + +/// The handler block when current frame and index changed. +@property (nonatomic, copy, nullable) void (^animationFrameHandler)(NSUInteger index, UIImage * _Nonnull frame); + +/// The handler block when one loop count finished. +@property (nonatomic, copy, nullable) void (^animationLoopHandler)(NSUInteger loopCount); + +/// Return the status whether animation is playing. +@property (nonatomic, readonly) BOOL isPlaying; + +/// Start the animation. Or resume the previously paused animation. +- (void)startPlaying; + +/// Pause the animation. Keep the current frame index and loop count. +- (void)pausePlaying; + +/// Stop the animation. Reset the current frame index and loop count. +- (void)stopPlaying; + +/// Seek to the desired frame index and loop count. +/// @note This can be used for advanced control like progressive loading, or skipping specify frames. +/// @param index The frame index +/// @param loopCount The loop count +- (void)seekToFrameAtIndex:(NSUInteger)index loopCount:(NSUInteger)loopCount; + +/// Clear the frame cache buffer. The frame cache buffer size can be controlled by `maxBufferSize`. +/// By default, when stop or pause the animation, the frame buffer is still kept to ready for the next restart +- (void)clearFrameBuffer; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImagePlayer.m b/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImagePlayer.m new file mode 100644 index 0000000..499be67 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImagePlayer.m @@ -0,0 +1,355 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import "SDAnimatedImagePlayer.h" +#import "NSImage+Compatibility.h" +#import "SDDisplayLink.h" +#import "SDDeviceHelper.h" +#import "SDImageFramePool.h" +#import "SDInternalMacros.h" + +@interface SDAnimatedImagePlayer () { + NSRunLoopMode _runLoopMode; +} + +@property (nonatomic, strong) SDImageFramePool *framePool; + +@property (nonatomic, strong, readwrite) UIImage *currentFrame; +@property (nonatomic, assign, readwrite) NSUInteger currentFrameIndex; +@property (nonatomic, assign, readwrite) NSUInteger currentLoopCount; +@property (nonatomic, strong) id animatedProvider; +@property (nonatomic, assign) NSUInteger currentFrameBytes; +@property (nonatomic, assign) NSTimeInterval currentTime; +@property (nonatomic, assign) BOOL bufferMiss; +@property (nonatomic, assign) BOOL needsDisplayWhenImageBecomesAvailable; +@property (nonatomic, assign) BOOL shouldReverse; +@property (nonatomic, strong) SDDisplayLink *displayLink; + +@end + +@implementation SDAnimatedImagePlayer + +- (instancetype)initWithProvider:(id)provider { + self = [super init]; + if (self) { + NSUInteger animatedImageFrameCount = provider.animatedImageFrameCount; + // Check the frame count + if (animatedImageFrameCount <= 1) { + return nil; + } + self.totalFrameCount = animatedImageFrameCount; + // Get the current frame and loop count. + self.totalLoopCount = provider.animatedImageLoopCount; + self.animatedProvider = provider; + self.playbackRate = 1.0; + self.framePool = [SDImageFramePool registerProvider:provider]; + } + return self; +} + ++ (instancetype)playerWithProvider:(id)provider { + SDAnimatedImagePlayer *player = [[SDAnimatedImagePlayer alloc] initWithProvider:provider]; + return player; +} + +- (void)dealloc { + // Dereference the frame pool, when zero the frame pool for provider will dealloc + [SDImageFramePool unregisterProvider:self.animatedProvider]; +} + +#pragma mark - Private + +- (SDDisplayLink *)displayLink { + if (!_displayLink) { + _displayLink = [SDDisplayLink displayLinkWithTarget:self selector:@selector(displayDidRefresh:)]; + [_displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:self.runLoopMode]; + [_displayLink stop]; + } + return _displayLink; +} + +- (void)setRunLoopMode:(NSRunLoopMode)runLoopMode { + if ([_runLoopMode isEqual:runLoopMode]) { + return; + } + if (_displayLink) { + if (_runLoopMode) { + [_displayLink removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:_runLoopMode]; + } + if (runLoopMode.length > 0) { + [_displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:runLoopMode]; + } + } + _runLoopMode = [runLoopMode copy]; +} + +- (NSRunLoopMode)runLoopMode { + if (!_runLoopMode) { + _runLoopMode = [[self class] defaultRunLoopMode]; + } + return _runLoopMode; +} + +#pragma mark - State Control + +- (void)setupCurrentFrame { + if (self.currentFrameIndex != 0) { + return; + } + if (self.playbackMode == SDAnimatedImagePlaybackModeReverse || + self.playbackMode == SDAnimatedImagePlaybackModeReversedBounce) { + self.currentFrameIndex = self.totalFrameCount - 1; + } + + if (!self.currentFrame && [self.animatedProvider isKindOfClass:[UIImage class]]) { + UIImage *image = (UIImage *)self.animatedProvider; + // Cache the poster image if available, but should not callback to avoid caller thread issues + #if SD_MAC + UIImage *posterFrame = [[NSImage alloc] initWithCGImage:image.CGImage scale:image.scale orientation:kCGImagePropertyOrientationUp]; + #else + UIImage *posterFrame = [[UIImage alloc] initWithCGImage:image.CGImage scale:image.scale orientation:image.imageOrientation]; + #endif + if (posterFrame) { + // Calculate max buffer size + [self calculateMaxBufferCountWithFrame:posterFrame]; + // HACK: The first frame should not check duration and immediately display + self.needsDisplayWhenImageBecomesAvailable = YES; + [self.framePool setFrame:posterFrame atIndex:self.currentFrameIndex]; + } + } + +} + +- (void)resetCurrentFrameStatus { + // These should not trigger KVO, user don't need to receive an `index == 0, image == nil` callback. + _currentFrame = nil; + _currentFrameIndex = 0; + _currentLoopCount = 0; + _currentTime = 0; + _bufferMiss = NO; + _needsDisplayWhenImageBecomesAvailable = NO; +} + +- (void)clearFrameBuffer { + [self.framePool removeAllFrames]; +} + +#pragma mark - Animation Control +- (void)startPlaying { + [self.displayLink start]; + // Setup frame + [self setupCurrentFrame]; +} + +- (void)stopPlaying { + // Using `_displayLink` here because when UIImageView dealloc, it may trigger `[self stopAnimating]`, we already release the display link in SDAnimatedImageView's dealloc method. + [_displayLink stop]; + // We need to reset the frame status, but not trigger any handle. This can ensure next time's playing status correct. + [self resetCurrentFrameStatus]; +} + +- (void)pausePlaying { + [_displayLink stop]; +} + +- (BOOL)isPlaying { + return _displayLink.isRunning; +} + +- (void)seekToFrameAtIndex:(NSUInteger)index loopCount:(NSUInteger)loopCount { + if (index >= self.totalFrameCount) { + return; + } + self.currentFrameIndex = index; + self.currentLoopCount = loopCount; + self.currentFrame = [self.animatedProvider animatedImageFrameAtIndex:index]; + [self handleFrameChange]; +} + +#pragma mark - Core Render +- (void)displayDidRefresh:(SDDisplayLink *)displayLink { + // If for some reason a wild call makes it through when we shouldn't be animating, bail. + // Early return! + if (!self.isPlaying) { + return; + } + + NSUInteger totalFrameCount = self.totalFrameCount; + if (totalFrameCount <= 1) { + // Total frame count less than 1, wrong configuration and stop animating + [self stopPlaying]; + return; + } + + NSTimeInterval playbackRate = self.playbackRate; + if (playbackRate <= 0) { + // Does not support <= 0 play rate + [self stopPlaying]; + return; + } + + // Calculate refresh duration + NSTimeInterval duration = self.displayLink.duration; + + NSUInteger currentFrameIndex = self.currentFrameIndex; + NSUInteger nextFrameIndex = (currentFrameIndex + 1) % totalFrameCount; + + if (self.playbackMode == SDAnimatedImagePlaybackModeReverse) { + nextFrameIndex = currentFrameIndex == 0 ? (totalFrameCount - 1) : (currentFrameIndex - 1) % totalFrameCount; + + } else if (self.playbackMode == SDAnimatedImagePlaybackModeBounce || + self.playbackMode == SDAnimatedImagePlaybackModeReversedBounce) { + if (currentFrameIndex == 0) { + self.shouldReverse = NO; + } else if (currentFrameIndex == totalFrameCount - 1) { + self.shouldReverse = YES; + } + nextFrameIndex = self.shouldReverse ? (currentFrameIndex - 1) : (currentFrameIndex + 1); + nextFrameIndex %= totalFrameCount; + } + + + // Check if we need to display new frame firstly + if (self.needsDisplayWhenImageBecomesAvailable) { + UIImage *currentFrame = [self.framePool frameAtIndex:currentFrameIndex]; + + // Update the current frame + if (currentFrame) { + // Update the current frame immediately + self.currentFrame = currentFrame; + [self handleFrameChange]; + + self.bufferMiss = NO; + self.needsDisplayWhenImageBecomesAvailable = NO; + } + else { + self.bufferMiss = YES; + } + } + + // Check if we have the frame buffer + if (!self.bufferMiss) { + // Then check if timestamp is reached + self.currentTime += duration; + NSTimeInterval currentDuration = [self.animatedProvider animatedImageDurationAtIndex:currentFrameIndex]; + currentDuration = currentDuration / playbackRate; + if (self.currentTime < currentDuration) { + // Current frame timestamp not reached, prefetch frame in advance. + [self prefetchFrameAtIndex:currentFrameIndex + nextIndex:nextFrameIndex]; + return; + } + + // Otherwise, we should be ready to display next frame + self.needsDisplayWhenImageBecomesAvailable = YES; + self.currentFrameIndex = nextFrameIndex; + self.currentTime -= currentDuration; + NSTimeInterval nextDuration = [self.animatedProvider animatedImageDurationAtIndex:nextFrameIndex]; + nextDuration = nextDuration / playbackRate; + if (self.currentTime > nextDuration) { + // Do not skip frame + self.currentTime = nextDuration; + } + + // Update the loop count when last frame rendered + if (nextFrameIndex == 0) { + // Update the loop count + self.currentLoopCount++; + [self handleLoopChange]; + + // if reached the max loop count, stop animating, 0 means loop indefinitely + NSUInteger maxLoopCount = self.totalLoopCount; + if (maxLoopCount != 0 && (self.currentLoopCount >= maxLoopCount)) { + [self stopPlaying]; + return; + } + } + } + + // Since we support handler, check animating state again + if (!self.isPlaying) { + return; + } + + [self prefetchFrameAtIndex:currentFrameIndex + nextIndex:nextFrameIndex]; +} + +// Check if we should prefetch next frame or current frame +// When buffer miss, means the decode speed is slower than render speed, we fetch current miss frame +// Or, most cases, the decode speed is faster than render speed, we fetch next frame +- (void)prefetchFrameAtIndex:(NSUInteger)currentIndex + nextIndex:(NSUInteger)nextIndex { + NSUInteger fetchFrameIndex = currentIndex; + UIImage *fetchFrame = nil; + if (!self.bufferMiss) { + fetchFrameIndex = nextIndex; + fetchFrame = [self.framePool frameAtIndex:nextIndex]; + } + BOOL bufferFull = NO; + if (self.framePool.currentFrameCount == self.totalFrameCount) { + bufferFull = YES; + } + if (!fetchFrame && !bufferFull) { + // Calculate max buffer size + [self calculateMaxBufferCountWithFrame:self.currentFrame]; + // Prefetch next frame + [self.framePool prefetchFrameAtIndex:fetchFrameIndex]; + } +} + +- (void)handleFrameChange { + if (self.animationFrameHandler) { + self.animationFrameHandler(self.currentFrameIndex, self.currentFrame); + } +} + +- (void)handleLoopChange { + if (self.animationLoopHandler) { + self.animationLoopHandler(self.currentLoopCount); + } +} + +#pragma mark - Util +- (void)calculateMaxBufferCountWithFrame:(nonnull UIImage *)frame { + NSUInteger bytes = self.currentFrameBytes; + if (bytes == 0) { + bytes = CGImageGetBytesPerRow(frame.CGImage) * CGImageGetHeight(frame.CGImage); + if (bytes == 0) { + bytes = 1024; + } else { + // Cache since most animated image each frame bytes is the same + self.currentFrameBytes = bytes; + } + } + + NSUInteger max = 0; + if (self.maxBufferSize > 0) { + max = self.maxBufferSize; + } else { + // Calculate based on current memory, these factors are by experience + NSUInteger total = [SDDeviceHelper totalMemory]; + NSUInteger free = [SDDeviceHelper freeMemory]; + max = MIN(total * 0.2, free * 0.6); + } + + NSUInteger maxBufferCount = (double)max / (double)bytes; + if (!maxBufferCount) { + // At least 1 frame + maxBufferCount = 1; + } + + self.framePool.maxBufferCount = maxBufferCount; +} + ++ (NSString *)defaultRunLoopMode { + // Key off `activeProcessorCount` (as opposed to `processorCount`) since the system could shut down cores in certain situations. + return [NSProcessInfo processInfo].activeProcessorCount > 1 ? NSRunLoopCommonModes : NSDefaultRunLoopMode; +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImageRep.h b/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImageRep.h new file mode 100644 index 0000000..dec2fbd --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImageRep.h @@ -0,0 +1,33 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +#if SD_MAC + +#import "NSData+ImageContentType.h" + +/** + A subclass of `NSBitmapImageRep` to fix that GIF duration issue because `NSBitmapImageRep` will reset `NSImageCurrentFrameDuration` by using `kCGImagePropertyGIFDelayTime` but not `kCGImagePropertyGIFUnclampedDelayTime`. + This also fix the GIF loop count issue, which will use the Netscape standard (See http://www6.uniovi.es/gifanim/gifabout.htm) to only place once when the `kCGImagePropertyGIFLoopCount` is nil. This is what modern browser's behavior. + Built in GIF coder use this instead of `NSBitmapImageRep` for better GIF rendering. If you do not want this, only enable `SDImageIOCoder`, which just call `NSImage` API and actually use `NSBitmapImageRep` for GIF image. + This also support APNG format using `SDImageAPNGCoder`. Which provide full alpha-channel support and the correct duration match the `kCGImagePropertyAPNGUnclampedDelayTime`. + */ +@interface SDAnimatedImageRep : NSBitmapImageRep + +/// Current animated image format. +/// @note This format is only valid when `animatedImageData` not nil +@property (nonatomic, assign, readonly) SDImageFormat animatedImageFormat; + +/// This allows to retrive the compressed data like GIF using `sd_imageData` on parent `NSImage`, without re-encoding (waste CPU and RAM) +/// @note This is typically nonnull when you create with `initWithData:`, even it's marked as weak, because ImageIO retain it +@property (nonatomic, readonly, nullable, weak) NSData *animatedImageData; + +@end + +#endif diff --git a/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImageRep.m b/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImageRep.m new file mode 100644 index 0000000..043f335 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImageRep.m @@ -0,0 +1,151 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDAnimatedImageRep.h" + +#if SD_MAC + +#import "SDImageIOAnimatedCoderInternal.h" +#import "SDImageGIFCoder.h" +#import "SDImageAPNGCoder.h" +#import "SDImageHEICCoder.h" +#import "SDImageAWebPCoder.h" + +@interface SDAnimatedImageRep () +/// This wrap the animated image frames for legacy animated image coder API (`encodedDataWithImage:`). +@property (nonatomic, readwrite, weak) NSArray *frames; +@property (nonatomic, assign, readwrite) SDImageFormat animatedImageFormat; +@end + +@implementation SDAnimatedImageRep { + CGImageSourceRef _imageSource; +} + +- (void)dealloc { + if (_imageSource) { + CFRelease(_imageSource); + _imageSource = NULL; + } +} + +- (instancetype)copyWithZone:(NSZone *)zone { + SDAnimatedImageRep *imageRep = [super copyWithZone:zone]; + // super will copy all ivars + if (imageRep->_imageSource) { + CFRetain(imageRep->_imageSource); + } + return imageRep; +} + +// `NSBitmapImageRep`'s `imageRepWithData:` is not designed initializer ++ (instancetype)imageRepWithData:(NSData *)data { + SDAnimatedImageRep *imageRep = [[SDAnimatedImageRep alloc] initWithData:data]; + return imageRep; +} + +// We should override init method for `NSBitmapImageRep` to do initialize about animated image format +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability" +- (instancetype)initWithData:(NSData *)data { + self = [super initWithData:data]; + if (self) { + CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef) data, NULL); + if (!imageSource) { + return self; + } + _imageSource = imageSource; + NSUInteger frameCount = CGImageSourceGetCount(imageSource); + if (frameCount <= 1) { + return self; + } + CFStringRef type = CGImageSourceGetType(imageSource); + if (!type) { + return self; + } + _animatedImageData = data; // CGImageSource will retain the data internally, no extra copy + SDImageFormat format = SDImageFormatUndefined; + if (CFStringCompare(type, kSDUTTypeGIF, 0) == kCFCompareEqualTo) { + // GIF + // Fix the `NSBitmapImageRep` GIF loop count calculation issue + // Which will use 0 when there are no loop count information metadata in GIF data + format = SDImageFormatGIF; + NSUInteger loopCount = [SDImageGIFCoder imageLoopCountWithSource:imageSource]; + [self setProperty:NSImageLoopCount withValue:@(loopCount)]; + } else if (CFStringCompare(type, kSDUTTypePNG, 0) == kCFCompareEqualTo) { + // APNG + // Do initialize about frame count, current frame/duration and loop count + format = SDImageFormatPNG; + [self setProperty:NSImageFrameCount withValue:@(frameCount)]; + [self setProperty:NSImageCurrentFrame withValue:@(0)]; + NSUInteger loopCount = [SDImageAPNGCoder imageLoopCountWithSource:imageSource]; + [self setProperty:NSImageLoopCount withValue:@(loopCount)]; + } else if (CFStringCompare(type, kSDUTTypeHEICS, 0) == kCFCompareEqualTo) { + // HEIC + // Do initialize about frame count, current frame/duration and loop count + format = SDImageFormatHEIC; + [self setProperty:NSImageFrameCount withValue:@(frameCount)]; + [self setProperty:NSImageCurrentFrame withValue:@(0)]; + NSUInteger loopCount = [SDImageHEICCoder imageLoopCountWithSource:imageSource]; + [self setProperty:NSImageLoopCount withValue:@(loopCount)]; + } else if (CFStringCompare(type, kSDUTTypeWebP, 0) == kCFCompareEqualTo) { + // WebP + // Do initialize about frame count, current frame/duration and loop count + format = SDImageFormatWebP; + [self setProperty:NSImageFrameCount withValue:@(frameCount)]; + [self setProperty:NSImageCurrentFrame withValue:@(0)]; + NSUInteger loopCount = [SDImageAWebPCoder imageLoopCountWithSource:imageSource]; + [self setProperty:NSImageLoopCount withValue:@(loopCount)]; + } else { + format = [NSData sd_imageFormatForImageData:data]; + } + _animatedImageFormat = format; + } + return self; +} + +// `NSBitmapImageRep` will use `kCGImagePropertyGIFDelayTime` whenever you call `setProperty:withValue:` with `NSImageCurrentFrame` to change the current frame. We override it and use the actual `kCGImagePropertyGIFUnclampedDelayTime` if need. +- (void)setProperty:(NSBitmapImageRepPropertyKey)property withValue:(id)value { + [super setProperty:property withValue:value]; + if ([property isEqualToString:NSImageCurrentFrame]) { + // Access the image source + CGImageSourceRef imageSource = _imageSource; + if (!imageSource) { + return; + } + // Check format type + CFStringRef type = CGImageSourceGetType(imageSource); + if (!type) { + return; + } + NSUInteger index = [value unsignedIntegerValue]; + NSTimeInterval frameDuration = 0; + if (CFStringCompare(type, kSDUTTypeGIF, 0) == kCFCompareEqualTo) { + // GIF + frameDuration = [SDImageGIFCoder frameDurationAtIndex:index source:imageSource]; + } else if (CFStringCompare(type, kSDUTTypePNG, 0) == kCFCompareEqualTo) { + // APNG + frameDuration = [SDImageAPNGCoder frameDurationAtIndex:index source:imageSource]; + } else if (CFStringCompare(type, kSDUTTypeHEICS, 0) == kCFCompareEqualTo) { + // HEIC + frameDuration = [SDImageHEICCoder frameDurationAtIndex:index source:imageSource]; + } else if (CFStringCompare(type, kSDUTTypeWebP, 0) == kCFCompareEqualTo) { + // WebP + frameDuration = [SDImageAWebPCoder frameDurationAtIndex:index source:imageSource]; + } + if (!frameDuration) { + return; + } + // Reset super frame duration with the actual frame duration + [super setProperty:NSImageCurrentFrameDuration withValue:@(frameDuration)]; + } +} +#pragma clang diagnostic pop + +@end + +#endif diff --git a/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImageView+WebCache.h b/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImageView+WebCache.h new file mode 100644 index 0000000..af46476 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImageView+WebCache.h @@ -0,0 +1,168 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDAnimatedImageView.h" + +#if SD_UIKIT || SD_MAC + +#import "SDWebImageManager.h" + +/** + Integrates SDWebImage async downloading and caching of remote images with SDAnimatedImageView. + */ +@interface SDAnimatedImageView (WebCache) + +/** + * Set the imageView `image` with an `url`. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url NS_REFINED_FOR_SWIFT; + +/** + * Set the imageView `image` with an `url` and a placeholder. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @see sd_setImageWithURL:placeholderImage:options: + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder NS_REFINED_FOR_SWIFT; + +/** + * Set the imageView `image` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options NS_REFINED_FOR_SWIFT; + +/** + * Set the imageView `image` with an `url`, placeholder, custom options and context. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context; + +/** + * Set the imageView `image` with an `url`. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the imageView `image` with an `url`, placeholder. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + completed:(nullable SDExternalCompletionBlock)completedBlock NS_REFINED_FOR_SWIFT; + +/** + * Set the imageView `image` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the imageView `image` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param progressBlock A block called while image is downloading + * @note the progress block is executed on a background queue + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the imageView `image` with an `url`, placeholder, custom options and context. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + * @param progressBlock A block called while image is downloading + * @note the progress block is executed on a background queue + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock; + +@end + +#endif diff --git a/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImageView+WebCache.m b/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImageView+WebCache.m new file mode 100644 index 0000000..beb56b2 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImageView+WebCache.m @@ -0,0 +1,79 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDAnimatedImageView+WebCache.h" + +#if SD_UIKIT || SD_MAC + +#import "UIView+WebCache.h" +#import "SDAnimatedImage.h" + +@implementation SDAnimatedImageView (WebCache) + +- (void)sd_setImageWithURL:(nullable NSURL *)url { + [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder { + [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options { + [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options context:(nullable SDWebImageContext *)context { + [self sd_setImageWithURL:url placeholderImage:placeholder options:options context:context progress:nil completed:nil]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:completedBlock]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:completedBlock]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:completedBlock]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options progress:(nullable SDImageLoaderProgressBlock)progressBlock completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setImageWithURL:url placeholderImage:placeholder options:options context:nil progress:progressBlock completed:completedBlock]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock { + Class animatedImageClass = [SDAnimatedImage class]; + SDWebImageMutableContext *mutableContext; + if (context) { + mutableContext = [context mutableCopy]; + } else { + mutableContext = [NSMutableDictionary dictionary]; + } + mutableContext[SDWebImageContextAnimatedImageClass] = animatedImageClass; + [self sd_internalSetImageWithURL:url + placeholderImage:placeholder + options:options + context:mutableContext + setImageBlock:nil + progress:progressBlock + completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) { + if (completedBlock) { + completedBlock(image, error, cacheType, imageURL); + } + }]; +} + +@end + +#endif diff --git a/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImageView.h b/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImageView.h new file mode 100644 index 0000000..aa31506 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImageView.h @@ -0,0 +1,125 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +#if SD_UIKIT || SD_MAC + +#import "SDAnimatedImage.h" +#import "SDAnimatedImagePlayer.h" +#import "SDImageTransformer.h" + +/** + A drop-in replacement for UIImageView/NSImageView, you can use this for animated image rendering. + Call `setImage:` with `UIImage(NSImage)` which conforms to `SDAnimatedImage` protocol will start animated image rendering. Call with normal UIImage(NSImage) will back to normal UIImageView(NSImageView) rendering + For UIKit: use `-startAnimating`, `-stopAnimating` to control animating. `isAnimating` to check animation state. + For AppKit: use `-setAnimates:` to control animating, `animates` to check animation state. This view is layer-backed. + */ +NS_SWIFT_UI_ACTOR +@interface SDAnimatedImageView : UIImageView +/** + The internal animation player. + This property is only used for advanced usage, like inspecting/debugging animation status, control progressive loading, complicated animation frame index control, etc. + @warning Pay attention if you directly update the player's property like `totalFrameCount`, `totalLoopCount`, the same property on `SDAnimatedImageView` may not get synced. + */ +@property (nonatomic, strong, readonly, nullable) SDAnimatedImagePlayer *player; + +/** + The transformer for each decoded animated image frame. + We supports post-transform on animated image frame from version 5.20. + When you configure the transformer on `SDAnimatedImageView` and animation is playing, the `transformedImageWithImage:forKey:` will be called just after the frame is decoded. (note: The `key` arg is always empty for backward-compatible and may be removed in the future) + + Example to tint the alpha animated image frame with a black color: + * @code + imageView.animationTransformer = [SDImageTintTransformer transformerWithColor:UIColor.blackColor]; + * @endcode + @note The `transformerKey` property is used to ensure the buffer cache available. So make sure it's correct value match the actual logic on transformer. Which means, for the `same frame index + same transformer key`, the transformed image should always be the same. + */ +@property (nonatomic, strong, nullable) id animationTransformer; + +/** + Current display frame image. This value is KVO Compliance. + */ +@property (nonatomic, strong, readonly, nullable) UIImage *currentFrame; +/** + Current frame index, zero based. This value is KVO Compliance. + */ +@property (nonatomic, assign, readonly) NSUInteger currentFrameIndex; +/** + Current loop count since its latest animating. This value is KVO Compliance. + */ +@property (nonatomic, assign, readonly) NSUInteger currentLoopCount; +/** + YES to choose `animationRepeatCount` property for animation loop count. No to use animated image's `animatedImageLoopCount` instead. + Default is NO. + */ +@property (nonatomic, assign) BOOL shouldCustomLoopCount; +/** + Total loop count for animated image rendering. Default is animated image's loop count. + If you need to set custom loop count, set `shouldCustomLoopCount` to YES and change this value. + This class override UIImageView's `animationRepeatCount` property on iOS, use this property as well. + */ +@property (nonatomic, assign) NSInteger animationRepeatCount; +/** + The animation playback rate. Default is 1.0. + `1.0` means the normal speed. + `0.0` means stopping the animation. + `0.0-1.0` means the slow speed. + `> 1.0` means the fast speed. + `< 0.0` is not supported currently and stop animation. (may support reverse playback in the future) + */ +@property (nonatomic, assign) double playbackRate; + +/// Asynchronous setup animation playback mode. Default mode is SDAnimatedImagePlaybackModeNormal. +@property (nonatomic, assign) SDAnimatedImagePlaybackMode playbackMode; + +/** + Provide a max buffer size by bytes. This is used to adjust frame buffer count and can be useful when the decoding cost is expensive (such as Animated WebP software decoding). Default is 0. + `0` means automatically adjust by calculating current memory usage. + `1` means without any buffer cache, each of frames will be decoded and then be freed after rendering. (Lowest Memory and Highest CPU) + `NSUIntegerMax` means cache all the buffer. (Lowest CPU and Highest Memory) + */ +@property (nonatomic, assign) NSUInteger maxBufferSize; +/** + Whehter or not to enable incremental image load for animated image. This is for the animated image which `sd_isIncremental` is YES (See `UIImage+Metadata.h`). If enable, animated image rendering will stop at the last frame available currently, and continue when another `setImage:` trigger, where the new animated image's `animatedImageData` should be updated from the previous one. If the `sd_isIncremental` is NO. The incremental image load stop. + @note If you are confused about this description, open Chrome browser to view some large GIF images with low network speed to see the animation behavior. + @note The best practice to use incremental load is using `initWithAnimatedCoder:scale:` in `SDAnimatedImage` with animated coder which conform to `SDProgressiveImageCoder` as well. Then call incremental update and incremental decode method to produce the image. + Default is YES. Set to NO to only render the static poster for incremental animated image. + */ +@property (nonatomic, assign) BOOL shouldIncrementalLoad; + +/** + Whether or not to clear the frame buffer cache when animation stopped. See `maxBufferSize` + This is useful when you want to limit the memory usage during frequently visibility changes (such as image view inside a list view, then push and pop) + Default is NO. + */ +@property (nonatomic, assign) BOOL clearBufferWhenStopped; + +/** + Whether or not to reset the current frame index when animation stopped. + For some of use case, you may want to reset the frame index to 0 when stop, but some other want to keep the current frame index. + Default is NO. + */ +@property (nonatomic, assign) BOOL resetFrameIndexWhenStopped; + +/** + If the image which conforms to `SDAnimatedImage` protocol has more than one frame, set this value to `YES` will automatically + play/stop the animation when the view become visible/invisible. + Default is YES. + */ +@property (nonatomic, assign) BOOL autoPlayAnimatedImage; + +/** + You can specify a runloop mode to let it rendering. + Default is NSRunLoopCommonModes on multi-core device, NSDefaultRunLoopMode on single-core device + @note This is useful for some cases, for example, always specify NSDefaultRunLoopMode, if you want to pause the animation when user scroll (for Mac user, drag the mouse or touchpad) + */ +@property (nonatomic, copy, nonnull) NSRunLoopMode runLoopMode; +@end + +#endif diff --git a/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImageView.m b/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImageView.m new file mode 100644 index 0000000..193652d --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImageView.m @@ -0,0 +1,622 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDAnimatedImageView.h" + +#if SD_UIKIT || SD_MAC + +#import "UIImage+Metadata.h" +#import "NSImage+Compatibility.h" +#import "SDInternalMacros.h" +#import "objc/runtime.h" + +// A wrapper to implements the transformer on animated image, like tint color +@interface SDAnimatedImageFrameProvider : NSObject +@property (nonatomic, strong) id provider; +@property (nonatomic, strong) id transformer; +@end + +@implementation SDAnimatedImageFrameProvider + +- (instancetype)initWithProvider:(id)provider transformer:(id)transformer { + self = [super init]; + if (self) { + _provider = provider; + _transformer = transformer; + } + return self; +} + +- (NSUInteger)hash { + NSUInteger prime = 31; + NSUInteger result = 1; + NSUInteger providerHash = self.provider.hash; + NSUInteger transformerHash = self.transformer.transformerKey.hash; + result = prime * result + providerHash; + result = prime * result + transformerHash; + return result; +} + +- (BOOL)isEqual:(id)object { + if (nil == object) { + return NO; + } + if (self == object) { + return YES; + } + if (![object isKindOfClass:[self class]]) { + return NO; + } + return self.provider == [object provider] + && [self.transformer.transformerKey isEqualToString:[object transformer].transformerKey]; +} + +- (NSData *)animatedImageData { + return self.provider.animatedImageData; +} + +- (NSUInteger)animatedImageFrameCount { + return self.provider.animatedImageFrameCount; +} + +- (NSUInteger)animatedImageLoopCount { + return self.provider.animatedImageLoopCount; +} + +- (NSTimeInterval)animatedImageDurationAtIndex:(NSUInteger)index { + return [self.provider animatedImageDurationAtIndex:index]; +} + +- (UIImage *)animatedImageFrameAtIndex:(NSUInteger)index { + UIImage *frame = [self.provider animatedImageFrameAtIndex:index]; + return [self.transformer transformedImageWithImage:frame forKey:@""]; +} + +@end + +@interface UIImageView () +@end + +@interface SDAnimatedImageView () { + BOOL _initFinished; // Extra flag to mark the `commonInit` is called + NSRunLoopMode _runLoopMode; + NSUInteger _maxBufferSize; + double _playbackRate; + SDAnimatedImagePlaybackMode _playbackMode; +} + +@property (nonatomic, strong, readwrite) SDAnimatedImagePlayer *player; +@property (nonatomic, strong, readwrite) UIImage *currentFrame; +@property (nonatomic, assign, readwrite) NSUInteger currentFrameIndex; +@property (nonatomic, assign, readwrite) NSUInteger currentLoopCount; +@property (nonatomic, assign) BOOL shouldAnimate; +@property (nonatomic, assign) BOOL isProgressive; +@property (nonatomic) CALayer *imageViewLayer; // The actual rendering layer. + +@end + +@implementation SDAnimatedImageView +#if SD_UIKIT +@dynamic animationRepeatCount; // we re-use this property from `UIImageView` super class on iOS. +#endif + +#pragma mark - Initializers + +#if SD_MAC ++ (instancetype)imageViewWithImage:(NSImage *)image +{ + NSRect frame = NSMakeRect(0, 0, image.size.width, image.size.height); + SDAnimatedImageView *imageView = [[SDAnimatedImageView alloc] initWithFrame:frame]; + [imageView setImage:image]; + return imageView; +} +#else +// -initWithImage: isn't documented as a designated initializer of UIImageView, but it actually seems to be. +// Using -initWithImage: doesn't call any of the other designated initializers. +- (instancetype)initWithImage:(UIImage *)image +{ + self = [super initWithImage:image]; + if (self) { + [self commonInit]; + } + return self; +} + +// -initWithImage:highlightedImage: also isn't documented as a designated initializer of UIImageView, but it doesn't call any other designated initializers. +- (instancetype)initWithImage:(UIImage *)image highlightedImage:(UIImage *)highlightedImage +{ + self = [super initWithImage:image highlightedImage:highlightedImage]; + if (self) { + [self commonInit]; + } + return self; +} +#endif + +- (instancetype)initWithFrame:(CGRect)frame +{ + self = [super initWithFrame:frame]; + if (self) { + [self commonInit]; + } + return self; +} + +- (instancetype)initWithCoder:(NSCoder *)aDecoder +{ + self = [super initWithCoder:aDecoder]; + if (self) { + [self commonInit]; + } + return self; +} + +- (void)commonInit +{ + // Pay attention that UIKit's `initWithImage:` will trigger a `setImage:` during initialization before this `commonInit`. + // So the properties which rely on this order, should using lazy-evaluation or do extra check in `setImage:`. + self.autoPlayAnimatedImage = YES; + self.shouldCustomLoopCount = NO; + self.shouldIncrementalLoad = YES; + self.playbackRate = 1.0; +#if SD_MAC + self.wantsLayer = YES; +#endif + // Mark commonInit finished + _initFinished = YES; +} + +#pragma mark - Accessors +#pragma mark Public + +- (void)setImage:(UIImage *)image +{ + if (self.image == image) { + return; + } + + // Check Progressive rendering + [self updateIsProgressiveWithImage:image]; + + if (!self.isProgressive) { + // Stop animating + self.player = nil; + self.currentFrame = nil; + self.currentFrameIndex = 0; + self.currentLoopCount = 0; + } + + // We need call super method to keep function. This will impliedly call `setNeedsDisplay`. But we have no way to avoid this when using animated image. So we call `setNeedsDisplay` again at the end. + super.image = image; + if ([image.class conformsToProtocol:@protocol(SDAnimatedImage)] && [(id)image animatedImageFrameCount] > 1) { + if (!self.player) { + id provider; + // Check progressive loading + if (self.isProgressive) { + provider = [(id)image animatedCoder]; + } else { + provider = (id)image; + } + // Create animated player + if (self.animationTransformer) { + // Check if post-transform animation available + provider = [[SDAnimatedImageFrameProvider alloc] initWithProvider:provider transformer:self.animationTransformer]; + self.player = [SDAnimatedImagePlayer playerWithProvider:provider]; + } else { + // Normal animation without post-transform + self.player = [SDAnimatedImagePlayer playerWithProvider:provider]; + } + } else { + // Update Frame Count + self.player.totalFrameCount = [(id)image animatedImageFrameCount]; + } + + if (!self.player) { + // animated player nil means the image format is not supported, or frame count <= 1 + return; + } + + // Custom Loop Count + if (self.shouldCustomLoopCount) { + self.player.totalLoopCount = self.animationRepeatCount; + } + + // RunLoop Mode + self.player.runLoopMode = self.runLoopMode; + + // Max Buffer Size + self.player.maxBufferSize = self.maxBufferSize; + + // Play Rate + self.player.playbackRate = self.playbackRate; + + // Play Mode + self.player.playbackMode = self.playbackMode; + + // Setup handler + @weakify(self); + self.player.animationFrameHandler = ^(NSUInteger index, UIImage * frame) { + @strongify(self); + self.currentFrameIndex = index; + self.currentFrame = frame; + [self.imageViewLayer setNeedsDisplay]; + }; + self.player.animationLoopHandler = ^(NSUInteger loopCount) { + @strongify(self); + // Progressive image reach the current last frame index. Keep the state and pause animating. Wait for later restart + if (self.isProgressive) { + NSUInteger lastFrameIndex = self.player.totalFrameCount - 1; + [self.player seekToFrameAtIndex:lastFrameIndex loopCount:0]; + [self.player pausePlaying]; + } else { + self.currentLoopCount = loopCount; + } + }; + + // Ensure disabled highlighting; it's not supported (see `-setHighlighted:`). + super.highlighted = NO; + + [self stopAnimating]; + [self checkPlay]; + } + [self.imageViewLayer setNeedsDisplay]; +} + +#pragma mark - Configuration + +- (void)setRunLoopMode:(NSRunLoopMode)runLoopMode +{ + _runLoopMode = [runLoopMode copy]; + self.player.runLoopMode = runLoopMode; +} + +- (NSRunLoopMode)runLoopMode +{ + if (!_runLoopMode) { + _runLoopMode = [[self class] defaultRunLoopMode]; + } + return _runLoopMode; +} + ++ (NSString *)defaultRunLoopMode { + // Key off `activeProcessorCount` (as opposed to `processorCount`) since the system could shut down cores in certain situations. + return [NSProcessInfo processInfo].activeProcessorCount > 1 ? NSRunLoopCommonModes : NSDefaultRunLoopMode; +} + +- (void)setMaxBufferSize:(NSUInteger)maxBufferSize +{ + _maxBufferSize = maxBufferSize; + self.player.maxBufferSize = maxBufferSize; +} + +- (NSUInteger)maxBufferSize { + return _maxBufferSize; // Defaults to 0 +} + +- (void)setPlaybackRate:(double)playbackRate +{ + _playbackRate = playbackRate; + self.player.playbackRate = playbackRate; +} + +- (double)playbackRate +{ + if (!_initFinished) { + return 1.0; // Defaults to 1.0 + } + return _playbackRate; +} + +- (void)setPlaybackMode:(SDAnimatedImagePlaybackMode)playbackMode { + _playbackMode = playbackMode; + self.player.playbackMode = playbackMode; +} + +- (SDAnimatedImagePlaybackMode)playbackMode { + if (!_initFinished) { + return SDAnimatedImagePlaybackModeNormal; // Default mode is normal + } + return _playbackMode; +} + + +- (BOOL)shouldIncrementalLoad +{ + if (!_initFinished) { + return YES; // Defaults to YES + } + return _initFinished; +} + +#pragma mark - UIView Method Overrides +#pragma mark Observing View-Related Changes + +#if SD_MAC +- (void)viewDidMoveToSuperview +#else +- (void)didMoveToSuperview +#endif +{ +#if SD_MAC + [super viewDidMoveToSuperview]; +#else + [super didMoveToSuperview]; +#endif + + [self checkPlay]; +} + +#if SD_MAC +- (void)viewDidMoveToWindow +#else +- (void)didMoveToWindow +#endif +{ +#if SD_MAC + [super viewDidMoveToWindow]; +#else + [super didMoveToWindow]; +#endif + + [self checkPlay]; +} + +#if SD_MAC +- (void)setAlphaValue:(CGFloat)alphaValue +#else +- (void)setAlpha:(CGFloat)alpha +#endif +{ +#if SD_MAC + [super setAlphaValue:alphaValue]; +#else + [super setAlpha:alpha]; +#endif + + [self checkPlay]; +} + +- (void)setHidden:(BOOL)hidden +{ + [super setHidden:hidden]; + + [self checkPlay]; +} + +#pragma mark - UIImageView Method Overrides +#pragma mark Image Data + +- (void)setAnimationRepeatCount:(NSInteger)animationRepeatCount +{ +#if SD_UIKIT + [super setAnimationRepeatCount:animationRepeatCount]; +#else + _animationRepeatCount = animationRepeatCount; +#endif + + if (self.shouldCustomLoopCount) { + self.player.totalLoopCount = animationRepeatCount; + } +} + +- (void)startAnimating +{ + if (self.player) { + [self updateShouldAnimate]; + if (self.shouldAnimate) { + [self.player startPlaying]; + } + } else { +#if SD_UIKIT + [super startAnimating]; +#else + [super setAnimates:YES]; +#endif + } +} + +- (void)stopAnimating +{ + if (self.player) { + if (self.resetFrameIndexWhenStopped) { + [self.player stopPlaying]; + } else { + [self.player pausePlaying]; + } + if (self.clearBufferWhenStopped) { + [self.player clearFrameBuffer]; + } + } else { +#if SD_UIKIT + [super stopAnimating]; +#else + [super setAnimates:NO]; +#endif + } +} + +#if SD_UIKIT +- (BOOL)isAnimating +{ + if (self.player) { + return self.player.isPlaying; + } else { + return [super isAnimating]; + } +} +#endif + +#if SD_MAC +- (BOOL)animates +{ + if (self.player) { + return self.player.isPlaying; + } else { + return [super animates]; + } +} + +- (void)setAnimates:(BOOL)animates +{ + if (animates) { + [self startAnimating]; + } else { + [self stopAnimating]; + } +} +#endif + +#pragma mark Highlighted Image Unsupport + +- (void)setHighlighted:(BOOL)highlighted +{ + // Highlighted image is unsupported for animated images, but implementing it breaks the image view when embedded in a UICollectionViewCell. + if (!self.player) { + [super setHighlighted:highlighted]; + } +} + + +#pragma mark - Private Methods +#pragma mark Animation + +/// Check if it should be played +- (void)checkPlay +{ + // Only handle for SDAnimatedImage, leave UIAnimatedImage or animationImages for super implementation control + if (self.player && self.autoPlayAnimatedImage) { + [self updateShouldAnimate]; + if (self.shouldAnimate) { + [self startAnimating]; + } else { + [self stopAnimating]; + } + } +} + +// Don't repeatedly check our window & superview in `-displayDidRefresh:` for performance reasons. +// Just update our cached value whenever the animated image or visibility (window, superview, hidden, alpha) is changed. +- (void)updateShouldAnimate +{ +#if SD_MAC + BOOL isVisible = self.window && self.superview && ![self isHidden] && self.alphaValue > 0.0; +#else + BOOL isVisible = self.window && self.superview && ![self isHidden] && self.alpha > 0.0; +#endif + self.shouldAnimate = self.player && isVisible; +} + +// Update progressive status only after `setImage:` call. +- (void)updateIsProgressiveWithImage:(UIImage *)image +{ + self.isProgressive = NO; + if (!self.shouldIncrementalLoad) { + // Early return + return; + } + // We must use `image.class conformsToProtocol:` instead of `image conformsToProtocol:` here + // Because UIKit on macOS, using internal hard-coded override method, which returns NO + id currentAnimatedCoder = [self progressiveAnimatedCoderForImage:image]; + if (currentAnimatedCoder) { + UIImage *previousImage = self.image; + if (!previousImage) { + // If current animated coder supports progressive, and no previous image to check, start progressive loading + self.isProgressive = YES; + } else { + id previousAnimatedCoder = [self progressiveAnimatedCoderForImage:previousImage]; + if (previousAnimatedCoder == currentAnimatedCoder) { + // If current animated coder is the same as previous, start progressive loading + self.isProgressive = YES; + } + } + } +} + +// Check if image can represent a `Progressive Animated Image` during loading +- (id)progressiveAnimatedCoderForImage:(UIImage *)image +{ + if ([image.class conformsToProtocol:@protocol(SDAnimatedImage)] && image.sd_isIncremental && [image respondsToSelector:@selector(animatedCoder)]) { + id animatedCoder = [(id)image animatedCoder]; + if ([animatedCoder respondsToSelector:@selector(initIncrementalWithOptions:)]) { + return (id)animatedCoder; + } + } + return nil; +} + + +#pragma mark Providing the Layer's Content +#pragma mark - CALayerDelegate + +- (void)displayLayer:(CALayer *)layer +{ + UIImage *currentFrame = self.currentFrame; + if (currentFrame) { + layer.contentsScale = currentFrame.scale; + layer.contents = (__bridge id)currentFrame.CGImage; + } else { + // If we have no animation frames, call super implementation. iOS 14+ UIImageView use this delegate method for rendering. + if ([UIImageView instancesRespondToSelector:@selector(displayLayer:)]) { + [super displayLayer:layer]; + } else { + // Fallback to implements the static image rendering by ourselves (like macOS or before iOS 14) + currentFrame = super.image; + layer.contentsScale = currentFrame.scale; + layer.contents = (__bridge id)currentFrame.CGImage; + } + } +} + +#if SD_UIKIT +- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection { + // See: #3635 + // From iOS 17, when UIImageView entering the background, it will receive the trait collection changes, and modify the CALayer.contents by `self.image.CGImage` + // However, For animated image, `self.image.CGImge != self.currentFrame.CGImage`, right ? + // So this cause the render issue, we need to reset the CALayer.contents again + [super traitCollectionDidChange:previousTraitCollection]; + [self.imageViewLayer setNeedsDisplay]; +} +#endif + +#if SD_MAC +// NSImageView use a subview. We need this subview's layer for actual rendering. +// Why using this design may because of properties like `imageAlignment` and `imageScaling`, which it's not available for UIImageView.contentMode (it's impossible to align left and keep aspect ratio at the same time) +- (NSView *)imageView { + NSImageView *imageView = objc_getAssociatedObject(self, SD_SEL_SPI(imageView)); + if (!imageView) { + // macOS 10.14 + imageView = objc_getAssociatedObject(self, SD_SEL_SPI(imageSubview)); + } + return imageView; +} + +// on macOS, it's the imageView subview's layer (we use layer-hosting view to let CALayerDelegate works) +- (CALayer *)imageViewLayer { + NSView *imageView = self.imageView; + if (!imageView) { + return nil; + } + if (!_imageViewLayer) { + _imageViewLayer = [CALayer new]; + _imageViewLayer.delegate = self; + imageView.layer = _imageViewLayer; + imageView.wantsLayer = YES; + } + return _imageViewLayer; +} +#else +// on iOS, it's the imageView itself's layer +- (CALayer *)imageViewLayer { + return self.layer; +} + +#endif + +@end + +#endif diff --git a/Pods/SDWebImage/SDWebImage/Core/SDCallbackQueue.h b/Pods/SDWebImage/SDWebImage/Core/SDCallbackQueue.h new file mode 100644 index 0000000..93c44f1 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDCallbackQueue.h @@ -0,0 +1,59 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + + +#import "SDWebImageCompat.h" + +/// SDCallbackPolicy controls how we execute the block on the queue, like whether to use `dispatch_async/dispatch_sync`, check if current queue match target queue, or just invoke without any context. +typedef NS_ENUM(NSUInteger, SDCallbackPolicy) { + /// When the current queue is equal to callback queue, sync/async will just invoke `block` directly without dispatch. Else it use `dispatch_async`/`dispatch_sync` to dispatch block on queue. This is useful for UIKit rendering to ensure all blocks executed in the same runloop + SDCallbackPolicySafeExecute = 0, + /// Follow async/sync using the correspond `dispatch_async`/`dispatch_sync` to dispatch block on queue + SDCallbackPolicyDispatch = 1, + /// Ignore any async/sync and just directly invoke `block` in current queue (without `dispatch_async`/`dispatch_sync`) + SDCallbackPolicyInvoke = 2, + /// Ensure callback in main thread. Do `dispatch_async` if the `NSThread.isMainTrhead == true` ; else do invoke `block`. Never use `dispatch_sync`, suitable for special UI-related code + SDCallbackPolicySafeAsyncMainThread = 3, +}; + +/// SDCallbackQueue is a wrapper used to control how the completionBlock should perform on queues, used by our `Cache`/`Manager`/`Loader`. +/// Useful when you call SDWebImage in non-main queue and want to avoid it callback into main queue, which may cause issue. +@interface SDCallbackQueue : NSObject + +/// The main queue. This is the default value, has the same effect when passing `nil` to `SDWebImageContextCallbackQueue` +/// The policy defaults to `SDCallbackPolicySafeAsyncMainThread` +@property (nonnull, class, readonly) SDCallbackQueue *mainQueue; + +/// The caller current queue. Using `dispatch_get_current_queue`. This is not a dynamic value and only keep the first call time queue. +/// The policy defaults to `SDCallbackPolicySafeExecute` +@property (nonnull, class, readonly) SDCallbackQueue *currentQueue; + +/// The global concurrent queue (user-initiated QoS). Using `dispatch_get_global_queue`. +/// The policy defaults to `SDCallbackPolicySafeExecute` +@property (nonnull, class, readonly) SDCallbackQueue *globalQueue; + +/// The current queue's callback policy. +@property (nonatomic, assign, readwrite) SDCallbackPolicy policy; + +- (nonnull instancetype)init NS_UNAVAILABLE; ++ (nonnull instancetype)new NS_UNAVAILABLE; +/// Create the callback queue with a GCD queue. The policy defaults to `SDCallbackPolicySafeExecute` +/// - Parameter queue: The GCD queue, should not be NULL +- (nonnull instancetype)initWithDispatchQueue:(nonnull dispatch_queue_t)queue NS_DESIGNATED_INITIALIZER; + +#pragma mark - Execution Entry + +/// Submits a block for execution and returns after that block finishes executing. +/// - Parameter block: The block that contains the work to perform. +- (void)sync:(nonnull dispatch_block_t)block API_DEPRECATED("No longer use, may cause deadlock when misused", macos(10.10, 10.10), ios(8.0, 8.0), tvos(9.0, 9.0), watchos(2.0, 2.0));; + +/// Schedules a block asynchronously for execution. +/// - Parameter block: The block that contains the work to perform. +- (void)async:(nonnull dispatch_block_t)block; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDCallbackQueue.m b/Pods/SDWebImage/SDWebImage/Core/SDCallbackQueue.m new file mode 100644 index 0000000..b4d0521 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDCallbackQueue.m @@ -0,0 +1,118 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + + +#import "SDCallbackQueue.h" + +@interface SDCallbackQueue () + +@property (nonatomic, strong, nonnull) dispatch_queue_t queue; + +@end + +static inline void SDSafeAsyncMainThread(dispatch_block_t _Nonnull block) { + if (NSThread.isMainThread) { + block(); + } else { + dispatch_async(dispatch_get_main_queue(), block); + } +} + +static void SDSafeExecute(dispatch_queue_t queue, dispatch_block_t _Nonnull block, BOOL async) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + dispatch_queue_t currentQueue = dispatch_get_current_queue(); +#pragma clang diagnostic pop + if (queue == currentQueue) { + block(); + return; + } + // Special handle for main queue only + if (NSThread.isMainThread && queue == dispatch_get_main_queue()) { + block(); + return; + } + if (async) { + dispatch_async(queue, block); + } else { + dispatch_sync(queue, block); + } +} + +@implementation SDCallbackQueue + +- (instancetype)initWithDispatchQueue:(dispatch_queue_t)queue { + self = [super init]; + if (self) { + NSCParameterAssert(queue); + _queue = queue; + _policy = SDCallbackPolicySafeExecute; + } + return self; +} + ++ (SDCallbackQueue *)mainQueue { + SDCallbackQueue *queue = [[SDCallbackQueue alloc] initWithDispatchQueue:dispatch_get_main_queue()]; + queue->_policy = SDCallbackPolicySafeAsyncMainThread; + return queue; +} + ++ (SDCallbackQueue *)currentQueue { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + SDCallbackQueue *queue = [[SDCallbackQueue alloc] initWithDispatchQueue:dispatch_get_current_queue()]; +#pragma clang diagnostic pop + return queue; +} + ++ (SDCallbackQueue *)globalQueue { + SDCallbackQueue *queue = [[SDCallbackQueue alloc] initWithDispatchQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)]; + return queue; +} + +- (void)sync:(nonnull dispatch_block_t)block { + switch (self.policy) { + case SDCallbackPolicySafeExecute: + SDSafeExecute(self.queue, block, NO); + break; + case SDCallbackPolicyDispatch: + dispatch_sync(self.queue, block); + break; + case SDCallbackPolicyInvoke: + block(); + break; + case SDCallbackPolicySafeAsyncMainThread: + SDSafeAsyncMainThread(block); + break; + default: + NSCAssert(NO, @"unexpected policy %tu", self.policy); + break; + } +} + +- (void)async:(nonnull dispatch_block_t)block { + switch (self.policy) { + case SDCallbackPolicySafeExecute: + SDSafeExecute(self.queue, block, YES); + break; + case SDCallbackPolicyDispatch: + dispatch_async(self.queue, block); + break; + case SDCallbackPolicyInvoke: + block(); + break; + case SDCallbackPolicySafeAsyncMainThread: + SDSafeAsyncMainThread(block); + break; + default: + NSCAssert(NO, @"unexpected policy %tu", self.policy); + break; + } +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDDiskCache.h b/Pods/SDWebImage/SDWebImage/Core/SDDiskCache.h new file mode 100644 index 0000000..fbfd4a9 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDDiskCache.h @@ -0,0 +1,146 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +@class SDImageCacheConfig; +/** + A protocol to allow custom disk cache used in SDImageCache. + */ +@protocol SDDiskCache + +// All of these method are called from the same global queue to avoid blocking on main queue and thread-safe problem. But it's also recommend to ensure thread-safe yourself using lock or other ways. +@required +/** + Create a new disk cache based on the specified path. You can check `maxDiskSize` and `maxDiskAge` used for disk cache. + + @param cachePath Full path of a directory in which the cache will write data. + Once initialized you should not read and write to this directory. + @param config The cache config to be used to create the cache. + + @return A new cache object, or nil if an error occurs. + */ +- (nullable instancetype)initWithCachePath:(nonnull NSString *)cachePath config:(nonnull SDImageCacheConfig *)config; + +/** + Returns a boolean value that indicates whether a given key is in cache. + This method may blocks the calling thread until file read finished. + + @param key A string identifying the data. If nil, just return NO. + @return Whether the key is in cache. + */ +- (BOOL)containsDataForKey:(nonnull NSString *)key; + +/** + Returns the data associated with a given key. + This method may blocks the calling thread until file read finished. + + @param key A string identifying the data. If nil, just return nil. + @return The value associated with key, or nil if no value is associated with key. + */ +- (nullable NSData *)dataForKey:(nonnull NSString *)key; + +/** + Sets the value of the specified key in the cache. + This method may blocks the calling thread until file write finished. + + @param data The data to be stored in the cache. + @param key The key with which to associate the value. If nil, this method has no effect. + */ +- (void)setData:(nullable NSData *)data forKey:(nonnull NSString *)key; + +/** + Returns the extended data associated with a given key. + This method may blocks the calling thread until file read finished. + + @param key A string identifying the data. If nil, just return nil. + @return The value associated with key, or nil if no value is associated with key. + */ +- (nullable NSData *)extendedDataForKey:(nonnull NSString *)key; + +/** + Set extended data with a given key. + + @discussion You can set any extended data to exist cache key. Without override the exist disk file data. + on UNIX, the common way for this is to use the Extended file attributes (xattr) + + @param extendedData The extended data (pass nil to remove). + @param key The key with which to associate the value. If nil, this method has no effect. +*/ +- (void)setExtendedData:(nullable NSData *)extendedData forKey:(nonnull NSString *)key; + +/** + Removes the value of the specified key in the cache. + This method may blocks the calling thread until file delete finished. + + @param key The key identifying the value to be removed. If nil, this method has no effect. + */ +- (void)removeDataForKey:(nonnull NSString *)key; + +/** + Empties the cache. + This method may blocks the calling thread until file delete finished. + */ +- (void)removeAllData; + +/** + Removes the expired data from the cache. You can choose the data to remove base on `ageLimit`, `countLimit` and `sizeLimit` options. + */ +- (void)removeExpiredData; + +/** + The cache path for key + + @param key A string identifying the value + @return The cache path for key. Or nil if the key can not associate to a path + */ +- (nullable NSString *)cachePathForKey:(nonnull NSString *)key; + +/** + Returns the number of data in this cache. + This method may blocks the calling thread until file read finished. + + @return The total data count. + */ +- (NSUInteger)totalCount; + +/** + Returns the total size (in bytes) of data in this cache. + This method may blocks the calling thread until file read finished. + + @return The total data size in bytes. + */ +- (NSUInteger)totalSize; + +@end + +/** + The built-in disk cache. + */ +@interface SDDiskCache : NSObject +/** + Cache Config object - storing all kind of settings. + */ +@property (nonatomic, strong, readonly, nonnull) SDImageCacheConfig *config; + +- (nonnull instancetype)init NS_UNAVAILABLE; ++ (nonnull instancetype)new NS_UNAVAILABLE; + +/** + Move the cache directory from old location to new location, the old location will be removed after finish. + If the old location does not exist, does nothing. + If the new location does not exist, only do a movement of directory. + If the new location does exist, will move and merge the files from old location. + If the new location does exist, but is not a directory, will remove it and do a movement of directory. + + @param srcPath old location of cache directory + @param dstPath new location of cache directory + */ +- (void)moveCacheDirectoryFromPath:(nonnull NSString *)srcPath toPath:(nonnull NSString *)dstPath; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDDiskCache.m b/Pods/SDWebImage/SDWebImage/Core/SDDiskCache.m new file mode 100644 index 0000000..938b844 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDDiskCache.m @@ -0,0 +1,390 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDDiskCache.h" +#import "SDImageCacheConfig.h" +#import "SDFileAttributeHelper.h" +#import + +static NSString * const SDDiskCacheExtendedAttributeName = @"com.hackemist.SDDiskCache"; + +@interface SDDiskCache () + +@property (nonatomic, copy) NSString *diskCachePath; +@property (nonatomic, strong, nonnull) NSFileManager *fileManager; + +@end + +@implementation SDDiskCache + +- (instancetype)init { + NSAssert(NO, @"Use `initWithCachePath:` with the disk cache path"); + return nil; +} + +#pragma mark - SDcachePathForKeyDiskCache Protocol +- (instancetype)initWithCachePath:(NSString *)cachePath config:(nonnull SDImageCacheConfig *)config { + if (self = [super init]) { + _diskCachePath = cachePath; + _config = config; + [self commonInit]; + } + return self; +} + +- (void)commonInit { + if (self.config.fileManager) { + self.fileManager = self.config.fileManager; + } else { + self.fileManager = [NSFileManager new]; + } + + [self createDirectory]; +} + +- (BOOL)containsDataForKey:(NSString *)key { + NSParameterAssert(key); + NSString *filePath = [self cachePathForKey:key]; + BOOL exists = [self.fileManager fileExistsAtPath:filePath]; + + // fallback because of https://github.com/rs/SDWebImage/pull/976 that added the extension to the disk file name + // checking the key with and without the extension + if (!exists) { + exists = [self.fileManager fileExistsAtPath:filePath.stringByDeletingPathExtension]; + } + + return exists; +} + +- (NSData *)dataForKey:(NSString *)key { + NSParameterAssert(key); + NSString *filePath = [self cachePathForKey:key]; + // if filePath is nil or (null),framework will crash with this: + // Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[_NSPlaceholderData initWithContentsOfFile:options:maxLength:error:]: nil file argument' + if (filePath == nil || [@"(null)" isEqualToString: filePath]) { + return nil; + } + NSData *data = [NSData dataWithContentsOfFile:filePath options:self.config.diskCacheReadingOptions error:nil]; + if (data) { + [[NSURL fileURLWithPath:filePath] setResourceValue:[NSDate date] forKey:NSURLContentAccessDateKey error:nil]; + return data; + } + + // fallback because of https://github.com/rs/SDWebImage/pull/976 that added the extension to the disk file name + // checking the key with and without the extension + filePath = filePath.stringByDeletingPathExtension; + data = [NSData dataWithContentsOfFile:filePath options:self.config.diskCacheReadingOptions error:nil]; + if (data) { + [[NSURL fileURLWithPath:filePath] setResourceValue:[NSDate date] forKey:NSURLContentAccessDateKey error:nil]; + return data; + } + + return nil; +} + +- (void)setData:(NSData *)data forKey:(NSString *)key { + NSParameterAssert(data); + NSParameterAssert(key); + + // get cache Path for image key + NSString *cachePathForKey = [self cachePathForKey:key]; + // transform to NSURL + NSURL *fileURL = [NSURL fileURLWithPath:cachePathForKey isDirectory:NO]; + + [data writeToURL:fileURL options:self.config.diskCacheWritingOptions error:nil]; +} + +- (NSData *)extendedDataForKey:(NSString *)key { + NSParameterAssert(key); + + // get cache Path for image key + NSString *cachePathForKey = [self cachePathForKey:key]; + + NSData *extendedData = [SDFileAttributeHelper extendedAttribute:SDDiskCacheExtendedAttributeName atPath:cachePathForKey traverseLink:NO error:nil]; + + return extendedData; +} + +- (void)setExtendedData:(NSData *)extendedData forKey:(NSString *)key { + NSParameterAssert(key); + // get cache Path for image key + NSString *cachePathForKey = [self cachePathForKey:key]; + + if (!extendedData) { + // Remove + [SDFileAttributeHelper removeExtendedAttribute:SDDiskCacheExtendedAttributeName atPath:cachePathForKey traverseLink:NO error:nil]; + } else { + // Override + [SDFileAttributeHelper setExtendedAttribute:SDDiskCacheExtendedAttributeName value:extendedData atPath:cachePathForKey traverseLink:NO overwrite:YES error:nil]; + } +} + +- (void)removeDataForKey:(NSString *)key { + NSParameterAssert(key); + NSString *filePath = [self cachePathForKey:key]; + [self.fileManager removeItemAtPath:filePath error:nil]; +} + +- (void)removeAllData { + [self.fileManager removeItemAtPath:self.diskCachePath error:nil]; + [self createDirectory]; +} + +- (void)createDirectory { + [self.fileManager createDirectoryAtPath:self.diskCachePath + withIntermediateDirectories:YES + attributes:nil + error:NULL]; + + // disable iCloud backup + if (self.config.shouldDisableiCloud) { + // ignore iCloud backup resource value error + [[NSURL fileURLWithPath:self.diskCachePath isDirectory:YES] setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil]; + } +} + +- (void)removeExpiredData { + NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES]; + + // Compute content date key to be used for tests + NSURLResourceKey cacheContentDateKey; + switch (self.config.diskCacheExpireType) { + case SDImageCacheConfigExpireTypeModificationDate: + cacheContentDateKey = NSURLContentModificationDateKey; + break; + case SDImageCacheConfigExpireTypeCreationDate: + cacheContentDateKey = NSURLCreationDateKey; + break; + case SDImageCacheConfigExpireTypeChangeDate: + cacheContentDateKey = NSURLAttributeModificationDateKey; + break; + case SDImageCacheConfigExpireTypeAccessDate: + default: + cacheContentDateKey = NSURLContentAccessDateKey; + break; + } + + NSArray *resourceKeys = @[NSURLIsDirectoryKey, cacheContentDateKey, NSURLTotalFileAllocatedSizeKey]; + + // This enumerator prefetches useful properties for our cache files. + NSDirectoryEnumerator *fileEnumerator = [self.fileManager enumeratorAtURL:diskCacheURL + includingPropertiesForKeys:resourceKeys + options:NSDirectoryEnumerationSkipsHiddenFiles + errorHandler:NULL]; + + NSDate *expirationDate = (self.config.maxDiskAge < 0) ? nil: [NSDate dateWithTimeIntervalSinceNow:-self.config.maxDiskAge]; + NSMutableDictionary *> *cacheFiles = [NSMutableDictionary dictionary]; + NSUInteger currentCacheSize = 0; + + // Enumerate all of the files in the cache directory. This loop has two purposes: + // + // 1. Removing files that are older than the expiration date. + // 2. Storing file attributes for the size-based cleanup pass. + NSMutableArray *urlsToDelete = [[NSMutableArray alloc] init]; + for (NSURL *fileURL in fileEnumerator) { + @autoreleasepool { + NSError *error; + NSDictionary *resourceValues = [fileURL resourceValuesForKeys:resourceKeys error:&error]; + + // Skip directories and errors. + if (error || !resourceValues || [resourceValues[NSURLIsDirectoryKey] boolValue]) { + continue; + } + + // Remove files that are older than the expiration date; + NSDate *modifiedDate = resourceValues[cacheContentDateKey]; + if (expirationDate && [[modifiedDate laterDate:expirationDate] isEqualToDate:expirationDate]) { + [urlsToDelete addObject:fileURL]; + continue; + } + + // Store a reference to this file and account for its total size. + NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey]; + currentCacheSize += totalAllocatedSize.unsignedIntegerValue; + cacheFiles[fileURL] = resourceValues; + } + } + + for (NSURL *fileURL in urlsToDelete) { + [self.fileManager removeItemAtURL:fileURL error:nil]; + } + + // If our remaining disk cache exceeds a configured maximum size, perform a second + // size-based cleanup pass. We delete the oldest files first. + NSUInteger maxDiskSize = self.config.maxDiskSize; + if (maxDiskSize > 0 && currentCacheSize > maxDiskSize) { + // Target half of our maximum cache size for this cleanup pass. + const NSUInteger desiredCacheSize = maxDiskSize / 2; + + // Sort the remaining cache files by their last modification time or last access time (oldest first). + NSArray *sortedFiles = [cacheFiles keysSortedByValueWithOptions:NSSortConcurrent + usingComparator:^NSComparisonResult(id obj1, id obj2) { + return [obj1[cacheContentDateKey] compare:obj2[cacheContentDateKey]]; + }]; + + // Delete files until we fall below our desired cache size. + for (NSURL *fileURL in sortedFiles) { + if ([self.fileManager removeItemAtURL:fileURL error:nil]) { + NSDictionary *resourceValues = cacheFiles[fileURL]; + NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey]; + currentCacheSize -= totalAllocatedSize.unsignedIntegerValue; + + if (currentCacheSize < desiredCacheSize) { + break; + } + } + } + } +} + +- (nullable NSString *)cachePathForKey:(NSString *)key { + NSParameterAssert(key); + return [self cachePathForKey:key inPath:self.diskCachePath]; +} + +- (NSUInteger)totalSize { + NSUInteger size = 0; + + // Use URL-based enumerator instead of Path(NSString *)-based enumerator to reduce + // those objects(ex. NSPathStore2/_NSCFString/NSConcreteData) created during traversal. + // Even worse, those objects are added into AutoreleasePool, in background threads, + // the time to release those objects is undifined(according to the usage of CPU) + // It will truely consumes a lot of VM, up to cause OOMs. + @autoreleasepool { + NSURL *pathURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES]; + NSDirectoryEnumerator *fileEnumerator = [self.fileManager enumeratorAtURL:pathURL + includingPropertiesForKeys:@[NSURLFileSizeKey] + options:(NSDirectoryEnumerationOptions)0 + errorHandler:NULL]; + + for (NSURL *fileURL in fileEnumerator) { + @autoreleasepool { + NSNumber *fileSize; + [fileURL getResourceValue:&fileSize forKey:NSURLFileSizeKey error:NULL]; + size += fileSize.unsignedIntegerValue; + } + } + } + return size; +} + +- (NSUInteger)totalCount { + NSUInteger count = 0; + @autoreleasepool { + NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES]; + NSDirectoryEnumerator *fileEnumerator = [self.fileManager enumeratorAtURL:diskCacheURL includingPropertiesForKeys:@[] options:(NSDirectoryEnumerationOptions)0 errorHandler:nil]; + count = fileEnumerator.allObjects.count; + } + return count; +} + +#pragma mark - Cache paths + +- (nullable NSString *)cachePathForKey:(nullable NSString *)key inPath:(nonnull NSString *)path { + NSString *filename = SDDiskCacheFileNameForKey(key); + return [path stringByAppendingPathComponent:filename]; +} + +- (void)moveCacheDirectoryFromPath:(nonnull NSString *)srcPath toPath:(nonnull NSString *)dstPath { + NSParameterAssert(srcPath); + NSParameterAssert(dstPath); + // Check if old path is equal to new path + if ([srcPath isEqualToString:dstPath]) { + return; + } + BOOL isDirectory; + // Check if old path is directory + if (![self.fileManager fileExistsAtPath:srcPath isDirectory:&isDirectory] || !isDirectory) { + return; + } + // Check if new path is directory + if (![self.fileManager fileExistsAtPath:dstPath isDirectory:&isDirectory] || !isDirectory) { + if (!isDirectory) { + // New path is not directory, remove file + [self.fileManager removeItemAtPath:dstPath error:nil]; + } + NSString *dstParentPath = [dstPath stringByDeletingLastPathComponent]; + // Creates any non-existent parent directories as part of creating the directory in path + if (![self.fileManager fileExistsAtPath:dstParentPath]) { + [self.fileManager createDirectoryAtPath:dstParentPath withIntermediateDirectories:YES attributes:nil error:NULL]; + } + // New directory does not exist, rename directory + [self.fileManager moveItemAtPath:srcPath toPath:dstPath error:nil]; + // disable iCloud backup + if (self.config.shouldDisableiCloud) { + // ignore iCloud backup resource value error + [[NSURL fileURLWithPath:dstPath isDirectory:YES] setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil]; + } + } else { + // New directory exist, merge the files + NSURL *srcURL = [NSURL fileURLWithPath:srcPath isDirectory:YES]; + NSDirectoryEnumerator *srcDirEnumerator = [self.fileManager enumeratorAtURL:srcURL + includingPropertiesForKeys:@[] + options:(NSDirectoryEnumerationOptions)0 + errorHandler:NULL]; + for (NSURL *url in srcDirEnumerator) { + @autoreleasepool { + NSString *dstFilePath = [dstPath stringByAppendingPathComponent:url.lastPathComponent]; + NSURL *dstFileURL = [NSURL fileURLWithPath:dstFilePath isDirectory:NO]; + [self.fileManager moveItemAtURL:url toURL:dstFileURL error:nil]; + } + } + + // Remove the old path + [self.fileManager removeItemAtURL:srcURL error:nil]; + } +} + +#pragma mark - Hash + +static inline NSString *SDSanitizeFileNameString(NSString * _Nullable fileName) { + if ([fileName length] == 0) { + return fileName; + } + // note: `:` is the only invalid char on Apple file system + // but `/` or `\` is valid + // \0 is also special case (which cause Foundation API treat the C string as EOF) + NSCharacterSet* illegalFileNameCharacters = [NSCharacterSet characterSetWithCharactersInString:@"\0:"]; + return [[fileName componentsSeparatedByCharactersInSet:illegalFileNameCharacters] componentsJoinedByString:@""]; +} + +#define SD_MAX_FILE_EXTENSION_LENGTH (NAME_MAX - CC_MD5_DIGEST_LENGTH * 2 - 1) + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +static inline NSString * _Nonnull SDDiskCacheFileNameForKey(NSString * _Nullable key) { + const char *str = key.UTF8String; + if (str == NULL) { + str = ""; + } + unsigned char r[CC_MD5_DIGEST_LENGTH]; + CC_MD5(str, (CC_LONG)strlen(str), r); + NSString *ext; + // 1. Use URL path extname if valid + NSURL *keyURL = [NSURL URLWithString:key]; + if (keyURL) { + ext = keyURL.pathExtension; + } + // 2. Use file extname if valid + if (!ext) { + ext = key.pathExtension; + } + // 3. Check if extname valid on file system + ext = SDSanitizeFileNameString(ext); + // File system has file name length limit, we need to check if ext is too long, we don't add it to the filename + if (ext.length > SD_MAX_FILE_EXTENSION_LENGTH) { + ext = nil; + } + NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%@", + r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], + r[11], r[12], r[13], r[14], r[15], ext.length == 0 ? @"" : [NSString stringWithFormat:@".%@", ext]]; + return filename; +} +#pragma clang diagnostic pop + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDGraphicsImageRenderer.h b/Pods/SDWebImage/SDWebImage/Core/SDGraphicsImageRenderer.h new file mode 100644 index 0000000..79bbef6 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDGraphicsImageRenderer.h @@ -0,0 +1,84 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import "SDWebImageCompat.h" + +/** + These following class are provided to use `UIGraphicsImageRenderer` with polyfill, which allows write cross-platform(AppKit/UIKit) code and avoid runtime version check. + Compared to `UIGraphicsBeginImageContext`, `UIGraphicsImageRenderer` use dynamic bitmap from your draw code to generate CGContext, not always use ARGB8888, which is more performant on RAM usage. + Which means, if you draw CGImage/CIImage which contains grayscale only, the underlaying bitmap context use grayscale, it's managed by system and not a fixed type. (actually, the `kCGContextTypeAutomatic`) + For usage, See more in Apple's documentation: https://developer.apple.com/documentation/uikit/uigraphicsimagerenderer + For UIKit on iOS/tvOS 10+, these method just use the same `UIGraphicsImageRenderer` API. + For others (macOS/watchOS or iOS/tvOS 10-), these method use the `SDImageGraphics.h` to implements the same behavior (but without dynamic bitmap support) +*/ + +/// A closure for drawing an image. +typedef void (^SDGraphicsImageDrawingActions)(CGContextRef _Nonnull context); +/// Constants that specify the color range of the image renderer context. +typedef NS_ENUM(NSInteger, SDGraphicsImageRendererFormatRange) { + /// The image renderer context doesn’t specify a color range. + SDGraphicsImageRendererFormatRangeUnspecified = -1, + /// The system automatically chooses the image renderer context’s pixel format according to the color range of its content. + SDGraphicsImageRendererFormatRangeAutomatic = 0, + /// The image renderer context supports wide color. + SDGraphicsImageRendererFormatRangeExtended, + /// The image renderer context doesn’t support extended colors. + SDGraphicsImageRendererFormatRangeStandard +}; + +/// A set of drawing attributes that represent the configuration of an image renderer context. +@interface SDGraphicsImageRendererFormat : NSObject + +#if SD_UIKIT +/// The underlying uiformat for UIKit. This usage of this API should be careful, which may cause out of sync. +@property (nonatomic, strong, nonnull) UIGraphicsImageRendererFormat *uiformat API_AVAILABLE(ios(10.0), tvos(10.0)); +#endif + +/// The display scale of the image renderer context. +/// The default value is equal to the scale of the main screen. +@property (nonatomic) CGFloat scale; + +/// A Boolean value indicating whether the underlying Core Graphics context has an alpha channel. +/// The default value is NO. +@property (nonatomic) BOOL opaque; + +/// Specifying whether the bitmap context should use extended color. +/// For iOS 12+, the value is from system `preferredRange` property +/// For iOS 10-11, the value is from system `prefersExtendedRange` property +/// For iOS 9-, the value is `.standard` +@property (nonatomic) SDGraphicsImageRendererFormatRange preferredRange; + +/// Init the default format. See each properties's default value. +- (nonnull instancetype)init; + +/// Returns a new format best suited for the main screen’s current configuration. ++ (nonnull instancetype)preferredFormat; + +@end + +/// A graphics renderer for creating Core Graphics-backed images. +@interface SDGraphicsImageRenderer : NSObject + +/// Creates an image renderer for drawing images of a given size. +/// @param size The size of images output from the renderer, specified in points. +/// @return An initialized image renderer. +- (nonnull instancetype)initWithSize:(CGSize)size; + +/// Creates a new image renderer with a given size and format. +/// @param size The size of images output from the renderer, specified in points. +/// @param format A SDGraphicsImageRendererFormat object that encapsulates the format used to create the renderer context. +/// @return An initialized image renderer. +- (nonnull instancetype)initWithSize:(CGSize)size format:(nonnull SDGraphicsImageRendererFormat *)format; + +/// Creates an image by following a set of drawing instructions. +/// @param actions A SDGraphicsImageDrawingActions block that, when invoked by the renderer, executes a set of drawing instructions to create the output image. +/// @note You should not retain or use the context outside the block, it's non-escaping. +/// @return A UIImage object created by the supplied drawing actions. +- (nonnull UIImage *)imageWithActions:(nonnull NS_NOESCAPE SDGraphicsImageDrawingActions)actions; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDGraphicsImageRenderer.m b/Pods/SDWebImage/SDWebImage/Core/SDGraphicsImageRenderer.m new file mode 100644 index 0000000..772ff9a --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDGraphicsImageRenderer.m @@ -0,0 +1,229 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import "SDGraphicsImageRenderer.h" +#import "SDImageGraphics.h" +#import "SDDeviceHelper.h" + +@implementation SDGraphicsImageRendererFormat +@synthesize scale = _scale; +@synthesize opaque = _opaque; +@synthesize preferredRange = _preferredRange; + +#pragma mark - Property +- (CGFloat)scale { +#if SD_UIKIT + if (@available(iOS 10.0, tvOS 10.10, *)) { + return self.uiformat.scale; + } else { + return _scale; + } +#else + return _scale; +#endif +} + +- (void)setScale:(CGFloat)scale { +#if SD_UIKIT + if (@available(iOS 10.0, tvOS 10.10, *)) { + self.uiformat.scale = scale; + } else { + _scale = scale; + } +#else + _scale = scale; +#endif +} + +- (BOOL)opaque { +#if SD_UIKIT + if (@available(iOS 10.0, tvOS 10.10, *)) { + return self.uiformat.opaque; + } else { + return _opaque; + } +#else + return _opaque; +#endif +} + +- (void)setOpaque:(BOOL)opaque { +#if SD_UIKIT + if (@available(iOS 10.0, tvOS 10.10, *)) { + self.uiformat.opaque = opaque; + } else { + _opaque = opaque; + } +#else + _opaque = opaque; +#endif +} + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +- (SDGraphicsImageRendererFormatRange)preferredRange { +#if SD_VISION + return (SDGraphicsImageRendererFormatRange)self.uiformat.preferredRange; +#elif SD_UIKIT + if (@available(iOS 10.0, tvOS 10.10, *)) { + if (@available(iOS 12.0, tvOS 12.0, *)) { + return (SDGraphicsImageRendererFormatRange)self.uiformat.preferredRange; + } else { + BOOL prefersExtendedRange = self.uiformat.prefersExtendedRange; + if (prefersExtendedRange) { + return SDGraphicsImageRendererFormatRangeExtended; + } else { + return SDGraphicsImageRendererFormatRangeStandard; + } + } + } else { + return _preferredRange; + } +#else + return _preferredRange; +#endif +} + +- (void)setPreferredRange:(SDGraphicsImageRendererFormatRange)preferredRange { +#if SD_VISION + self.uiformat.preferredRange = (UIGraphicsImageRendererFormatRange)preferredRange; +#elif SD_UIKIT + if (@available(iOS 10.0, tvOS 10.10, *)) { + if (@available(iOS 12.0, tvOS 12.0, *)) { + self.uiformat.preferredRange = (UIGraphicsImageRendererFormatRange)preferredRange; + } else { + switch (preferredRange) { + case SDGraphicsImageRendererFormatRangeExtended: + self.uiformat.prefersExtendedRange = YES; + break; + case SDGraphicsImageRendererFormatRangeStandard: + self.uiformat.prefersExtendedRange = NO; + default: + // Automatic means default + break; + } + } + } else { + _preferredRange = preferredRange; + } +#else + _preferredRange = preferredRange; +#endif +} +#pragma clang diagnostic pop + +- (instancetype)init { + self = [super init]; + if (self) { +#if SD_UIKIT + if (@available(iOS 10.0, tvOS 10.10, *)) { + UIGraphicsImageRendererFormat *uiformat = [[UIGraphicsImageRendererFormat alloc] init]; + self.uiformat = uiformat; + } else { +#endif + CGFloat screenScale = SDDeviceHelper.screenScale; + self.scale = screenScale; + self.opaque = NO; +#if SD_UIKIT + } +#endif + } + return self; +} + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability" +- (instancetype)initForMainScreen { + self = [super init]; + if (self) { +#if SD_UIKIT + if (@available(iOS 10.0, tvOS 10.0, *)) { + UIGraphicsImageRendererFormat *uiformat; + // iOS 11.0.0 GM does have `preferredFormat`, but iOS 11 betas did not (argh!) + if ([UIGraphicsImageRenderer respondsToSelector:@selector(preferredFormat)]) { + uiformat = [UIGraphicsImageRendererFormat preferredFormat]; + } else { + uiformat = [UIGraphicsImageRendererFormat defaultFormat]; + } + self.uiformat = uiformat; + } else { +#endif + CGFloat screenScale = SDDeviceHelper.screenScale; + self.scale = screenScale; + self.opaque = NO; +#if SD_UIKIT + } +#endif + } + return self; +} +#pragma clang diagnostic pop + ++ (instancetype)preferredFormat { + SDGraphicsImageRendererFormat *format = [[SDGraphicsImageRendererFormat alloc] initForMainScreen]; + return format; +} + +@end + +@interface SDGraphicsImageRenderer () +@property (nonatomic, assign) CGSize size; +@property (nonatomic, strong) SDGraphicsImageRendererFormat *format; +#if SD_UIKIT +@property (nonatomic, strong) UIGraphicsImageRenderer *uirenderer API_AVAILABLE(ios(10.0), tvos(10.0)); +#endif +@end + +@implementation SDGraphicsImageRenderer + +- (instancetype)initWithSize:(CGSize)size { + return [self initWithSize:size format:SDGraphicsImageRendererFormat.preferredFormat]; +} + +- (instancetype)initWithSize:(CGSize)size format:(SDGraphicsImageRendererFormat *)format { + NSParameterAssert(format); + self = [super init]; + if (self) { + self.size = size; + self.format = format; +#if SD_UIKIT + if (@available(iOS 10.0, tvOS 10.0, *)) { + UIGraphicsImageRendererFormat *uiformat = format.uiformat; + self.uirenderer = [[UIGraphicsImageRenderer alloc] initWithSize:size format:uiformat]; + } +#endif + } + return self; +} + +- (UIImage *)imageWithActions:(NS_NOESCAPE SDGraphicsImageDrawingActions)actions { + NSParameterAssert(actions); +#if SD_UIKIT + if (@available(iOS 10.0, tvOS 10.0, *)) { + UIGraphicsImageDrawingActions uiactions = ^(UIGraphicsImageRendererContext *rendererContext) { + if (actions) { + actions(rendererContext.CGContext); + } + }; + return [self.uirenderer imageWithActions:uiactions]; + } else { +#endif + SDGraphicsBeginImageContextWithOptions(self.size, self.format.opaque, self.format.scale); + CGContextRef context = SDGraphicsGetCurrentContext(); + if (actions) { + actions(context); + } + UIImage *image = SDGraphicsGetImageFromCurrentImageContext(); + SDGraphicsEndImageContext(); + return image; +#if SD_UIKIT + } +#endif +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDImageAPNGCoder.h b/Pods/SDWebImage/SDWebImage/Core/SDImageAPNGCoder.h new file mode 100644 index 0000000..f73742c --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDImageAPNGCoder.h @@ -0,0 +1,19 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDImageIOAnimatedCoder.h" + +/** + Built in coder using ImageIO that supports APNG encoding/decoding + */ +@interface SDImageAPNGCoder : SDImageIOAnimatedCoder + +@property (nonatomic, class, readonly, nonnull) SDImageAPNGCoder *sharedCoder; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDImageAPNGCoder.m b/Pods/SDWebImage/SDWebImage/Core/SDImageAPNGCoder.m new file mode 100644 index 0000000..b262bd3 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDImageAPNGCoder.m @@ -0,0 +1,58 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDImageAPNGCoder.h" +#import "SDImageIOAnimatedCoderInternal.h" +#if SD_MAC +#import +#else +#import +#endif + +@implementation SDImageAPNGCoder + ++ (instancetype)sharedCoder { + static SDImageAPNGCoder *coder; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + coder = [[SDImageAPNGCoder alloc] init]; + }); + return coder; +} + +#pragma mark - Subclass Override + ++ (SDImageFormat)imageFormat { + return SDImageFormatPNG; +} + ++ (NSString *)imageUTType { + return (__bridge NSString *)kSDUTTypePNG; +} + ++ (NSString *)dictionaryProperty { + return (__bridge NSString *)kCGImagePropertyPNGDictionary; +} + ++ (NSString *)unclampedDelayTimeProperty { + return (__bridge NSString *)kCGImagePropertyAPNGUnclampedDelayTime; +} + ++ (NSString *)delayTimeProperty { + return (__bridge NSString *)kCGImagePropertyAPNGDelayTime; +} + ++ (NSString *)loopCountProperty { + return (__bridge NSString *)kCGImagePropertyAPNGLoopCount; +} + ++ (NSUInteger)defaultLoopCount { + return 0; +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDImageAWebPCoder.h b/Pods/SDWebImage/SDWebImage/Core/SDImageAWebPCoder.h new file mode 100644 index 0000000..4b585a9 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDImageAWebPCoder.h @@ -0,0 +1,23 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDImageIOAnimatedCoder.h" + +/** + This coder is used for Google WebP and Animated WebP(AWebP) image format. + Image/IO provide the WebP decoding support in iOS 14/macOS 11/tvOS 14/watchOS 7+. + @note Currently Image/IO seems does not supports WebP encoding, if you need WebP encoding, use the custom codec below. + @note If you need to support lower firmware version for WebP, you can have a try at https://github.com/SDWebImage/SDWebImageWebPCoder + */ +API_AVAILABLE(ios(14.0), tvos(14.0), macos(11.0), watchos(7.0)) +@interface SDImageAWebPCoder : SDImageIOAnimatedCoder + +@property (nonatomic, class, readonly, nonnull) SDImageAWebPCoder *sharedCoder; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDImageAWebPCoder.m b/Pods/SDWebImage/SDWebImage/Core/SDImageAWebPCoder.m new file mode 100644 index 0000000..e58bc21 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDImageAWebPCoder.m @@ -0,0 +1,98 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import "SDImageAWebPCoder.h" +#import "SDImageIOAnimatedCoderInternal.h" + +// These constants are available from iOS 14+ and Xcode 12. This raw value is used for toolchain and firmware compatibility +static NSString * kSDCGImagePropertyWebPDictionary = @"{WebP}"; +static NSString * kSDCGImagePropertyWebPLoopCount = @"LoopCount"; +static NSString * kSDCGImagePropertyWebPDelayTime = @"DelayTime"; +static NSString * kSDCGImagePropertyWebPUnclampedDelayTime = @"UnclampedDelayTime"; + +@implementation SDImageAWebPCoder + ++ (void)initialize { +#if __IPHONE_14_0 || __TVOS_14_0 || __MAC_11_0 || __WATCHOS_7_0 + // Xcode 12 + if (@available(iOS 14, tvOS 14, macOS 11, watchOS 7, *)) { + // Use SDK instead of raw value + kSDCGImagePropertyWebPDictionary = (__bridge NSString *)kCGImagePropertyWebPDictionary; + kSDCGImagePropertyWebPLoopCount = (__bridge NSString *)kCGImagePropertyWebPLoopCount; + kSDCGImagePropertyWebPDelayTime = (__bridge NSString *)kCGImagePropertyWebPDelayTime; + kSDCGImagePropertyWebPUnclampedDelayTime = (__bridge NSString *)kCGImagePropertyWebPUnclampedDelayTime; + } +#endif +} + ++ (instancetype)sharedCoder { + static SDImageAWebPCoder *coder; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + coder = [[SDImageAWebPCoder alloc] init]; + }); + return coder; +} + +#pragma mark - SDImageCoder + +- (BOOL)canDecodeFromData:(nullable NSData *)data { + switch ([NSData sd_imageFormatForImageData:data]) { + case SDImageFormatWebP: + // Check WebP decoding compatibility + return [self.class canDecodeFromFormat:SDImageFormatWebP]; + default: + return NO; + } +} + +- (BOOL)canIncrementalDecodeFromData:(NSData *)data { + return [self canDecodeFromData:data]; +} + +- (BOOL)canEncodeToFormat:(SDImageFormat)format { + switch (format) { + case SDImageFormatWebP: + // Check WebP encoding compatibility + return [self.class canEncodeToFormat:SDImageFormatWebP]; + default: + return NO; + } +} + +#pragma mark - Subclass Override + ++ (SDImageFormat)imageFormat { + return SDImageFormatWebP; +} + ++ (NSString *)imageUTType { + return (__bridge NSString *)kSDUTTypeWebP; +} + ++ (NSString *)dictionaryProperty { + return kSDCGImagePropertyWebPDictionary; +} + ++ (NSString *)unclampedDelayTimeProperty { + return kSDCGImagePropertyWebPUnclampedDelayTime; +} + ++ (NSString *)delayTimeProperty { + return kSDCGImagePropertyWebPDelayTime; +} + ++ (NSString *)loopCountProperty { + return kSDCGImagePropertyWebPLoopCount; +} + ++ (NSUInteger)defaultLoopCount { + return 0; +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDImageCache.h b/Pods/SDWebImage/SDWebImage/Core/SDImageCache.h new file mode 100644 index 0000000..d576f43 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDImageCache.h @@ -0,0 +1,477 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" +#import "SDWebImageDefine.h" +#import "SDImageCacheConfig.h" +#import "SDImageCacheDefine.h" +#import "SDMemoryCache.h" +#import "SDDiskCache.h" + +/// Image Cache Options +typedef NS_OPTIONS(NSUInteger, SDImageCacheOptions) { + /** + * By default, we do not query image data when the image is already cached in memory. This mask can force to query image data at the same time. However, this query is asynchronously unless you specify `SDImageCacheQueryMemoryDataSync` + */ + SDImageCacheQueryMemoryData = 1 << 0, + /** + * By default, when you only specify `SDImageCacheQueryMemoryData`, we query the memory image data asynchronously. Combined this mask as well to query the memory image data synchronously. + */ + SDImageCacheQueryMemoryDataSync = 1 << 1, + /** + * By default, when the memory cache miss, we query the disk cache asynchronously. This mask can force to query disk cache (when memory cache miss) synchronously. + @note These 3 query options can be combined together. For the full list about these masks combination, see wiki page. + */ + SDImageCacheQueryDiskDataSync = 1 << 2, + /** + * By default, images are decoded respecting their original size. On iOS, this flag will scale down the + * images to a size compatible with the constrained memory of devices. + */ + SDImageCacheScaleDownLargeImages = 1 << 3, + /** + * By default, we will decode the image in the background during cache query and download from the network. This can help to improve performance because when rendering image on the screen, it need to be firstly decoded. But this happen on the main queue by Core Animation. + * However, this process may increase the memory usage as well. If you are experiencing a issue due to excessive memory consumption, This flag can prevent decode the image. + * @note 5.14.0 introduce `SDImageCoderDecodeUseLazyDecoding`, use that for better control from codec, instead of post-processing. Which acts the similar like this option but works for SDAnimatedImage as well (this one does not) + * @deprecated Deprecated in v5.17.0, if you don't want force-decode, pass [.imageForceDecodePolicy] = SDImageForceDecodePolicy.never.rawValue in context option + */ + SDImageCacheAvoidDecodeImage API_DEPRECATED("Use SDWebImageContextImageForceDecodePolicy instead", macos(10.10, 10.10), ios(8.0, 8.0), tvos(9.0, 9.0), watchos(2.0, 2.0)) = 1 << 4, + /** + * By default, we decode the animated image. This flag can force decode the first frame only and produce the static image. + */ + SDImageCacheDecodeFirstFrameOnly = 1 << 5, + /** + * By default, for `SDAnimatedImage`, we decode the animated image frame during rendering to reduce memory usage. This flag actually trigger `preloadAllAnimatedImageFrames = YES` after image load from disk cache + */ + SDImageCachePreloadAllFrames = 1 << 6, + /** + * By default, when you use `SDWebImageContextAnimatedImageClass` context option (like using `SDAnimatedImageView` which designed to use `SDAnimatedImage`), we may still use `UIImage` when the memory cache hit, or image decoder is not available, to behave as a fallback solution. + * Using this option, can ensure we always produce image with your provided class. If failed, an error with code `SDWebImageErrorBadImageData` will be used. + * Note this options is not compatible with `SDImageCacheDecodeFirstFrameOnly`, which always produce a UIImage/NSImage. + */ + SDImageCacheMatchAnimatedImageClass = 1 << 7, +}; + +/** + * A token associated with each cache query. Can be used to cancel a cache query + */ +@interface SDImageCacheToken : NSObject + +/** + Cancel the current cache query. + */ +- (void)cancel; + +/** + The query's cache key. + */ +@property (nonatomic, strong, nullable, readonly) NSString *key; + +@end + +/** + * SDImageCache maintains a memory cache and a disk cache. Disk cache write operations are performed + * asynchronous so it doesn’t add unnecessary latency to the UI. + */ +@interface SDImageCache : NSObject + +#pragma mark - Properties + +/** + * Cache Config object - storing all kind of settings. + * The property is copy so change of current config will not accidentally affect other cache's config. + */ +@property (nonatomic, copy, nonnull, readonly) SDImageCacheConfig *config; + +/** + * The memory cache implementation object used for current image cache. + * By default we use `SDMemoryCache` class, you can also use this to call your own implementation class method. + * @note To customize this class, check `SDImageCacheConfig.memoryCacheClass` property. + */ +@property (nonatomic, strong, readonly, nonnull) id memoryCache; + +/** + * The disk cache implementation object used for current image cache. + * By default we use `SDMemoryCache` class, you can also use this to call your own implementation class method. + * @note To customize this class, check `SDImageCacheConfig.diskCacheClass` property. + * @warning When calling method about read/write in disk cache, be sure to either make your disk cache implementation IO-safe or using the same access queue to avoid issues. + */ +@property (nonatomic, strong, readonly, nonnull) id diskCache; + +/** + * The disk cache's root path + */ +@property (nonatomic, copy, nonnull, readonly) NSString *diskCachePath; + +/** + * The additional disk cache path to check if the query from disk cache not exist; + * The `key` param is the image cache key. The returned file path will be used to load the disk cache. If return nil, ignore it. + * Useful if you want to bundle pre-loaded images with your app + */ +@property (nonatomic, copy, nullable) SDImageCacheAdditionalCachePathBlock additionalCachePathBlock; + +#pragma mark - Singleton and initialization + +/** + * Returns global shared cache instance + */ +@property (nonatomic, class, readonly, nonnull) SDImageCache *sharedImageCache; + +/** + * Control the default disk cache directory. This will effect all the SDImageCache instance created after modification, even for shared image cache. + * This can be used to share the same disk cache with the App and App Extension (Today/Notification Widget) using `- [NSFileManager.containerURLForSecurityApplicationGroupIdentifier:]`. + * @note If you pass nil, the value will be reset to `~/Library/Caches/com.hackemist.SDImageCache`. + * @note We still preserve the `namespace` arg, which means, if you change this property into `/path/to/use`, the `SDImageCache.sharedImageCache.diskCachePath` should be `/path/to/use/default` because shared image cache use `default` as namespace. + * Defaults to nil. + */ +@property (nonatomic, class, readwrite, null_resettable) NSString *defaultDiskCacheDirectory; + +/** + * Init a new cache store with a specific namespace + * The final disk cache directory should looks like ($directory/$namespace). And the default config of shared cache, should result in (~/Library/Caches/com.hackemist.SDImageCache/default/) + * + * @param ns The namespace to use for this cache store + */ +- (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns; + +/** + * Init a new cache store with a specific namespace and directory. + * The final disk cache directory should looks like ($directory/$namespace). And the default config of shared cache, should result in (~/Library/Caches/com.hackemist.SDImageCache/default/) + * + * @param ns The namespace to use for this cache store + * @param directory Directory to cache disk images in + */ +- (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns + diskCacheDirectory:(nullable NSString *)directory; + +/** + * Init a new cache store with a specific namespace, directory and config. + * The final disk cache directory should looks like ($directory/$namespace). And the default config of shared cache, should result in (~/Library/Caches/com.hackemist.SDImageCache/default/) + * + * @param ns The namespace to use for this cache store + * @param directory Directory to cache disk images in + * @param config The cache config to be used to create the cache. You can provide custom memory cache or disk cache class in the cache config + */ +- (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns + diskCacheDirectory:(nullable NSString *)directory + config:(nullable SDImageCacheConfig *)config NS_DESIGNATED_INITIALIZER; + +#pragma mark - Cache paths + +/** + Get the cache path for a certain key + + @param key The unique image cache key + @return The cache path. You can check `lastPathComponent` to grab the file name. + */ +- (nullable NSString *)cachePathForKey:(nullable NSString *)key; + +#pragma mark - Store Ops + +/** + * Asynchronously store an image into memory and disk cache at the given key. + * + * @param image The image to store + * @param key The unique image cache key, usually it's image absolute URL + * @param completionBlock A block executed after the operation is finished + */ +- (void)storeImage:(nullable UIImage *)image + forKey:(nullable NSString *)key + completion:(nullable SDWebImageNoParamsBlock)completionBlock; + +/** + * Asynchronously store an image into memory and disk cache at the given key. + * + * @param image The image to store + * @param key The unique image cache key, usually it's image absolute URL + * @param toDisk Store the image to disk cache if YES. If NO, the completion block is called synchronously + * @param completionBlock A block executed after the operation is finished + * @note If no image data is provided and encode to disk, we will try to detect the image format (using either `sd_imageFormat` or `SDAnimatedImage` protocol method) and animation status, to choose the best matched format, including GIF, JPEG or PNG. + */ +- (void)storeImage:(nullable UIImage *)image + forKey:(nullable NSString *)key + toDisk:(BOOL)toDisk + completion:(nullable SDWebImageNoParamsBlock)completionBlock; + +/** + * Asynchronously store an image data into disk cache at the given key. + * + * @param imageData The image data to store + * @param key The unique image cache key, usually it's image absolute URL + * @param completionBlock A block executed after the operation is finished + */ +- (void)storeImageData:(nullable NSData *)imageData + forKey:(nullable NSString *)key + completion:(nullable SDWebImageNoParamsBlock)completionBlock; + +/** + * Asynchronously store an image into memory and disk cache at the given key. + * + * @param image The image to store + * @param imageData The image data as returned by the server, this representation will be used for disk storage + * instead of converting the given image object into a storable/compressed image format in order + * to save quality and CPU + * @param key The unique image cache key, usually it's image absolute URL + * @param toDisk Store the image to disk cache if YES. If NO, the completion block is called synchronously + * @param completionBlock A block executed after the operation is finished + * @note If no image data is provided and encode to disk, we will try to detect the image format (using either `sd_imageFormat` or `SDAnimatedImage` protocol method) and animation status, to choose the best matched format, including GIF, JPEG or PNG. + */ +- (void)storeImage:(nullable UIImage *)image + imageData:(nullable NSData *)imageData + forKey:(nullable NSString *)key + toDisk:(BOOL)toDisk + completion:(nullable SDWebImageNoParamsBlock)completionBlock; + +/** + * Asynchronously store an image into memory and disk cache at the given key. + * + * @param image The image to store + * @param imageData The image data as returned by the server, this representation will be used for disk storage + * instead of converting the given image object into a storable/compressed image format in order + * to save quality and CPU + * @param key The unique image cache key, usually it's image absolute URL + * @param options A mask to specify options to use for this store + * @param context The context options to use. Pass `.callbackQueue` to control callback queue + * @param cacheType The image store op cache type + * @param completionBlock A block executed after the operation is finished + * @note If no image data is provided and encode to disk, we will try to detect the image format (using either `sd_imageFormat` or `SDAnimatedImage` protocol method) and animation status, to choose the best matched format, including GIF, JPEG or PNG. + */ +- (void)storeImage:(nullable UIImage *)image + imageData:(nullable NSData *)imageData + forKey:(nullable NSString *)key + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + cacheType:(SDImageCacheType)cacheType + completion:(nullable SDWebImageNoParamsBlock)completionBlock; + +/** + * Synchronously store an image into memory cache at the given key. + * + * @param image The image to store + * @param key The unique image cache key, usually it's image absolute URL + */ +- (void)storeImageToMemory:(nullable UIImage*)image + forKey:(nullable NSString *)key; + +/** + * Synchronously store an image data into disk cache at the given key. + * + * @param imageData The image data to store + * @param key The unique image cache key, usually it's image absolute URL + */ +- (void)storeImageDataToDisk:(nullable NSData *)imageData + forKey:(nullable NSString *)key; + + +#pragma mark - Contains and Check Ops + +/** + * Asynchronously check if image exists in disk cache already (does not load the image) + * + * @param key the key describing the url + * @param completionBlock the block to be executed when the check is done. + * @note the completion block will be always executed on the main queue + */ +- (void)diskImageExistsWithKey:(nullable NSString *)key completion:(nullable SDImageCacheCheckCompletionBlock)completionBlock; + +/** + * Synchronously check if image data exists in disk cache already (does not load the image) + * + * @param key the key describing the url + */ +- (BOOL)diskImageDataExistsWithKey:(nullable NSString *)key; + +#pragma mark - Query and Retrieve Ops + +/** + * Synchronously query the image data for the given key in disk cache. You can decode the image data to image after loaded. + * + * @param key The unique key used to store the wanted image + * @return The image data for the given key, or nil if not found. + */ +- (nullable NSData *)diskImageDataForKey:(nullable NSString *)key; + +/** + * Asynchronously query the image data for the given key in disk cache. You can decode the image data to image after loaded. + * + * @param key The unique key used to store the wanted image + * @param completionBlock the block to be executed when the query is done. + * @note the completion block will be always executed on the main queue + */ +- (void)diskImageDataQueryForKey:(nullable NSString *)key completion:(nullable SDImageCacheQueryDataCompletionBlock)completionBlock; + +/** + * Asynchronously queries the cache with operation and call the completion when done. + * + * @param key The unique key used to store the wanted image. If you want transformed or thumbnail image, calculate the key with `SDTransformedKeyForKey`, `SDThumbnailedKeyForKey`, or generate the cache key from url with `cacheKeyForURL:context:`. + * @param doneBlock The completion block. Will not get called if the operation is cancelled + * + * @return a SDImageCacheToken instance containing the cache operation, will callback immediately when cancelled + */ +- (nullable SDImageCacheToken *)queryCacheOperationForKey:(nullable NSString *)key done:(nullable SDImageCacheQueryCompletionBlock)doneBlock; + +/** + * Asynchronously queries the cache with operation and call the completion when done. + * + * @param key The unique key used to store the wanted image. If you want transformed or thumbnail image, calculate the key with `SDTransformedKeyForKey`, `SDThumbnailedKeyForKey`, or generate the cache key from url with `cacheKeyForURL:context:`. + * @param options A mask to specify options to use for this cache query + * @param doneBlock The completion block. Will not get called if the operation is cancelled + * + * @return a SDImageCacheToken instance containing the cache operation, will callback immediately when cancelled + * @warning If you query with thumbnail cache key, you'd better not pass the thumbnail pixel size context, which is undefined behavior. + */ +- (nullable SDImageCacheToken *)queryCacheOperationForKey:(nullable NSString *)key options:(SDImageCacheOptions)options done:(nullable SDImageCacheQueryCompletionBlock)doneBlock; + +/** + * Asynchronously queries the cache with operation and call the completion when done. + * + * @param key The unique key used to store the wanted image. If you want transformed or thumbnail image, calculate the key with `SDTransformedKeyForKey`, `SDThumbnailedKeyForKey`, or generate the cache key from url with `cacheKeyForURL:context:`. + * @param options A mask to specify options to use for this cache query + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + * @param doneBlock The completion block. Will not get called if the operation is cancelled + * + * @return a SDImageCacheToken instance containing the cache operation, will callback immediately when cancellederation, will callback immediately when cancelled + * @warning If you query with thumbnail cache key, you'd better not pass the thumbnail pixel size context, which is undefined behavior. + */ +- (nullable SDImageCacheToken *)queryCacheOperationForKey:(nullable NSString *)key options:(SDImageCacheOptions)options context:(nullable SDWebImageContext *)context done:(nullable SDImageCacheQueryCompletionBlock)doneBlock; + +/** + * Asynchronously queries the cache with operation and call the completion when done. + * + * @param key The unique key used to store the wanted image. If you want transformed or thumbnail image, calculate the key with `SDTransformedKeyForKey`, `SDThumbnailedKeyForKey`, or generate the cache key from url with `cacheKeyForURL:context:`. + * @param options A mask to specify options to use for this cache query + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + * @param queryCacheType Specify where to query the cache from. By default we use `.all`, which means both memory cache and disk cache. You can choose to query memory only or disk only as well. Pass `.none` is invalid and callback with nil immediately. + * @param doneBlock The completion block. Will not get called if the operation is cancelled + * + * @return a SDImageCacheToken instance containing the cache operation, will callback immediately when cancelled + * @warning If you query with thumbnail cache key, you'd better not pass the thumbnail pixel size context, which is undefined behavior. + */ +- (nullable SDImageCacheToken *)queryCacheOperationForKey:(nullable NSString *)key options:(SDImageCacheOptions)options context:(nullable SDWebImageContext *)context cacheType:(SDImageCacheType)queryCacheType done:(nullable SDImageCacheQueryCompletionBlock)doneBlock; + +/** + * Synchronously query the memory cache. + * + * @param key The unique key used to store the image + * @return The image for the given key, or nil if not found. + */ +- (nullable UIImage *)imageFromMemoryCacheForKey:(nullable NSString *)key; + +/** + * Synchronously query the disk cache. + * + * @param key The unique key used to store the image + * @return The image for the given key, or nil if not found. + */ +- (nullable UIImage *)imageFromDiskCacheForKey:(nullable NSString *)key; + +/** + * Synchronously query the disk cache. With the options and context which may effect the image generation. (Such as transformer, animated image, thumbnail, etc) + * + * @param key The unique key used to store the image + * @param options A mask to specify options to use for this cache query + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + * @return The image for the given key, or nil if not found. + */ +- (nullable UIImage *)imageFromDiskCacheForKey:(nullable NSString *)key options:(SDImageCacheOptions)options context:(nullable SDWebImageContext *)context; + +/** + * Synchronously query the cache (memory and or disk) after checking the memory cache. + * + * @param key The unique key used to store the image + * @return The image for the given key, or nil if not found. + */ +- (nullable UIImage *)imageFromCacheForKey:(nullable NSString *)key; + +/** + * Synchronously query the cache (memory and or disk) after checking the memory cache. With the options and context which may effect the image generation. (Such as transformer, animated image, thumbnail, etc) + * + * @param key The unique key used to store the image + * @param options A mask to specify options to use for this cache query + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + * @return The image for the given key, or nil if not found. + */ +- (nullable UIImage *)imageFromCacheForKey:(nullable NSString *)key options:(SDImageCacheOptions)options context:(nullable SDWebImageContext *)context; + +#pragma mark - Remove Ops + +/** + * Asynchronously remove the image from memory and disk cache + * + * @param key The unique image cache key + * @param completion A block that should be executed after the image has been removed (optional) + */ +- (void)removeImageForKey:(nullable NSString *)key withCompletion:(nullable SDWebImageNoParamsBlock)completion; + +/** + * Asynchronously remove the image from memory and optionally disk cache + * + * @param key The unique image cache key + * @param fromDisk Also remove cache entry from disk if YES. If NO, the completion block is called synchronously + * @param completion A block that should be executed after the image has been removed (optional) + */ +- (void)removeImageForKey:(nullable NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(nullable SDWebImageNoParamsBlock)completion; + +/** + Synchronously remove the image from memory cache. + + @param key The unique image cache key + */ +- (void)removeImageFromMemoryForKey:(nullable NSString *)key; + +/** + Synchronously remove the image from disk cache. + + @param key The unique image cache key + */ +- (void)removeImageFromDiskForKey:(nullable NSString *)key; + +#pragma mark - Cache clean Ops + +/** + * Synchronously Clear all memory cached images + */ +- (void)clearMemory; + +/** + * Asynchronously clear all disk cached images. Non-blocking method - returns immediately. + * @param completion A block that should be executed after cache expiration completes (optional) + */ +- (void)clearDiskOnCompletion:(nullable SDWebImageNoParamsBlock)completion; + +/** + * Asynchronously remove all expired cached image from disk. Non-blocking method - returns immediately. + * @param completionBlock A block that should be executed after cache expiration completes (optional) + */ +- (void)deleteOldFilesWithCompletionBlock:(nullable SDWebImageNoParamsBlock)completionBlock; + +#pragma mark - Cache Info + +/** + * Get the total bytes size of images in the disk cache + */ +- (NSUInteger)totalDiskSize; + +/** + * Get the number of images in the disk cache + */ +- (NSUInteger)totalDiskCount; + +/** + * Asynchronously calculate the disk cache's size. + */ +- (void)calculateSizeWithCompletionBlock:(nullable SDImageCacheCalculateSizeBlock)completionBlock; + +@end + +/** + * SDImageCache is the built-in image cache implementation for web image manager. It adopts `SDImageCache` protocol to provide the function for web image manager to use for image loading process. + */ +@interface SDImageCache (SDImageCache) + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDImageCache.m b/Pods/SDWebImage/SDWebImage/Core/SDImageCache.m new file mode 100644 index 0000000..8c33461 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDImageCache.m @@ -0,0 +1,1064 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDImageCache.h" +#import "SDInternalMacros.h" +#import "NSImage+Compatibility.h" +#import "SDImageCodersManager.h" +#import "SDImageCoderHelper.h" +#import "SDAnimatedImage.h" +#import "UIImage+MemoryCacheCost.h" +#import "UIImage+Metadata.h" +#import "UIImage+ExtendedCacheData.h" +#import "SDCallbackQueue.h" +#import "SDImageTransformer.h" // TODO, remove this + +// TODO, remove this +static BOOL SDIsThumbnailKey(NSString *key) { + if ([key rangeOfString:@"-Thumbnail("].location != NSNotFound) { + return YES; + } + return NO; +} + +@interface SDImageCacheToken () + +@property (nonatomic, strong, nullable, readwrite) NSString *key; +@property (nonatomic, assign, getter=isCancelled) BOOL cancelled; +@property (nonatomic, copy, nullable) SDImageCacheQueryCompletionBlock doneBlock; +@property (nonatomic, strong, nullable) SDCallbackQueue *callbackQueue; + +@end + +@implementation SDImageCacheToken + +-(instancetype)initWithDoneBlock:(nullable SDImageCacheQueryCompletionBlock)doneBlock { + self = [super init]; + if (self) { + self.doneBlock = doneBlock; + } + return self; +} + +- (void)cancel { + @synchronized (self) { + if (self.isCancelled) { + return; + } + self.cancelled = YES; + + SDImageCacheQueryCompletionBlock doneBlock = self.doneBlock; + self.doneBlock = nil; + if (doneBlock) { + [(self.callbackQueue ?: SDCallbackQueue.mainQueue) async:^{ + doneBlock(nil, nil, SDImageCacheTypeNone); + }]; + } + } +} + +@end + +static NSString * _defaultDiskCacheDirectory; + +@interface SDImageCache () + +#pragma mark - Properties +@property (nonatomic, strong, readwrite, nonnull) id memoryCache; +@property (nonatomic, strong, readwrite, nonnull) id diskCache; +@property (nonatomic, copy, readwrite, nonnull) SDImageCacheConfig *config; +@property (nonatomic, copy, readwrite, nonnull) NSString *diskCachePath; +@property (nonatomic, strong, nonnull) dispatch_queue_t ioQueue; + +@end + + +@implementation SDImageCache + +#pragma mark - Singleton, init, dealloc + ++ (nonnull instancetype)sharedImageCache { + static dispatch_once_t once; + static id instance; + dispatch_once(&once, ^{ + instance = [self new]; + }); + return instance; +} + ++ (NSString *)defaultDiskCacheDirectory { + if (!_defaultDiskCacheDirectory) { + _defaultDiskCacheDirectory = [[self userCacheDirectory] stringByAppendingPathComponent:@"com.hackemist.SDImageCache"]; + } + return _defaultDiskCacheDirectory; +} + ++ (void)setDefaultDiskCacheDirectory:(NSString *)defaultDiskCacheDirectory { + _defaultDiskCacheDirectory = [defaultDiskCacheDirectory copy]; +} + +- (instancetype)init { + return [self initWithNamespace:@"default"]; +} + +- (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns { + return [self initWithNamespace:ns diskCacheDirectory:nil]; +} + +- (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns + diskCacheDirectory:(nullable NSString *)directory { + return [self initWithNamespace:ns diskCacheDirectory:directory config:SDImageCacheConfig.defaultCacheConfig]; +} + +- (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns + diskCacheDirectory:(nullable NSString *)directory + config:(nullable SDImageCacheConfig *)config { + if ((self = [super init])) { + NSAssert(ns, @"Cache namespace should not be nil"); + + if (!config) { + config = SDImageCacheConfig.defaultCacheConfig; + } + _config = [config copy]; + + // Create IO queue + dispatch_queue_attr_t ioQueueAttributes = _config.ioQueueAttributes; + _ioQueue = dispatch_queue_create("com.hackemist.SDImageCache.ioQueue", ioQueueAttributes); + NSAssert(_ioQueue, @"The IO queue should not be nil. Your configured `ioQueueAttributes` may be wrong"); + + // Init the memory cache + NSAssert([config.memoryCacheClass conformsToProtocol:@protocol(SDMemoryCache)], @"Custom memory cache class must conform to `SDMemoryCache` protocol"); + _memoryCache = [[config.memoryCacheClass alloc] initWithConfig:_config]; + + // Init the disk cache + if (!directory) { + // Use default disk cache directory + directory = [self.class defaultDiskCacheDirectory]; + } + _diskCachePath = [directory stringByAppendingPathComponent:ns]; + + NSAssert([config.diskCacheClass conformsToProtocol:@protocol(SDDiskCache)], @"Custom disk cache class must conform to `SDDiskCache` protocol"); + _diskCache = [[config.diskCacheClass alloc] initWithCachePath:_diskCachePath config:_config]; + + // Check and migrate disk cache directory if need + [self migrateDiskCacheDirectory]; + +#if SD_UIKIT + // Subscribe to app events + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(applicationWillTerminate:) + name:UIApplicationWillTerminateNotification + object:nil]; + + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(applicationDidEnterBackground:) + name:UIApplicationDidEnterBackgroundNotification + object:nil]; +#endif +#if SD_MAC + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(applicationWillTerminate:) + name:NSApplicationWillTerminateNotification + object:nil]; +#endif + } + + return self; +} + +- (void)dealloc { + [[NSNotificationCenter defaultCenter] removeObserver:self]; +} + +#pragma mark - Cache paths + +- (nullable NSString *)cachePathForKey:(nullable NSString *)key { + if (!key) { + return nil; + } + return [self.diskCache cachePathForKey:key]; +} + ++ (nullable NSString *)userCacheDirectory { + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); + return paths.firstObject; +} + +- (void)migrateDiskCacheDirectory { + if ([self.diskCache isKindOfClass:[SDDiskCache class]]) { + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + // ~/Library/Caches/com.hackemist.SDImageCache/default/ + NSString *newDefaultPath = [[[self.class userCacheDirectory] stringByAppendingPathComponent:@"com.hackemist.SDImageCache"] stringByAppendingPathComponent:@"default"]; + // ~/Library/Caches/default/com.hackemist.SDWebImageCache.default/ + NSString *oldDefaultPath = [[[self.class userCacheDirectory] stringByAppendingPathComponent:@"default"] stringByAppendingPathComponent:@"com.hackemist.SDWebImageCache.default"]; + dispatch_async(self.ioQueue, ^{ + [((SDDiskCache *)self.diskCache) moveCacheDirectoryFromPath:oldDefaultPath toPath:newDefaultPath]; + }); + }); + } +} + +#pragma mark - Store Ops + +- (void)storeImage:(nullable UIImage *)image + forKey:(nullable NSString *)key + completion:(nullable SDWebImageNoParamsBlock)completionBlock { + [self storeImage:image imageData:nil forKey:key options:0 context:nil cacheType:SDImageCacheTypeAll completion:completionBlock]; +} + +- (void)storeImage:(nullable UIImage *)image + forKey:(nullable NSString *)key + toDisk:(BOOL)toDisk + completion:(nullable SDWebImageNoParamsBlock)completionBlock { + [self storeImage:image imageData:nil forKey:key options:0 context:nil cacheType:(toDisk ? SDImageCacheTypeAll : SDImageCacheTypeMemory) completion:completionBlock]; +} + +- (void)storeImageData:(nullable NSData *)imageData + forKey:(nullable NSString *)key + completion:(nullable SDWebImageNoParamsBlock)completionBlock { + [self storeImage:nil imageData:imageData forKey:key options:0 context:nil cacheType:SDImageCacheTypeAll completion:completionBlock]; +} + +- (void)storeImage:(nullable UIImage *)image + imageData:(nullable NSData *)imageData + forKey:(nullable NSString *)key + toDisk:(BOOL)toDisk + completion:(nullable SDWebImageNoParamsBlock)completionBlock { + [self storeImage:image imageData:imageData forKey:key options:0 context:nil cacheType:(toDisk ? SDImageCacheTypeAll : SDImageCacheTypeMemory) completion:completionBlock]; +} + +- (void)storeImage:(nullable UIImage *)image + imageData:(nullable NSData *)imageData + forKey:(nullable NSString *)key + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + cacheType:(SDImageCacheType)cacheType + completion:(nullable SDWebImageNoParamsBlock)completionBlock { + if ((!image && !imageData) || !key) { + if (completionBlock) { + completionBlock(); + } + return; + } + BOOL toMemory = cacheType == SDImageCacheTypeMemory || cacheType == SDImageCacheTypeAll; + BOOL toDisk = cacheType == SDImageCacheTypeDisk || cacheType == SDImageCacheTypeAll; + // if memory cache is enabled + if (image && toMemory && self.config.shouldCacheImagesInMemory) { + NSUInteger cost = image.sd_memoryCost; + [self.memoryCache setObject:image forKey:key cost:cost]; + } + + if (!toDisk) { + if (completionBlock) { + completionBlock(); + } + return; + } + NSData *data = imageData; + if (!data && [image respondsToSelector:@selector(animatedImageData)]) { + // If image is custom animated image class, prefer its original animated data + data = [((id)image) animatedImageData]; + } + SDCallbackQueue *queue = context[SDWebImageContextCallbackQueue]; + if (!data && image) { + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ + // Check image's associated image format, may return .undefined + SDImageFormat format = image.sd_imageFormat; + if (format == SDImageFormatUndefined) { + // If image is animated, use GIF (APNG may be better, but has bugs before macOS 10.14) + if (image.sd_imageFrameCount > 1) { + format = SDImageFormatGIF; + } else { + // If we do not have any data to detect image format, check whether it contains alpha channel to use PNG or JPEG format + format = [SDImageCoderHelper CGImageContainsAlpha:image.CGImage] ? SDImageFormatPNG : SDImageFormatJPEG; + } + } + NSData *encodedData = [[SDImageCodersManager sharedManager] encodedDataWithImage:image format:format options:context[SDWebImageContextImageEncodeOptions]]; + dispatch_async(self.ioQueue, ^{ + [self _storeImageDataToDisk:encodedData forKey:key]; + [self _archivedDataWithImage:image forKey:key]; + if (completionBlock) { + [(queue ?: SDCallbackQueue.mainQueue) async:^{ + completionBlock(); + }]; + } + }); + }); + } else { + dispatch_async(self.ioQueue, ^{ + [self _storeImageDataToDisk:data forKey:key]; + [self _archivedDataWithImage:image forKey:key]; + if (completionBlock) { + [(queue ?: SDCallbackQueue.mainQueue) async:^{ + completionBlock(); + }]; + } + }); + } +} + +- (void)_archivedDataWithImage:(UIImage *)image forKey:(NSString *)key { + if (!image || !key) { + return; + } + // Check extended data + id extendedObject = image.sd_extendedObject; + if (![extendedObject conformsToProtocol:@protocol(NSCoding)]) { + return; + } + NSData *extendedData; + if (@available(iOS 11, tvOS 11, macOS 10.13, watchOS 4, *)) { + NSError *error; + extendedData = [NSKeyedArchiver archivedDataWithRootObject:extendedObject requiringSecureCoding:NO error:&error]; + if (error) { + SD_LOG("NSKeyedArchiver archive failed with error: %@", error); + } + } else { + @try { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + extendedData = [NSKeyedArchiver archivedDataWithRootObject:extendedObject]; +#pragma clang diagnostic pop + } @catch (NSException *exception) { + SD_LOG("NSKeyedArchiver archive failed with exception: %@", exception); + } + } + if (extendedData) { + [self.diskCache setExtendedData:extendedData forKey:key]; + } +} + +- (void)storeImageToMemory:(UIImage *)image forKey:(NSString *)key { + if (!image || !key) { + return; + } + NSUInteger cost = image.sd_memoryCost; + [self.memoryCache setObject:image forKey:key cost:cost]; +} + +- (void)storeImageDataToDisk:(nullable NSData *)imageData + forKey:(nullable NSString *)key { + if (!imageData || !key) { + return; + } + + dispatch_sync(self.ioQueue, ^{ + [self _storeImageDataToDisk:imageData forKey:key]; + }); +} + +// Make sure to call from io queue by caller +- (void)_storeImageDataToDisk:(nullable NSData *)imageData forKey:(nullable NSString *)key { + if (!imageData || !key) { + return; + } + + [self.diskCache setData:imageData forKey:key]; +} + +#pragma mark - Query and Retrieve Ops + +- (void)diskImageExistsWithKey:(nullable NSString *)key completion:(nullable SDImageCacheCheckCompletionBlock)completionBlock { + dispatch_async(self.ioQueue, ^{ + BOOL exists = [self _diskImageDataExistsWithKey:key]; + if (completionBlock) { + dispatch_async(dispatch_get_main_queue(), ^{ + completionBlock(exists); + }); + } + }); +} + +- (BOOL)diskImageDataExistsWithKey:(nullable NSString *)key { + if (!key) { + return NO; + } + + __block BOOL exists = NO; + dispatch_sync(self.ioQueue, ^{ + exists = [self _diskImageDataExistsWithKey:key]; + }); + + return exists; +} + +// Make sure to call from io queue by caller +- (BOOL)_diskImageDataExistsWithKey:(nullable NSString *)key { + if (!key) { + return NO; + } + + return [self.diskCache containsDataForKey:key]; +} + +- (void)diskImageDataQueryForKey:(NSString *)key completion:(SDImageCacheQueryDataCompletionBlock)completionBlock { + dispatch_async(self.ioQueue, ^{ + NSData *imageData = [self diskImageDataBySearchingAllPathsForKey:key]; + if (completionBlock) { + dispatch_async(dispatch_get_main_queue(), ^{ + completionBlock(imageData); + }); + } + }); +} + +- (nullable NSData *)diskImageDataForKey:(nullable NSString *)key { + if (!key) { + return nil; + } + __block NSData *imageData = nil; + dispatch_sync(self.ioQueue, ^{ + imageData = [self diskImageDataBySearchingAllPathsForKey:key]; + }); + + return imageData; +} + +- (nullable UIImage *)imageFromMemoryCacheForKey:(nullable NSString *)key { + return [self.memoryCache objectForKey:key]; +} + +- (nullable UIImage *)imageFromDiskCacheForKey:(nullable NSString *)key { + return [self imageFromDiskCacheForKey:key options:0 context:nil]; +} + +- (nullable UIImage *)imageFromDiskCacheForKey:(nullable NSString *)key options:(SDImageCacheOptions)options context:(nullable SDWebImageContext *)context { + if (!key) { + return nil; + } + NSData *data = [self diskImageDataForKey:key]; + UIImage *diskImage = [self diskImageForKey:key data:data options:options context:context]; + + BOOL shouldCacheToMemory = YES; + if (context[SDWebImageContextStoreCacheType]) { + SDImageCacheType cacheType = [context[SDWebImageContextStoreCacheType] integerValue]; + shouldCacheToMemory = (cacheType == SDImageCacheTypeAll || cacheType == SDImageCacheTypeMemory); + } + if (shouldCacheToMemory) { + // check if we need sync logic + [self _syncDiskToMemoryWithImage:diskImage forKey:key]; + } + + return diskImage; +} + +- (nullable UIImage *)imageFromCacheForKey:(nullable NSString *)key { + return [self imageFromCacheForKey:key options:0 context:nil]; +} + +- (nullable UIImage *)imageFromCacheForKey:(nullable NSString *)key options:(SDImageCacheOptions)options context:(nullable SDWebImageContext *)context { + // First check the in-memory cache... + UIImage *image = [self imageFromMemoryCacheForKey:key]; + if (image) { + if (options & SDImageCacheDecodeFirstFrameOnly) { + // Ensure static image + if (image.sd_imageFrameCount > 1) { +#if SD_MAC + image = [[NSImage alloc] initWithCGImage:image.CGImage scale:image.scale orientation:kCGImagePropertyOrientationUp]; +#else + image = [[UIImage alloc] initWithCGImage:image.CGImage scale:image.scale orientation:image.imageOrientation]; +#endif + } + } else if (options & SDImageCacheMatchAnimatedImageClass) { + // Check image class matching + Class animatedImageClass = image.class; + Class desiredImageClass = context[SDWebImageContextAnimatedImageClass]; + if (desiredImageClass && ![animatedImageClass isSubclassOfClass:desiredImageClass]) { + image = nil; + } + } + } + + // Since we don't need to query imageData, return image if exist + if (image) { + return image; + } + + // Second check the disk cache... + image = [self imageFromDiskCacheForKey:key options:options context:context]; + return image; +} + +- (nullable NSData *)diskImageDataBySearchingAllPathsForKey:(nullable NSString *)key { + if (!key) { + return nil; + } + + NSData *data = [self.diskCache dataForKey:key]; + if (data) { + return data; + } + + // Addtional cache path for custom pre-load cache + if (self.additionalCachePathBlock) { + NSString *filePath = self.additionalCachePathBlock(key); + if (filePath) { + data = [NSData dataWithContentsOfFile:filePath options:self.config.diskCacheReadingOptions error:nil]; + } + } + + return data; +} + +- (nullable UIImage *)diskImageForKey:(nullable NSString *)key { + if (!key) { + return nil; + } + NSData *data = [self diskImageDataForKey:key]; + return [self diskImageForKey:key data:data options:0 context:nil]; +} + +- (nullable UIImage *)diskImageForKey:(nullable NSString *)key data:(nullable NSData *)data options:(SDImageCacheOptions)options context:(SDWebImageContext *)context { + if (!data) { + return nil; + } + UIImage *image = SDImageCacheDecodeImageData(data, key, [[self class] imageOptionsFromCacheOptions:options], context); + [self _unarchiveObjectWithImage:image forKey:key]; + return image; +} + +- (void)_syncDiskToMemoryWithImage:(UIImage *)diskImage forKey:(NSString *)key { + // earily check + if (!self.config.shouldCacheImagesInMemory) { + return; + } + if (!diskImage) { + return; + } + // The disk -> memory sync logic, which should only store thumbnail image with thumbnail key + // However, caller (like SDWebImageManager) will query full key, with thumbnail size, and get thubmnail image + // We should add a check here, currently it's a hack + if (diskImage.sd_isThumbnail && !SDIsThumbnailKey(key)) { + SDImageCoderOptions *options = diskImage.sd_decodeOptions; + CGSize thumbnailSize = CGSizeZero; + NSValue *thumbnailSizeValue = options[SDImageCoderDecodeThumbnailPixelSize]; + if (thumbnailSizeValue != nil) { + #if SD_MAC + thumbnailSize = thumbnailSizeValue.sizeValue; + #else + thumbnailSize = thumbnailSizeValue.CGSizeValue; + #endif + } + BOOL preserveAspectRatio = YES; + NSNumber *preserveAspectRatioValue = options[SDImageCoderDecodePreserveAspectRatio]; + if (preserveAspectRatioValue != nil) { + preserveAspectRatio = preserveAspectRatioValue.boolValue; + } + // Calculate the actual thumbnail key + NSString *thumbnailKey = SDThumbnailedKeyForKey(key, thumbnailSize, preserveAspectRatio); + // Override the sync key + key = thumbnailKey; + } + NSUInteger cost = diskImage.sd_memoryCost; + [self.memoryCache setObject:diskImage forKey:key cost:cost]; +} + +- (void)_unarchiveObjectWithImage:(UIImage *)image forKey:(NSString *)key { + if (!image || !key) { + return; + } + // Check extended data + NSData *extendedData = [self.diskCache extendedDataForKey:key]; + if (!extendedData) { + return; + } + id extendedObject; + if (@available(iOS 11, tvOS 11, macOS 10.13, watchOS 4, *)) { + NSError *error; + NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingFromData:extendedData error:&error]; + unarchiver.requiresSecureCoding = NO; + extendedObject = [unarchiver decodeTopLevelObjectForKey:NSKeyedArchiveRootObjectKey error:&error]; + if (error) { + SD_LOG("NSKeyedUnarchiver unarchive failed with error: %@", error); + } + } else { + @try { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + extendedObject = [NSKeyedUnarchiver unarchiveObjectWithData:extendedData]; +#pragma clang diagnostic pop + } @catch (NSException *exception) { + SD_LOG("NSKeyedUnarchiver unarchive failed with exception: %@", exception); + } + } + image.sd_extendedObject = extendedObject; +} + +- (nullable SDImageCacheToken *)queryCacheOperationForKey:(NSString *)key done:(SDImageCacheQueryCompletionBlock)doneBlock { + return [self queryCacheOperationForKey:key options:0 done:doneBlock]; +} + +- (nullable SDImageCacheToken *)queryCacheOperationForKey:(NSString *)key options:(SDImageCacheOptions)options done:(SDImageCacheQueryCompletionBlock)doneBlock { + return [self queryCacheOperationForKey:key options:options context:nil done:doneBlock]; +} + +- (nullable SDImageCacheToken *)queryCacheOperationForKey:(nullable NSString *)key options:(SDImageCacheOptions)options context:(nullable SDWebImageContext *)context done:(nullable SDImageCacheQueryCompletionBlock)doneBlock { + return [self queryCacheOperationForKey:key options:options context:context cacheType:SDImageCacheTypeAll done:doneBlock]; +} + +- (nullable SDImageCacheToken *)queryCacheOperationForKey:(nullable NSString *)key options:(SDImageCacheOptions)options context:(nullable SDWebImageContext *)context cacheType:(SDImageCacheType)queryCacheType done:(nullable SDImageCacheQueryCompletionBlock)doneBlock { + if (!key) { + if (doneBlock) { + doneBlock(nil, nil, SDImageCacheTypeNone); + } + return nil; + } + // Invalid cache type + if (queryCacheType == SDImageCacheTypeNone) { + if (doneBlock) { + doneBlock(nil, nil, SDImageCacheTypeNone); + } + return nil; + } + + // First check the in-memory cache... + UIImage *image; + BOOL shouldQueryDiskOnly = (queryCacheType == SDImageCacheTypeDisk); + if (!shouldQueryDiskOnly) { + image = [self imageFromMemoryCacheForKey:key]; + } + + if (image) { + if (options & SDImageCacheDecodeFirstFrameOnly) { + // Ensure static image + if (image.sd_imageFrameCount > 1) { +#if SD_MAC + image = [[NSImage alloc] initWithCGImage:image.CGImage scale:image.scale orientation:kCGImagePropertyOrientationUp]; +#else + image = [[UIImage alloc] initWithCGImage:image.CGImage scale:image.scale orientation:image.imageOrientation]; +#endif + } + } else if (options & SDImageCacheMatchAnimatedImageClass) { + // Check image class matching + Class animatedImageClass = image.class; + Class desiredImageClass = context[SDWebImageContextAnimatedImageClass]; + if (desiredImageClass && ![animatedImageClass isSubclassOfClass:desiredImageClass]) { + image = nil; + } + } + } + + BOOL shouldQueryMemoryOnly = (queryCacheType == SDImageCacheTypeMemory) || (image && !(options & SDImageCacheQueryMemoryData)); + if (shouldQueryMemoryOnly) { + if (doneBlock) { + doneBlock(image, nil, SDImageCacheTypeMemory); + } + return nil; + } + + // Second check the disk cache... + SDCallbackQueue *queue = context[SDWebImageContextCallbackQueue]; + SDImageCacheToken *operation = [[SDImageCacheToken alloc] initWithDoneBlock:doneBlock]; + operation.key = key; + operation.callbackQueue = queue; + // Check whether we need to synchronously query disk + // 1. in-memory cache hit & memoryDataSync + // 2. in-memory cache miss & diskDataSync + BOOL shouldQueryDiskSync = ((image && options & SDImageCacheQueryMemoryDataSync) || + (!image && options & SDImageCacheQueryDiskDataSync)); + NSData* (^queryDiskDataBlock)(void) = ^NSData* { + @synchronized (operation) { + if (operation.isCancelled) { + return nil; + } + } + + return [self diskImageDataBySearchingAllPathsForKey:key]; + }; + + UIImage* (^queryDiskImageBlock)(NSData*) = ^UIImage*(NSData* diskData) { + @synchronized (operation) { + if (operation.isCancelled) { + return nil; + } + } + + UIImage *diskImage; + if (image) { + // the image is from in-memory cache, but need image data + diskImage = image; + } else if (diskData) { + // the image memory cache miss, need image data and image + BOOL shouldCacheToMemory = YES; + if (context[SDWebImageContextStoreCacheType]) { + SDImageCacheType cacheType = [context[SDWebImageContextStoreCacheType] integerValue]; + shouldCacheToMemory = (cacheType == SDImageCacheTypeAll || cacheType == SDImageCacheTypeMemory); + } + // Special case: If user query image in list for the same URL, to avoid decode and write **same** image object into disk cache multiple times, we query and check memory cache here again. See: #3523 + // This because disk operation can be async, previous sync check of `memory cache miss`, does not gurantee current check of `memory cache miss` + if (!shouldQueryDiskSync) { + // First check the in-memory cache... + if (!shouldQueryDiskOnly) { + diskImage = [self imageFromMemoryCacheForKey:key]; + } + } + // decode image data only if in-memory cache missed + if (!diskImage) { + diskImage = [self diskImageForKey:key data:diskData options:options context:context]; + // check if we need sync logic + if (shouldCacheToMemory) { + [self _syncDiskToMemoryWithImage:diskImage forKey:key]; + } + } + } + return diskImage; + }; + + // Query in ioQueue to keep IO-safe + if (shouldQueryDiskSync) { + __block NSData* diskData; + __block UIImage* diskImage; + dispatch_sync(self.ioQueue, ^{ + diskData = queryDiskDataBlock(); + diskImage = queryDiskImageBlock(diskData); + }); + if (doneBlock) { + doneBlock(diskImage, diskData, SDImageCacheTypeDisk); + } + } else { + dispatch_async(self.ioQueue, ^{ + NSData* diskData = queryDiskDataBlock(); + UIImage* diskImage = queryDiskImageBlock(diskData); + @synchronized (operation) { + if (operation.isCancelled) { + return; + } + } + if (doneBlock) { + [(queue ?: SDCallbackQueue.mainQueue) async:^{ + // Dispatch from IO queue to main queue need time, user may call cancel during the dispatch timing + // This check is here to avoid double callback (one is from `SDImageCacheToken` in sync) + @synchronized (operation) { + if (operation.isCancelled) { + return; + } + } + doneBlock(diskImage, diskData, SDImageCacheTypeDisk); + }]; + } + }); + } + + return operation; +} + +#pragma mark - Remove Ops + +- (void)removeImageForKey:(nullable NSString *)key withCompletion:(nullable SDWebImageNoParamsBlock)completion { + [self removeImageForKey:key fromDisk:YES withCompletion:completion]; +} + +- (void)removeImageForKey:(nullable NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(nullable SDWebImageNoParamsBlock)completion { + [self removeImageForKey:key fromMemory:YES fromDisk:fromDisk withCompletion:completion]; +} + +- (void)removeImageForKey:(nullable NSString *)key fromMemory:(BOOL)fromMemory fromDisk:(BOOL)fromDisk withCompletion:(nullable SDWebImageNoParamsBlock)completion { + if (!key) { + return; + } + + if (fromMemory && self.config.shouldCacheImagesInMemory) { + [self.memoryCache removeObjectForKey:key]; + } + + if (fromDisk) { + dispatch_async(self.ioQueue, ^{ + [self.diskCache removeDataForKey:key]; + + if (completion) { + dispatch_async(dispatch_get_main_queue(), ^{ + completion(); + }); + } + }); + } else if (completion) { + completion(); + } +} + +- (void)removeImageFromMemoryForKey:(NSString *)key { + if (!key) { + return; + } + + [self.memoryCache removeObjectForKey:key]; +} + +- (void)removeImageFromDiskForKey:(NSString *)key { + if (!key) { + return; + } + dispatch_sync(self.ioQueue, ^{ + [self _removeImageFromDiskForKey:key]; + }); +} + +// Make sure to call from io queue by caller +- (void)_removeImageFromDiskForKey:(NSString *)key { + if (!key) { + return; + } + + [self.diskCache removeDataForKey:key]; +} + +#pragma mark - Cache clean Ops + +- (void)clearMemory { + [self.memoryCache removeAllObjects]; +} + +- (void)clearDiskOnCompletion:(nullable SDWebImageNoParamsBlock)completion { + dispatch_async(self.ioQueue, ^{ + [self.diskCache removeAllData]; + if (completion) { + dispatch_async(dispatch_get_main_queue(), ^{ + completion(); + }); + } + }); +} + +- (void)deleteOldFilesWithCompletionBlock:(nullable SDWebImageNoParamsBlock)completionBlock { + dispatch_async(self.ioQueue, ^{ + [self.diskCache removeExpiredData]; + if (completionBlock) { + dispatch_async(dispatch_get_main_queue(), ^{ + completionBlock(); + }); + } + }); +} + +#pragma mark - UIApplicationWillTerminateNotification + +#if SD_UIKIT || SD_MAC +- (void)applicationWillTerminate:(NSNotification *)notification { + // On iOS/macOS, the async opeartion to remove exipred data will be terminated quickly + // Try using the sync operation to ensure we reomve the exipred data + if (!self.config.shouldRemoveExpiredDataWhenTerminate) { + return; + } + dispatch_sync(self.ioQueue, ^{ + [self.diskCache removeExpiredData]; + }); +} +#endif + +#pragma mark - UIApplicationDidEnterBackgroundNotification + +#if SD_UIKIT +- (void)applicationDidEnterBackground:(NSNotification *)notification { + if (!self.config.shouldRemoveExpiredDataWhenEnterBackground) { + return; + } + Class UIApplicationClass = NSClassFromString(@"UIApplication"); + if(!UIApplicationClass || ![UIApplicationClass respondsToSelector:@selector(sharedApplication)]) { + return; + } + UIApplication *application = [UIApplication performSelector:@selector(sharedApplication)]; + __block UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithExpirationHandler:^{ + // Clean up any unfinished task business by marking where you + // stopped or ending the task outright. + [application endBackgroundTask:bgTask]; + bgTask = UIBackgroundTaskInvalid; + }]; + + // Start the long-running task and return immediately. + [self deleteOldFilesWithCompletionBlock:^{ + [application endBackgroundTask:bgTask]; + bgTask = UIBackgroundTaskInvalid; + }]; +} +#endif + +#pragma mark - Cache Info + +- (NSUInteger)totalDiskSize { + __block NSUInteger size = 0; + dispatch_sync(self.ioQueue, ^{ + size = [self.diskCache totalSize]; + }); + return size; +} + +- (NSUInteger)totalDiskCount { + __block NSUInteger count = 0; + dispatch_sync(self.ioQueue, ^{ + count = [self.diskCache totalCount]; + }); + return count; +} + +- (void)calculateSizeWithCompletionBlock:(nullable SDImageCacheCalculateSizeBlock)completionBlock { + dispatch_async(self.ioQueue, ^{ + NSUInteger fileCount = [self.diskCache totalCount]; + NSUInteger totalSize = [self.diskCache totalSize]; + if (completionBlock) { + dispatch_async(dispatch_get_main_queue(), ^{ + completionBlock(fileCount, totalSize); + }); + } + }); +} + +#pragma mark - Helper +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" ++ (SDWebImageOptions)imageOptionsFromCacheOptions:(SDImageCacheOptions)cacheOptions { + SDWebImageOptions options = 0; + if (cacheOptions & SDImageCacheScaleDownLargeImages) options |= SDWebImageScaleDownLargeImages; + if (cacheOptions & SDImageCacheDecodeFirstFrameOnly) options |= SDWebImageDecodeFirstFrameOnly; + if (cacheOptions & SDImageCachePreloadAllFrames) options |= SDWebImagePreloadAllFrames; + if (cacheOptions & SDImageCacheAvoidDecodeImage) options |= SDWebImageAvoidDecodeImage; + if (cacheOptions & SDImageCacheMatchAnimatedImageClass) options |= SDWebImageMatchAnimatedImageClass; + + return options; +} +#pragma clang diagnostic pop + +@end + +@implementation SDImageCache (SDImageCache) + +#pragma mark - SDImageCache + +- (id)queryImageForKey:(NSString *)key options:(SDWebImageOptions)options context:(nullable SDWebImageContext *)context completion:(nullable SDImageCacheQueryCompletionBlock)completionBlock { + return [self queryImageForKey:key options:options context:context cacheType:SDImageCacheTypeAll completion:completionBlock]; +} + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +- (id)queryImageForKey:(NSString *)key options:(SDWebImageOptions)options context:(nullable SDWebImageContext *)context cacheType:(SDImageCacheType)cacheType completion:(nullable SDImageCacheQueryCompletionBlock)completionBlock { + SDImageCacheOptions cacheOptions = 0; + if (options & SDWebImageQueryMemoryData) cacheOptions |= SDImageCacheQueryMemoryData; + if (options & SDWebImageQueryMemoryDataSync) cacheOptions |= SDImageCacheQueryMemoryDataSync; + if (options & SDWebImageQueryDiskDataSync) cacheOptions |= SDImageCacheQueryDiskDataSync; + if (options & SDWebImageScaleDownLargeImages) cacheOptions |= SDImageCacheScaleDownLargeImages; + if (options & SDWebImageAvoidDecodeImage) cacheOptions |= SDImageCacheAvoidDecodeImage; + if (options & SDWebImageDecodeFirstFrameOnly) cacheOptions |= SDImageCacheDecodeFirstFrameOnly; + if (options & SDWebImagePreloadAllFrames) cacheOptions |= SDImageCachePreloadAllFrames; + if (options & SDWebImageMatchAnimatedImageClass) cacheOptions |= SDImageCacheMatchAnimatedImageClass; + + return [self queryCacheOperationForKey:key options:cacheOptions context:context cacheType:cacheType done:completionBlock]; +} +#pragma clang diagnostic pop + +- (void)storeImage:(UIImage *)image imageData:(NSData *)imageData forKey:(nullable NSString *)key cacheType:(SDImageCacheType)cacheType completion:(nullable SDWebImageNoParamsBlock)completionBlock { + [self storeImage:image imageData:imageData forKey:key options:0 context:nil cacheType:cacheType completion:completionBlock]; +} + +- (void)removeImageForKey:(NSString *)key cacheType:(SDImageCacheType)cacheType completion:(nullable SDWebImageNoParamsBlock)completionBlock { + switch (cacheType) { + case SDImageCacheTypeNone: { + [self removeImageForKey:key fromMemory:NO fromDisk:NO withCompletion:completionBlock]; + } + break; + case SDImageCacheTypeMemory: { + [self removeImageForKey:key fromMemory:YES fromDisk:NO withCompletion:completionBlock]; + } + break; + case SDImageCacheTypeDisk: { + [self removeImageForKey:key fromMemory:NO fromDisk:YES withCompletion:completionBlock]; + } + break; + case SDImageCacheTypeAll: { + [self removeImageForKey:key fromMemory:YES fromDisk:YES withCompletion:completionBlock]; + } + break; + default: { + if (completionBlock) { + completionBlock(); + } + } + break; + } +} + +- (void)containsImageForKey:(NSString *)key cacheType:(SDImageCacheType)cacheType completion:(nullable SDImageCacheContainsCompletionBlock)completionBlock { + switch (cacheType) { + case SDImageCacheTypeNone: { + if (completionBlock) { + completionBlock(SDImageCacheTypeNone); + } + } + break; + case SDImageCacheTypeMemory: { + BOOL isInMemoryCache = ([self imageFromMemoryCacheForKey:key] != nil); + if (completionBlock) { + completionBlock(isInMemoryCache ? SDImageCacheTypeMemory : SDImageCacheTypeNone); + } + } + break; + case SDImageCacheTypeDisk: { + [self diskImageExistsWithKey:key completion:^(BOOL isInDiskCache) { + if (completionBlock) { + completionBlock(isInDiskCache ? SDImageCacheTypeDisk : SDImageCacheTypeNone); + } + }]; + } + break; + case SDImageCacheTypeAll: { + BOOL isInMemoryCache = ([self imageFromMemoryCacheForKey:key] != nil); + if (isInMemoryCache) { + if (completionBlock) { + completionBlock(SDImageCacheTypeMemory); + } + return; + } + [self diskImageExistsWithKey:key completion:^(BOOL isInDiskCache) { + if (completionBlock) { + completionBlock(isInDiskCache ? SDImageCacheTypeDisk : SDImageCacheTypeNone); + } + }]; + } + break; + default: + if (completionBlock) { + completionBlock(SDImageCacheTypeNone); + } + break; + } +} + +- (void)clearWithCacheType:(SDImageCacheType)cacheType completion:(SDWebImageNoParamsBlock)completionBlock { + switch (cacheType) { + case SDImageCacheTypeNone: { + if (completionBlock) { + completionBlock(); + } + } + break; + case SDImageCacheTypeMemory: { + [self clearMemory]; + if (completionBlock) { + completionBlock(); + } + } + break; + case SDImageCacheTypeDisk: { + [self clearDiskOnCompletion:completionBlock]; + } + break; + case SDImageCacheTypeAll: { + [self clearMemory]; + [self clearDiskOnCompletion:completionBlock]; + } + break; + default: { + if (completionBlock) { + completionBlock(); + } + } + break; + } +} + +@end + diff --git a/Pods/SDWebImage/SDWebImage/Core/SDImageCacheConfig.h b/Pods/SDWebImage/SDWebImage/Core/SDImageCacheConfig.h new file mode 100644 index 0000000..dace4be --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDImageCacheConfig.h @@ -0,0 +1,153 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" + +/// Image Cache Expire Type +typedef NS_ENUM(NSUInteger, SDImageCacheConfigExpireType) { + /** + * When the image cache is accessed it will update this value + */ + SDImageCacheConfigExpireTypeAccessDate, + /** + * When the image cache is created or modified it will update this value (Default) + */ + SDImageCacheConfigExpireTypeModificationDate, + /** + * When the image cache is created it will update this value + */ + SDImageCacheConfigExpireTypeCreationDate, + /** + * When the image cache is created, modified, renamed, file attribute updated (like permission, xattr) it will update this value + */ + SDImageCacheConfigExpireTypeChangeDate, +}; + +/** + The class contains all the config for image cache + @note This class conform to NSCopying, make sure to add the property in `copyWithZone:` as well. + */ +@interface SDImageCacheConfig : NSObject + +/** + Gets the default cache config used for shared instance or initialization when it does not provide any cache config. Such as `SDImageCache.sharedImageCache`. + @note You can modify the property on default cache config, which can be used for later created cache instance. The already created cache instance does not get affected. + */ +@property (nonatomic, class, readonly, nonnull) SDImageCacheConfig *defaultCacheConfig; + +/** + * Whether or not to disable iCloud backup + * Defaults to YES. + */ +@property (assign, nonatomic) BOOL shouldDisableiCloud; + +/** + * Whether or not to use memory cache + * @note When the memory cache is disabled, the weak memory cache will also be disabled. + * Defaults to YES. + */ +@property (assign, nonatomic) BOOL shouldCacheImagesInMemory; + +/* + * The option to control weak memory cache for images. When enable, `SDImageCache`'s memory cache will use a weak maptable to store the image at the same time when it stored to memory, and get removed at the same time. + * However when memory warning is triggered, since the weak maptable does not hold a strong reference to image instance, even when the memory cache itself is purged, some images which are held strongly by UIImageViews or other live instances can be recovered again, to avoid later re-query from disk cache or network. This may be helpful for the case, for example, when app enter background and memory is purged, cause cell flashing after re-enter foreground. + * When enabling this option, we will sync back the image from weak maptable to strong cache during next time top level `sd_setImage` function call. + * Defaults to NO (YES before 5.12.0 version). You can change this option dynamically. + */ +@property (assign, nonatomic) BOOL shouldUseWeakMemoryCache; + +/** + * Whether or not to remove the expired disk data when application entering the background. (Not works for macOS) + * Defaults to YES. + */ +@property (assign, nonatomic) BOOL shouldRemoveExpiredDataWhenEnterBackground; + +/** + * Whether or not to remove the expired disk data when application been terminated. This operation is processed in sync to ensure clean up. + * Defaults to YES. + */ +@property (assign, nonatomic) BOOL shouldRemoveExpiredDataWhenTerminate; + +/** + * The reading options while reading cache from disk. + * Defaults to 0. You can set this to `NSDataReadingMappedIfSafe` to improve performance. + */ +@property (assign, nonatomic) NSDataReadingOptions diskCacheReadingOptions; + +/** + * The writing options while writing cache to disk. + * Defaults to `NSDataWritingAtomic`. You can set this to `NSDataWritingWithoutOverwriting` to prevent overwriting an existing file. + */ +@property (assign, nonatomic) NSDataWritingOptions diskCacheWritingOptions; + +/** + * The maximum length of time to keep an image in the disk cache, in seconds. + * Setting this to a negative value means no expiring. + * Setting this to zero means that all cached files would be removed when do expiration check. + * Defaults to 1 week. + */ +@property (assign, nonatomic) NSTimeInterval maxDiskAge; + +/** + * The maximum size of the disk cache, in bytes. + * Defaults to 0. Which means there is no cache size limit. + */ +@property (assign, nonatomic) NSUInteger maxDiskSize; + +/** + * The maximum "total cost" of the in-memory image cache. The cost function is the bytes size held in memory. + * @note The memory cost is bytes size in memory, but not simple pixels count. For common ARGB8888 image, one pixel is 4 bytes (32 bits). + * Defaults to 0. Which means there is no memory cost limit. + */ +@property (assign, nonatomic) NSUInteger maxMemoryCost; + +/** + * The maximum number of objects in-memory image cache should hold. + * Defaults to 0. Which means there is no memory count limit. + */ +@property (assign, nonatomic) NSUInteger maxMemoryCount; + +/* + * The attribute which the clear cache will be checked against when clearing the disk cache + * Default is Access Date + */ +@property (assign, nonatomic) SDImageCacheConfigExpireType diskCacheExpireType; + +/** + * The custom file manager for disk cache. Pass nil to let disk cache choose the proper file manager. + * Defaults to nil. + * @note This value does not support dynamic changes. Which means further modification on this value after cache initialized has no effect. + * @note Since `NSFileManager` does not support `NSCopying`. We just pass this by reference during copying. So it's not recommend to set this value on `defaultCacheConfig`. + */ +@property (strong, nonatomic, nullable) NSFileManager *fileManager; + +/** + * The dispatch queue attr for ioQueue. You can config the QoS and concurrent/serial to internal IO queue. The ioQueue is used by SDImageCache to access read/write for disk data. + * Defaults we use `DISPATCH_QUEUE_SERIAL`(NULL) under iOS 10, `DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL` above and equal iOS 10, using serial dispatch queue is to ensure single access for disk data. It's safe but may be slow. + * @note You can override this to use `DISPATCH_QUEUE_CONCURRENT`, use concurrent queue. + * @warning **MAKE SURE** to keep `diskCacheWritingOptions` to use `NSDataWritingAtomic`, or concurrent queue may cause corrupted disk data (because multiple threads read/write same file without atomic is not IO-safe). + * @note This value does not support dynamic changes. Which means further modification on this value after cache initialized has no effect. + */ +@property (strong, nonatomic, nullable) dispatch_queue_attr_t ioQueueAttributes; + +/** + * The custom memory cache class. Provided class instance must conform to `SDMemoryCache` protocol to allow usage. + * Defaults to built-in `SDMemoryCache` class. + * @note This value does not support dynamic changes. Which means further modification on this value after cache initialized has no effect. + */ +@property (assign, nonatomic, nonnull) Class memoryCacheClass; + +/** + * The custom disk cache class. Provided class instance must conform to `SDDiskCache` protocol to allow usage. + * Defaults to built-in `SDDiskCache` class. + * @note This value does not support dynamic changes. Which means further modification on this value after cache initialized has no effect. + */ +@property (assign ,nonatomic, nonnull) Class diskCacheClass; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDImageCacheConfig.m b/Pods/SDWebImage/SDWebImage/Core/SDImageCacheConfig.m new file mode 100644 index 0000000..70402db --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDImageCacheConfig.m @@ -0,0 +1,72 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDImageCacheConfig.h" +#import "SDMemoryCache.h" +#import "SDDiskCache.h" + +static SDImageCacheConfig *_defaultCacheConfig; +static const NSInteger kDefaultCacheMaxDiskAge = 60 * 60 * 24 * 7; // 1 week + +@implementation SDImageCacheConfig + ++ (SDImageCacheConfig *)defaultCacheConfig { + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + _defaultCacheConfig = [SDImageCacheConfig new]; + }); + return _defaultCacheConfig; +} + +- (instancetype)init { + if (self = [super init]) { + _shouldDisableiCloud = YES; + _shouldCacheImagesInMemory = YES; + _shouldUseWeakMemoryCache = NO; + _shouldRemoveExpiredDataWhenEnterBackground = YES; + _shouldRemoveExpiredDataWhenTerminate = YES; + _diskCacheReadingOptions = 0; + _diskCacheWritingOptions = NSDataWritingAtomic; + _maxDiskAge = kDefaultCacheMaxDiskAge; + _maxDiskSize = 0; + _diskCacheExpireType = SDImageCacheConfigExpireTypeAccessDate; + _fileManager = nil; + if (@available(iOS 10.0, tvOS 10.0, macOS 10.12, watchOS 3.0, *)) { + _ioQueueAttributes = DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL; // DISPATCH_AUTORELEASE_FREQUENCY_WORK_ITEM + } else { + _ioQueueAttributes = DISPATCH_QUEUE_SERIAL; // NULL + } + _memoryCacheClass = [SDMemoryCache class]; + _diskCacheClass = [SDDiskCache class]; + } + return self; +} + +- (id)copyWithZone:(NSZone *)zone { + SDImageCacheConfig *config = [[[self class] allocWithZone:zone] init]; + config.shouldDisableiCloud = self.shouldDisableiCloud; + config.shouldCacheImagesInMemory = self.shouldCacheImagesInMemory; + config.shouldUseWeakMemoryCache = self.shouldUseWeakMemoryCache; + config.shouldRemoveExpiredDataWhenEnterBackground = self.shouldRemoveExpiredDataWhenEnterBackground; + config.shouldRemoveExpiredDataWhenTerminate = self.shouldRemoveExpiredDataWhenTerminate; + config.diskCacheReadingOptions = self.diskCacheReadingOptions; + config.diskCacheWritingOptions = self.diskCacheWritingOptions; + config.maxDiskAge = self.maxDiskAge; + config.maxDiskSize = self.maxDiskSize; + config.maxMemoryCost = self.maxMemoryCost; + config.maxMemoryCount = self.maxMemoryCount; + config.diskCacheExpireType = self.diskCacheExpireType; + config.fileManager = self.fileManager; // NSFileManager does not conform to NSCopying, just pass the reference + config.ioQueueAttributes = self.ioQueueAttributes; // Pass the reference + config.memoryCacheClass = self.memoryCacheClass; + config.diskCacheClass = self.diskCacheClass; + + return config; +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDImageCacheDefine.h b/Pods/SDWebImage/SDWebImage/Core/SDImageCacheDefine.h new file mode 100644 index 0000000..b33bada --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDImageCacheDefine.h @@ -0,0 +1,179 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" +#import "SDWebImageOperation.h" +#import "SDWebImageDefine.h" +#import "SDImageCoder.h" + +/// Image Cache Type +typedef NS_ENUM(NSInteger, SDImageCacheType) { + /** + * For query and contains op in response, means the image isn't available in the image cache + * For op in request, this type is not available and take no effect. + */ + SDImageCacheTypeNone, + /** + * For query and contains op in response, means the image was obtained from the disk cache. + * For op in request, means process only disk cache. + */ + SDImageCacheTypeDisk, + /** + * For query and contains op in response, means the image was obtained from the memory cache. + * For op in request, means process only memory cache. + */ + SDImageCacheTypeMemory, + /** + * For query and contains op in response, this type is not available and take no effect. + * For op in request, means process both memory cache and disk cache. + */ + SDImageCacheTypeAll +}; + +typedef void(^SDImageCacheCheckCompletionBlock)(BOOL isInCache); +typedef void(^SDImageCacheQueryDataCompletionBlock)(NSData * _Nullable data); +typedef void(^SDImageCacheCalculateSizeBlock)(NSUInteger fileCount, NSUInteger totalSize); +typedef NSString * _Nullable (^SDImageCacheAdditionalCachePathBlock)(NSString * _Nonnull key); +typedef void(^SDImageCacheQueryCompletionBlock)(UIImage * _Nullable image, NSData * _Nullable data, SDImageCacheType cacheType); +typedef void(^SDImageCacheContainsCompletionBlock)(SDImageCacheType containsCacheType); + +/** + This is the built-in decoding process for image query from cache. + @note If you want to implement your custom loader with `queryImageForKey:options:context:completion:` API, but also want to keep compatible with SDWebImage's behavior, you'd better use this to produce image. + + @param imageData The image data from the cache. Should not be nil + @param cacheKey The image cache key from the input. Should not be nil + @param options The options arg from the input + @param context The context arg from the input + @return The decoded image for current image data query from cache + */ +FOUNDATION_EXPORT UIImage * _Nullable SDImageCacheDecodeImageData(NSData * _Nonnull imageData, NSString * _Nonnull cacheKey, SDWebImageOptions options, SDWebImageContext * _Nullable context); + +/// Get the decode options from the loading context options and cache key. This is the built-in translate between the web loading part to the decoding part (which does not depends on). +/// @param context The context arg from the input +/// @param options The options arg from the input +/// @param cacheKey The image cache key from the input. Should not be nil +FOUNDATION_EXPORT SDImageCoderOptions * _Nonnull SDGetDecodeOptionsFromContext(SDWebImageContext * _Nullable context, SDWebImageOptions options, NSString * _Nonnull cacheKey); + +/// Set the decode options to the loading context options. This is the built-in translate between the web loading part from the decoding part (which does not depends on). +/// @param mutableContext The context arg to override +/// @param mutableOptions The options arg to override +/// @param decodeOptions The image decoding options +FOUNDATION_EXPORT void SDSetDecodeOptionsToContext(SDWebImageMutableContext * _Nonnull mutableContext, SDWebImageOptions * _Nonnull mutableOptions, SDImageCoderOptions * _Nonnull decodeOptions); + +/** + This is the image cache protocol to provide custom image cache for `SDWebImageManager`. + Though the best practice to custom image cache, is to write your own class which conform `SDMemoryCache` or `SDDiskCache` protocol for `SDImageCache` class (See more on `SDImageCacheConfig.memoryCacheClass & SDImageCacheConfig.diskCacheClass`). + However, if your own cache implementation contains more advanced feature beyond `SDImageCache` itself, you can consider to provide this instead. For example, you can even use a cache manager like `SDImageCachesManager` to register multiple caches. + */ +@protocol SDImageCache + +@required +/** + Query the cached image from image cache for given key. The operation can be used to cancel the query. + If image is cached in memory, completion is called synchronously, else asynchronously and depends on the options arg (See `SDWebImageQueryDiskSync`) + + @param key The image cache key + @param options A mask to specify options to use for this query + @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. Pass `.callbackQueue` to control callback queue + @param completionBlock The completion block. Will not get called if the operation is cancelled + @return The operation for this query + */ +- (nullable id)queryImageForKey:(nullable NSString *)key + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + completion:(nullable SDImageCacheQueryCompletionBlock)completionBlock API_DEPRECATED_WITH_REPLACEMENT("queryImageForKey:options:context:cacheType:completion:", macos(10.10, API_TO_BE_DEPRECATED), ios(8.0, API_TO_BE_DEPRECATED), tvos(9.0, API_TO_BE_DEPRECATED), watchos(2.0, API_TO_BE_DEPRECATED)); + +@optional +/** + Query the cached image from image cache for given key. The operation can be used to cancel the query. + If image is cached in memory, completion is called synchronously, else asynchronously and depends on the options arg (See `SDWebImageQueryDiskSync`) + + @param key The image cache key + @param options A mask to specify options to use for this query + @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. Pass `.callbackQueue` to control callback queue + @param cacheType Specify where to query the cache from. By default we use `.all`, which means both memory cache and disk cache. You can choose to query memory only or disk only as well. Pass `.none` is invalid and callback with nil immediately. + @param completionBlock The completion block. Will not get called if the operation is cancelled + @return The operation for this query + */ +- (nullable id)queryImageForKey:(nullable NSString *)key + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + cacheType:(SDImageCacheType)cacheType + completion:(nullable SDImageCacheQueryCompletionBlock)completionBlock; + +@required +/** + Store the image into image cache for the given key. If cache type is memory only, completion is called synchronously, else asynchronously. + + @param image The image to store + @param imageData The image data to be used for disk storage + @param key The image cache key + @param cacheType The image store op cache type + @param completionBlock A block executed after the operation is finished + */ +- (void)storeImage:(nullable UIImage *)image + imageData:(nullable NSData *)imageData + forKey:(nullable NSString *)key + cacheType:(SDImageCacheType)cacheType + completion:(nullable SDWebImageNoParamsBlock)completionBlock API_DEPRECATED_WITH_REPLACEMENT("storeImage:imageData:forKey:options:context:cacheType:completion:", macos(10.10, API_TO_BE_DEPRECATED), ios(8.0, API_TO_BE_DEPRECATED), tvos(9.0, API_TO_BE_DEPRECATED), watchos(2.0, API_TO_BE_DEPRECATED)); + +@optional +/** + Store the image into image cache for the given key. If cache type is memory only, completion is called synchronously, else asynchronously. + + @param image The image to store + @param imageData The image data to be used for disk storage + @param key The image cache key + @param options A mask to specify options to use for this store + @param context The context options to use. Pass `.callbackQueue` to control callback queue + @param cacheType The image store op cache type + @param completionBlock A block executed after the operation is finished + */ +- (void)storeImage:(nullable UIImage *)image + imageData:(nullable NSData *)imageData + forKey:(nullable NSString *)key + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + cacheType:(SDImageCacheType)cacheType + completion:(nullable SDWebImageNoParamsBlock)completionBlock; + +#pragma mark - Deprecated because SDWebImageManager does not use these APIs +/** + Remove the image from image cache for the given key. If cache type is memory only, completion is called synchronously, else asynchronously. + + @param key The image cache key + @param cacheType The image remove op cache type + @param completionBlock A block executed after the operation is finished + */ +- (void)removeImageForKey:(nullable NSString *)key + cacheType:(SDImageCacheType)cacheType + completion:(nullable SDWebImageNoParamsBlock)completionBlock API_DEPRECATED("No longer use. Cast to cache instance and call its API", macos(10.10, API_TO_BE_DEPRECATED), ios(8.0, API_TO_BE_DEPRECATED), tvos(9.0, API_TO_BE_DEPRECATED), watchos(2.0, API_TO_BE_DEPRECATED)); + +/** + Check if image cache contains the image for the given key (does not load the image). If image is cached in memory, completion is called synchronously, else asynchronously. + + @param key The image cache key + @param cacheType The image contains op cache type + @param completionBlock A block executed after the operation is finished. + */ +- (void)containsImageForKey:(nullable NSString *)key + cacheType:(SDImageCacheType)cacheType + completion:(nullable SDImageCacheContainsCompletionBlock)completionBlock API_DEPRECATED("No longer use. Cast to cache instance and call its API", macos(10.10, API_TO_BE_DEPRECATED), ios(8.0, API_TO_BE_DEPRECATED), tvos(9.0, API_TO_BE_DEPRECATED), watchos(2.0, API_TO_BE_DEPRECATED)); + +/** + Clear all the cached images for image cache. If cache type is memory only, completion is called synchronously, else asynchronously. + + @param cacheType The image clear op cache type + @param completionBlock A block executed after the operation is finished + */ +- (void)clearWithCacheType:(SDImageCacheType)cacheType + completion:(nullable SDWebImageNoParamsBlock)completionBlock API_DEPRECATED("No longer use. Cast to cache instance and call its API", macos(10.10, API_TO_BE_DEPRECATED), ios(8.0, API_TO_BE_DEPRECATED), tvos(9.0, API_TO_BE_DEPRECATED), watchos(2.0, API_TO_BE_DEPRECATED)); + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDImageCacheDefine.m b/Pods/SDWebImage/SDWebImage/Core/SDImageCacheDefine.m new file mode 100644 index 0000000..4e4ad32 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDImageCacheDefine.m @@ -0,0 +1,153 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDImageCacheDefine.h" +#import "SDImageCodersManager.h" +#import "SDImageCoderHelper.h" +#import "SDAnimatedImage.h" +#import "UIImage+Metadata.h" +#import "SDInternalMacros.h" +#import "SDDeviceHelper.h" + +#import + +SDImageCoderOptions * _Nonnull SDGetDecodeOptionsFromContext(SDWebImageContext * _Nullable context, SDWebImageOptions options, NSString * _Nonnull cacheKey) { + BOOL decodeFirstFrame = SD_OPTIONS_CONTAINS(options, SDWebImageDecodeFirstFrameOnly); + NSNumber *scaleValue = context[SDWebImageContextImageScaleFactor]; + CGFloat scale = scaleValue.doubleValue >= 1 ? scaleValue.doubleValue : SDImageScaleFactorForKey(cacheKey); // Use cache key to detect scale + NSNumber *preserveAspectRatioValue = context[SDWebImageContextImagePreserveAspectRatio]; + NSValue *thumbnailSizeValue; + BOOL shouldScaleDown = SD_OPTIONS_CONTAINS(options, SDWebImageScaleDownLargeImages); + NSNumber *scaleDownLimitBytesValue = context[SDWebImageContextImageScaleDownLimitBytes]; + if (scaleDownLimitBytesValue == nil && shouldScaleDown) { + // Use the default limit bytes + scaleDownLimitBytesValue = @(SDImageCoderHelper.defaultScaleDownLimitBytes); + } + if (context[SDWebImageContextImageThumbnailPixelSize]) { + thumbnailSizeValue = context[SDWebImageContextImageThumbnailPixelSize]; + } + NSString *typeIdentifierHint = context[SDWebImageContextImageTypeIdentifierHint]; + NSString *fileExtensionHint; + if (!typeIdentifierHint) { + // UTI has high priority + fileExtensionHint = cacheKey.pathExtension; // without dot + if (fileExtensionHint.length == 0) { + // Ignore file extension which is empty + fileExtensionHint = nil; + } + } + + // First check if user provided decode options + SDImageCoderMutableOptions *mutableCoderOptions; + if (context[SDWebImageContextImageDecodeOptions] != nil) { + mutableCoderOptions = [NSMutableDictionary dictionaryWithDictionary:context[SDWebImageContextImageDecodeOptions]]; + } else { + mutableCoderOptions = [NSMutableDictionary dictionaryWithCapacity:6]; + } + + // Some options need preserve the custom decode options + NSNumber *decodeToHDR = context[SDWebImageContextImageDecodeToHDR]; + if (decodeToHDR == nil) { + decodeToHDR = mutableCoderOptions[SDImageCoderDecodeToHDR]; + } + + // Override individual options + mutableCoderOptions[SDImageCoderDecodeFirstFrameOnly] = @(decodeFirstFrame); + mutableCoderOptions[SDImageCoderDecodeScaleFactor] = @(scale); + mutableCoderOptions[SDImageCoderDecodePreserveAspectRatio] = preserveAspectRatioValue; + mutableCoderOptions[SDImageCoderDecodeThumbnailPixelSize] = thumbnailSizeValue; + mutableCoderOptions[SDImageCoderDecodeTypeIdentifierHint] = typeIdentifierHint; + mutableCoderOptions[SDImageCoderDecodeFileExtensionHint] = fileExtensionHint; + mutableCoderOptions[SDImageCoderDecodeScaleDownLimitBytes] = scaleDownLimitBytesValue; + mutableCoderOptions[SDImageCoderDecodeToHDR] = decodeToHDR; + + return [mutableCoderOptions copy]; +} + +void SDSetDecodeOptionsToContext(SDWebImageMutableContext * _Nonnull mutableContext, SDWebImageOptions * _Nonnull mutableOptions, SDImageCoderOptions * _Nonnull decodeOptions) { + if ([decodeOptions[SDImageCoderDecodeFirstFrameOnly] boolValue]) { + *mutableOptions |= SDWebImageDecodeFirstFrameOnly; + } else { + *mutableOptions &= ~SDWebImageDecodeFirstFrameOnly; + } + + mutableContext[SDWebImageContextImageScaleFactor] = decodeOptions[SDImageCoderDecodeScaleFactor]; + mutableContext[SDWebImageContextImagePreserveAspectRatio] = decodeOptions[SDImageCoderDecodePreserveAspectRatio]; + mutableContext[SDWebImageContextImageThumbnailPixelSize] = decodeOptions[SDImageCoderDecodeThumbnailPixelSize]; + mutableContext[SDWebImageContextImageScaleDownLimitBytes] = decodeOptions[SDImageCoderDecodeScaleDownLimitBytes]; + mutableContext[SDWebImageContextImageDecodeToHDR] = decodeOptions[SDImageCoderDecodeToHDR]; + + NSString *typeIdentifierHint = decodeOptions[SDImageCoderDecodeTypeIdentifierHint]; + if (!typeIdentifierHint) { + NSString *fileExtensionHint = decodeOptions[SDImageCoderDecodeFileExtensionHint]; + if (fileExtensionHint) { + typeIdentifierHint = (__bridge_transfer NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)fileExtensionHint, kUTTypeImage); + // Ignore dynamic UTI + if (UTTypeIsDynamic((__bridge CFStringRef)typeIdentifierHint)) { + typeIdentifierHint = nil; + } + } + } + mutableContext[SDWebImageContextImageTypeIdentifierHint] = typeIdentifierHint; +} + +UIImage * _Nullable SDImageCacheDecodeImageData(NSData * _Nonnull imageData, NSString * _Nonnull cacheKey, SDWebImageOptions options, SDWebImageContext * _Nullable context) { + NSCParameterAssert(imageData); + NSCParameterAssert(cacheKey); + UIImage *image; + SDImageCoderOptions *coderOptions = SDGetDecodeOptionsFromContext(context, options, cacheKey); + BOOL decodeFirstFrame = SD_OPTIONS_CONTAINS(options, SDWebImageDecodeFirstFrameOnly); + CGFloat scale = [coderOptions[SDImageCoderDecodeScaleFactor] doubleValue]; + + // Grab the image coder + id imageCoder = context[SDWebImageContextImageCoder]; + if (!imageCoder) { + imageCoder = [SDImageCodersManager sharedManager]; + } + + if (!decodeFirstFrame) { + Class animatedImageClass = context[SDWebImageContextAnimatedImageClass]; + // check whether we should use `SDAnimatedImage` + if ([animatedImageClass isSubclassOfClass:[UIImage class]] && [animatedImageClass conformsToProtocol:@protocol(SDAnimatedImage)]) { + image = [[animatedImageClass alloc] initWithData:imageData scale:scale options:coderOptions]; + if (image) { + // Preload frames if supported + if (options & SDWebImagePreloadAllFrames && [image respondsToSelector:@selector(preloadAllFrames)]) { + [((id)image) preloadAllFrames]; + } + } else { + // Check image class matching + if (options & SDWebImageMatchAnimatedImageClass) { + return nil; + } + } + } + } + if (!image) { + image = [imageCoder decodedImageWithData:imageData options:coderOptions]; + } + if (image) { + SDImageForceDecodePolicy policy = SDImageForceDecodePolicyAutomatic; + NSNumber *policyValue = context[SDWebImageContextImageForceDecodePolicy]; + if (policyValue != nil) { + policy = policyValue.unsignedIntegerValue; + } + // TODO: Deprecated, remove in SD 6.0... +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + if (SD_OPTIONS_CONTAINS(options, SDWebImageAvoidDecodeImage)) { + policy = SDImageForceDecodePolicyNever; + } +#pragma clang diagnostic pop + image = [SDImageCoderHelper decodedImageWithImage:image policy:policy]; + // assign the decode options, to let manager check whether to re-decode if needed + image.sd_decodeOptions = coderOptions; + } + + return image; +} diff --git a/Pods/SDWebImage/SDWebImage/Core/SDImageCachesManager.h b/Pods/SDWebImage/SDWebImage/Core/SDImageCachesManager.h new file mode 100644 index 0000000..ad85db8 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDImageCachesManager.h @@ -0,0 +1,81 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDImageCacheDefine.h" + +/// Policy for cache operation +typedef NS_ENUM(NSUInteger, SDImageCachesManagerOperationPolicy) { + SDImageCachesManagerOperationPolicySerial, // process all caches serially (from the highest priority to the lowest priority cache by order) + SDImageCachesManagerOperationPolicyConcurrent, // process all caches concurrently + SDImageCachesManagerOperationPolicyHighestOnly, // process the highest priority cache only + SDImageCachesManagerOperationPolicyLowestOnly // process the lowest priority cache only +}; + +/** + A caches manager to manage multiple caches. + */ +@interface SDImageCachesManager : NSObject + +/** + Returns the global shared caches manager instance. By default we will set [`SDImageCache.sharedImageCache`] into the caches array. + */ +@property (nonatomic, class, readonly, nonnull) SDImageCachesManager *sharedManager; + +// These are op policy for cache manager. + +/** + Operation policy for query op. + Defaults to `Serial`, means query all caches serially (one completion called then next begin) until one cache query success (`image` != nil). + */ +@property (nonatomic, assign) SDImageCachesManagerOperationPolicy queryOperationPolicy; + +/** + Operation policy for store op. + Defaults to `HighestOnly`, means store to the highest priority cache only. + */ +@property (nonatomic, assign) SDImageCachesManagerOperationPolicy storeOperationPolicy; + +/** + Operation policy for remove op. + Defaults to `Concurrent`, means remove all caches concurrently. + */ +@property (nonatomic, assign) SDImageCachesManagerOperationPolicy removeOperationPolicy; + +/** + Operation policy for contains op. + Defaults to `Serial`, means check all caches serially (one completion called then next begin) until one cache check success (`containsCacheType` != None). + */ +@property (nonatomic, assign) SDImageCachesManagerOperationPolicy containsOperationPolicy; + +/** + Operation policy for clear op. + Defaults to `Concurrent`, means clear all caches concurrently. + */ +@property (nonatomic, assign) SDImageCachesManagerOperationPolicy clearOperationPolicy; + +/** + All caches in caches manager. The caches array is a priority queue, which means the later added cache will have the highest priority + */ +@property (nonatomic, copy, nullable) NSArray> *caches; + +/** + Add a new cache to the end of caches array. Which has the highest priority. + + @param cache cache + */ +- (void)addCache:(nonnull id)cache; + +/** + Remove a cache in the caches array. + + @param cache cache + */ +- (void)removeCache:(nonnull id)cache; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDImageCachesManager.m b/Pods/SDWebImage/SDWebImage/Core/SDImageCachesManager.m new file mode 100644 index 0000000..9b58d7d --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDImageCachesManager.m @@ -0,0 +1,560 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDImageCachesManager.h" +#import "SDImageCachesManagerOperation.h" +#import "SDImageCache.h" +#import "SDInternalMacros.h" + +@interface SDImageCachesManager () + +@property (nonatomic, strong, nonnull) NSMutableArray> *imageCaches; + +@end + +@implementation SDImageCachesManager { + SD_LOCK_DECLARE(_cachesLock); +} + ++ (SDImageCachesManager *)sharedManager { + static dispatch_once_t onceToken; + static SDImageCachesManager *manager; + dispatch_once(&onceToken, ^{ + manager = [[SDImageCachesManager alloc] init]; + }); + return manager; +} + +- (instancetype)init { + self = [super init]; + if (self) { + self.queryOperationPolicy = SDImageCachesManagerOperationPolicySerial; + self.storeOperationPolicy = SDImageCachesManagerOperationPolicyHighestOnly; + self.removeOperationPolicy = SDImageCachesManagerOperationPolicyConcurrent; + self.containsOperationPolicy = SDImageCachesManagerOperationPolicySerial; + self.clearOperationPolicy = SDImageCachesManagerOperationPolicyConcurrent; + // initialize with default image caches + _imageCaches = [NSMutableArray arrayWithObject:[SDImageCache sharedImageCache]]; + SD_LOCK_INIT(_cachesLock); + } + return self; +} + +- (NSArray> *)caches { + SD_LOCK(_cachesLock); + NSArray> *caches = [_imageCaches copy]; + SD_UNLOCK(_cachesLock); + return caches; +} + +- (void)setCaches:(NSArray> *)caches { + SD_LOCK(_cachesLock); + [_imageCaches removeAllObjects]; + if (caches.count) { + [_imageCaches addObjectsFromArray:caches]; + } + SD_UNLOCK(_cachesLock); +} + +#pragma mark - Cache IO operations + +- (void)addCache:(id)cache { + if (![cache conformsToProtocol:@protocol(SDImageCache)]) { + return; + } + SD_LOCK(_cachesLock); + [_imageCaches addObject:cache]; + SD_UNLOCK(_cachesLock); +} + +- (void)removeCache:(id)cache { + if (![cache conformsToProtocol:@protocol(SDImageCache)]) { + return; + } + SD_LOCK(_cachesLock); + [_imageCaches removeObject:cache]; + SD_UNLOCK(_cachesLock); +} + +#pragma mark - SDImageCache + +- (id)queryImageForKey:(NSString *)key options:(SDWebImageOptions)options context:(SDWebImageContext *)context completion:(SDImageCacheQueryCompletionBlock)completionBlock { + return [self queryImageForKey:key options:options context:context cacheType:SDImageCacheTypeAll completion:completionBlock]; +} + +- (id)queryImageForKey:(NSString *)key options:(SDWebImageOptions)options context:(SDWebImageContext *)context cacheType:(SDImageCacheType)cacheType completion:(SDImageCacheQueryCompletionBlock)completionBlock { + if (!key) { + return nil; + } + NSArray> *caches = self.caches; + NSUInteger count = caches.count; + if (count == 0) { + return nil; + } else if (count == 1) { + return [caches.firstObject queryImageForKey:key options:options context:context cacheType:cacheType completion:completionBlock]; + } + switch (self.queryOperationPolicy) { + case SDImageCachesManagerOperationPolicyHighestOnly: { + id cache = caches.lastObject; + return [cache queryImageForKey:key options:options context:context cacheType:cacheType completion:completionBlock]; + } + break; + case SDImageCachesManagerOperationPolicyLowestOnly: { + id cache = caches.firstObject; + return [cache queryImageForKey:key options:options context:context cacheType:cacheType completion:completionBlock]; + } + break; + case SDImageCachesManagerOperationPolicyConcurrent: { + SDImageCachesManagerOperation *operation = [SDImageCachesManagerOperation new]; + [operation beginWithTotalCount:caches.count]; + [self concurrentQueryImageForKey:key options:options context:context cacheType:cacheType completion:completionBlock enumerator:caches.reverseObjectEnumerator operation:operation]; + return operation; + } + break; + case SDImageCachesManagerOperationPolicySerial: { + SDImageCachesManagerOperation *operation = [SDImageCachesManagerOperation new]; + [operation beginWithTotalCount:caches.count]; + [self serialQueryImageForKey:key options:options context:context cacheType:cacheType completion:completionBlock enumerator:caches.reverseObjectEnumerator operation:operation]; + return operation; + } + break; + default: + return nil; + break; + } +} + +- (void)storeImage:(UIImage *)image imageData:(NSData *)imageData forKey:(NSString *)key cacheType:(SDImageCacheType)cacheType completion:(SDWebImageNoParamsBlock)completionBlock { + [self storeImage:image imageData:imageData forKey:key options:0 context:nil cacheType:cacheType completion:completionBlock]; +} + +- (void)storeImage:(UIImage *)image imageData:(NSData *)imageData forKey:(NSString *)key options:(SDWebImageOptions)options context:(SDWebImageContext *)context cacheType:(SDImageCacheType)cacheType completion:(SDWebImageNoParamsBlock)completionBlock { + if (!key) { + return; + } + NSArray> *caches = self.caches; + NSUInteger count = caches.count; + if (count == 0) { + return; + } else if (count == 1) { + [caches.firstObject storeImage:image imageData:imageData forKey:key options:options context:context cacheType:cacheType completion:completionBlock]; + return; + } + switch (self.storeOperationPolicy) { + case SDImageCachesManagerOperationPolicyHighestOnly: { + id cache = caches.lastObject; + [cache storeImage:image imageData:imageData forKey:key options:options context:context cacheType:cacheType completion:completionBlock]; + } + break; + case SDImageCachesManagerOperationPolicyLowestOnly: { + id cache = caches.firstObject; + [cache storeImage:image imageData:imageData forKey:key options:options context:context cacheType:cacheType completion:completionBlock]; + } + break; + case SDImageCachesManagerOperationPolicyConcurrent: { + SDImageCachesManagerOperation *operation = [SDImageCachesManagerOperation new]; + [operation beginWithTotalCount:caches.count]; + [self concurrentStoreImage:image imageData:imageData forKey:key options:options context:context cacheType:cacheType completion:completionBlock enumerator:caches.reverseObjectEnumerator operation:operation]; + } + break; + case SDImageCachesManagerOperationPolicySerial: { + [self serialStoreImage:image imageData:imageData forKey:key options:options context:context cacheType:cacheType completion:completionBlock enumerator:caches.reverseObjectEnumerator]; + } + break; + default: + break; + } +} + +- (void)removeImageForKey:(NSString *)key cacheType:(SDImageCacheType)cacheType completion:(SDWebImageNoParamsBlock)completionBlock { + if (!key) { + return; + } + NSArray> *caches = self.caches; + NSUInteger count = caches.count; + if (count == 0) { + return; + } else if (count == 1) { + [caches.firstObject removeImageForKey:key cacheType:cacheType completion:completionBlock]; + return; + } + switch (self.removeOperationPolicy) { + case SDImageCachesManagerOperationPolicyHighestOnly: { + id cache = caches.lastObject; + [cache removeImageForKey:key cacheType:cacheType completion:completionBlock]; + } + break; + case SDImageCachesManagerOperationPolicyLowestOnly: { + id cache = caches.firstObject; + [cache removeImageForKey:key cacheType:cacheType completion:completionBlock]; + } + break; + case SDImageCachesManagerOperationPolicyConcurrent: { + SDImageCachesManagerOperation *operation = [SDImageCachesManagerOperation new]; + [operation beginWithTotalCount:caches.count]; + [self concurrentRemoveImageForKey:key cacheType:cacheType completion:completionBlock enumerator:caches.reverseObjectEnumerator operation:operation]; + } + break; + case SDImageCachesManagerOperationPolicySerial: { + [self serialRemoveImageForKey:key cacheType:cacheType completion:completionBlock enumerator:caches.reverseObjectEnumerator]; + } + break; + default: + break; + } +} + +- (void)containsImageForKey:(NSString *)key cacheType:(SDImageCacheType)cacheType completion:(SDImageCacheContainsCompletionBlock)completionBlock { + if (!key) { + return; + } + NSArray> *caches = self.caches; + NSUInteger count = caches.count; + if (count == 0) { + return; + } else if (count == 1) { + [caches.firstObject containsImageForKey:key cacheType:cacheType completion:completionBlock]; + return; + } + switch (self.clearOperationPolicy) { + case SDImageCachesManagerOperationPolicyHighestOnly: { + id cache = caches.lastObject; + [cache containsImageForKey:key cacheType:cacheType completion:completionBlock]; + } + break; + case SDImageCachesManagerOperationPolicyLowestOnly: { + id cache = caches.firstObject; + [cache containsImageForKey:key cacheType:cacheType completion:completionBlock]; + } + break; + case SDImageCachesManagerOperationPolicyConcurrent: { + SDImageCachesManagerOperation *operation = [SDImageCachesManagerOperation new]; + [operation beginWithTotalCount:caches.count]; + [self concurrentContainsImageForKey:key cacheType:cacheType completion:completionBlock enumerator:caches.reverseObjectEnumerator operation:operation]; + } + break; + case SDImageCachesManagerOperationPolicySerial: { + SDImageCachesManagerOperation *operation = [SDImageCachesManagerOperation new]; + [operation beginWithTotalCount:caches.count]; + [self serialContainsImageForKey:key cacheType:cacheType completion:completionBlock enumerator:caches.reverseObjectEnumerator operation:operation]; + } + break; + default: + break; + } +} + +- (void)clearWithCacheType:(SDImageCacheType)cacheType completion:(SDWebImageNoParamsBlock)completionBlock { + NSArray> *caches = self.caches; + NSUInteger count = caches.count; + if (count == 0) { + return; + } else if (count == 1) { + [caches.firstObject clearWithCacheType:cacheType completion:completionBlock]; + return; + } + switch (self.clearOperationPolicy) { + case SDImageCachesManagerOperationPolicyHighestOnly: { + id cache = caches.lastObject; + [cache clearWithCacheType:cacheType completion:completionBlock]; + } + break; + case SDImageCachesManagerOperationPolicyLowestOnly: { + id cache = caches.firstObject; + [cache clearWithCacheType:cacheType completion:completionBlock]; + } + break; + case SDImageCachesManagerOperationPolicyConcurrent: { + SDImageCachesManagerOperation *operation = [SDImageCachesManagerOperation new]; + [operation beginWithTotalCount:caches.count]; + [self concurrentClearWithCacheType:cacheType completion:completionBlock enumerator:caches.reverseObjectEnumerator operation:operation]; + } + break; + case SDImageCachesManagerOperationPolicySerial: { + [self serialClearWithCacheType:cacheType completion:completionBlock enumerator:caches.reverseObjectEnumerator]; + } + break; + default: + break; + } +} + +#pragma mark - Concurrent Operation + +- (void)concurrentQueryImageForKey:(NSString *)key options:(SDWebImageOptions)options context:(SDWebImageContext *)context cacheType:(SDImageCacheType)queryCacheType completion:(SDImageCacheQueryCompletionBlock)completionBlock enumerator:(NSEnumerator> *)enumerator operation:(SDImageCachesManagerOperation *)operation { + NSParameterAssert(enumerator); + NSParameterAssert(operation); + for (id cache in enumerator) { + [cache queryImageForKey:key options:options context:context cacheType:queryCacheType completion:^(UIImage * _Nullable image, NSData * _Nullable data, SDImageCacheType cacheType) { + if (operation.isCancelled) { + // Cancelled + return; + } + if (operation.isFinished) { + // Finished + return; + } + [operation completeOne]; + if (image) { + // Success + [operation done]; + if (completionBlock) { + completionBlock(image, data, cacheType); + } + return; + } + if (operation.pendingCount == 0) { + // Complete + [operation done]; + if (completionBlock) { + completionBlock(nil, nil, SDImageCacheTypeNone); + } + } + }]; + } +} + +- (void)concurrentStoreImage:(UIImage *)image imageData:(NSData *)imageData forKey:(NSString *)key options:(SDWebImageOptions)options context:(SDWebImageContext *)context cacheType:(SDImageCacheType)cacheType completion:(SDWebImageNoParamsBlock)completionBlock enumerator:(NSEnumerator> *)enumerator operation:(SDImageCachesManagerOperation *)operation { + NSParameterAssert(enumerator); + NSParameterAssert(operation); + for (id cache in enumerator) { + [cache storeImage:image imageData:imageData forKey:key options:options context:context cacheType:cacheType completion:^{ + if (operation.isCancelled) { + // Cancelled + return; + } + if (operation.isFinished) { + // Finished + return; + } + [operation completeOne]; + if (operation.pendingCount == 0) { + // Complete + [operation done]; + if (completionBlock) { + completionBlock(); + } + } + }]; + } +} + +- (void)concurrentRemoveImageForKey:(NSString *)key cacheType:(SDImageCacheType)cacheType completion:(SDWebImageNoParamsBlock)completionBlock enumerator:(NSEnumerator> *)enumerator operation:(SDImageCachesManagerOperation *)operation { + NSParameterAssert(enumerator); + NSParameterAssert(operation); + for (id cache in enumerator) { + [cache removeImageForKey:key cacheType:cacheType completion:^{ + if (operation.isCancelled) { + // Cancelled + return; + } + if (operation.isFinished) { + // Finished + return; + } + [operation completeOne]; + if (operation.pendingCount == 0) { + // Complete + [operation done]; + if (completionBlock) { + completionBlock(); + } + } + }]; + } +} + +- (void)concurrentContainsImageForKey:(NSString *)key cacheType:(SDImageCacheType)cacheType completion:(SDImageCacheContainsCompletionBlock)completionBlock enumerator:(NSEnumerator> *)enumerator operation:(SDImageCachesManagerOperation *)operation { + NSParameterAssert(enumerator); + NSParameterAssert(operation); + for (id cache in enumerator) { + [cache containsImageForKey:key cacheType:cacheType completion:^(SDImageCacheType containsCacheType) { + if (operation.isCancelled) { + // Cancelled + return; + } + if (operation.isFinished) { + // Finished + return; + } + [operation completeOne]; + if (containsCacheType != SDImageCacheTypeNone) { + // Success + [operation done]; + if (completionBlock) { + completionBlock(containsCacheType); + } + return; + } + if (operation.pendingCount == 0) { + // Complete + [operation done]; + if (completionBlock) { + completionBlock(SDImageCacheTypeNone); + } + } + }]; + } +} + +- (void)concurrentClearWithCacheType:(SDImageCacheType)cacheType completion:(SDWebImageNoParamsBlock)completionBlock enumerator:(NSEnumerator> *)enumerator operation:(SDImageCachesManagerOperation *)operation { + NSParameterAssert(enumerator); + NSParameterAssert(operation); + for (id cache in enumerator) { + [cache clearWithCacheType:cacheType completion:^{ + if (operation.isCancelled) { + // Cancelled + return; + } + if (operation.isFinished) { + // Finished + return; + } + [operation completeOne]; + if (operation.pendingCount == 0) { + // Complete + [operation done]; + if (completionBlock) { + completionBlock(); + } + } + }]; + } +} + +#pragma mark - Serial Operation + +- (void)serialQueryImageForKey:(NSString *)key options:(SDWebImageOptions)options context:(SDWebImageContext *)context cacheType:(SDImageCacheType)queryCacheType completion:(SDImageCacheQueryCompletionBlock)completionBlock enumerator:(NSEnumerator> *)enumerator operation:(SDImageCachesManagerOperation *)operation { + NSParameterAssert(enumerator); + NSParameterAssert(operation); + id cache = enumerator.nextObject; + if (!cache) { + // Complete + [operation done]; + if (completionBlock) { + completionBlock(nil, nil, SDImageCacheTypeNone); + } + return; + } + @weakify(self); + [cache queryImageForKey:key options:options context:context cacheType:queryCacheType completion:^(UIImage * _Nullable image, NSData * _Nullable data, SDImageCacheType cacheType) { + @strongify(self); + if (operation.isCancelled) { + // Cancelled + return; + } + if (operation.isFinished) { + // Finished + return; + } + [operation completeOne]; + if (image) { + // Success + [operation done]; + if (completionBlock) { + completionBlock(image, data, cacheType); + } + return; + } + // Next + [self serialQueryImageForKey:key options:options context:context cacheType:queryCacheType completion:completionBlock enumerator:enumerator operation:operation]; + }]; +} + +- (void)serialStoreImage:(UIImage *)image imageData:(NSData *)imageData forKey:(NSString *)key options:(SDWebImageOptions)options context:(SDWebImageContext *)context cacheType:(SDImageCacheType)cacheType completion:(SDWebImageNoParamsBlock)completionBlock enumerator:(NSEnumerator> *)enumerator { + NSParameterAssert(enumerator); + id cache = enumerator.nextObject; + if (!cache) { + // Complete + if (completionBlock) { + completionBlock(); + } + return; + } + @weakify(self); + [cache storeImage:image imageData:imageData forKey:key options:options context:context cacheType:cacheType completion:^{ + @strongify(self); + // Next + [self serialStoreImage:image imageData:imageData forKey:key options:options context:context cacheType:cacheType completion:completionBlock enumerator:enumerator]; + }]; +} + +- (void)serialRemoveImageForKey:(NSString *)key cacheType:(SDImageCacheType)cacheType completion:(SDWebImageNoParamsBlock)completionBlock enumerator:(NSEnumerator> *)enumerator { + NSParameterAssert(enumerator); + id cache = enumerator.nextObject; + if (!cache) { + // Complete + if (completionBlock) { + completionBlock(); + } + return; + } + @weakify(self); + [cache removeImageForKey:key cacheType:cacheType completion:^{ + @strongify(self); + // Next + [self serialRemoveImageForKey:key cacheType:cacheType completion:completionBlock enumerator:enumerator]; + }]; +} + +- (void)serialContainsImageForKey:(NSString *)key cacheType:(SDImageCacheType)cacheType completion:(SDImageCacheContainsCompletionBlock)completionBlock enumerator:(NSEnumerator> *)enumerator operation:(SDImageCachesManagerOperation *)operation { + NSParameterAssert(enumerator); + NSParameterAssert(operation); + id cache = enumerator.nextObject; + if (!cache) { + // Complete + [operation done]; + if (completionBlock) { + completionBlock(SDImageCacheTypeNone); + } + return; + } + @weakify(self); + [cache containsImageForKey:key cacheType:cacheType completion:^(SDImageCacheType containsCacheType) { + @strongify(self); + if (operation.isCancelled) { + // Cancelled + return; + } + if (operation.isFinished) { + // Finished + return; + } + [operation completeOne]; + if (containsCacheType != SDImageCacheTypeNone) { + // Success + [operation done]; + if (completionBlock) { + completionBlock(containsCacheType); + } + return; + } + // Next + [self serialContainsImageForKey:key cacheType:cacheType completion:completionBlock enumerator:enumerator operation:operation]; + }]; +} + +- (void)serialClearWithCacheType:(SDImageCacheType)cacheType completion:(SDWebImageNoParamsBlock)completionBlock enumerator:(NSEnumerator> *)enumerator { + NSParameterAssert(enumerator); + id cache = enumerator.nextObject; + if (!cache) { + // Complete + if (completionBlock) { + completionBlock(); + } + return; + } + @weakify(self); + [cache clearWithCacheType:cacheType completion:^{ + @strongify(self); + // Next + [self serialClearWithCacheType:cacheType completion:completionBlock enumerator:enumerator]; + }]; +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDImageCoder.h b/Pods/SDWebImage/SDWebImage/Core/SDImageCoder.h new file mode 100644 index 0000000..373fc17 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDImageCoder.h @@ -0,0 +1,347 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" +#import "NSData+ImageContentType.h" +#import "SDImageFrame.h" + +/// Image Decoding/Encoding Options +typedef NSString * SDImageCoderOption NS_STRING_ENUM; +typedef NSDictionary SDImageCoderOptions; +typedef NSMutableDictionary SDImageCoderMutableOptions; + +#pragma mark - Image Decoding Options +// These options are for image decoding +/** + A Boolean value indicating whether to decode the first frame only for animated image during decoding. (NSNumber). If not provide, decode animated image if need. + @note works for `SDImageCoder`. + */ +FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderDecodeFirstFrameOnly; + +/** + A CGFloat value which is greater than or equal to 1.0. This value specify the image scale factor for decoding. If not provide, use 1.0. (NSNumber) + @note works for `SDImageCoder`, `SDProgressiveImageCoder`, `SDAnimatedImageCoder`. + */ +FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderDecodeScaleFactor; + +/** + A Boolean value indicating whether to keep the original aspect ratio when generating thumbnail images (or bitmap images from vector format). + Defaults to YES. + @note works for `SDImageCoder`, `SDProgressiveImageCoder`, `SDAnimatedImageCoder`. + */ +FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderDecodePreserveAspectRatio; + +/** + A CGSize value indicating whether or not to generate the thumbnail images (or bitmap images from vector format). When this value is provided, the decoder will generate a thumbnail image which pixel size is smaller than or equal to (depends the `.preserveAspectRatio`) the value size. + Defaults to CGSizeZero, which means no thumbnail generation at all. + @note Supports for animated image as well. + @note When you pass `.preserveAspectRatio == NO`, the thumbnail image is stretched to match each dimension. When `.preserveAspectRatio == YES`, the thumbnail image's width is limited to pixel size's width, the thumbnail image's height is limited to pixel size's height. For common cases, you can just pass a square size to limit both. + @note works for `SDImageCoder`, `SDProgressiveImageCoder`, `SDAnimatedImageCoder`. + */ +FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderDecodeThumbnailPixelSize; + +/** + A NSString value indicating the source image's file extension. Example: "jpg", "nef", "tif", don't prefix the dot + Some image file format share the same data structure but has different tag explanation, like TIFF and NEF/SRW, see https://en.wikipedia.org/wiki/TIFF + Changing the file extension cause the different image result. The coder (like ImageIO) may use file extension to choose the correct parser + @note However, different UTType may share the same file extension, like `public.jpeg` and `public.jpeg-2000` both use `.jpg`. If you want detail control, use `TypeIdentifierHint` below + */ +FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderDecodeFileExtensionHint; + +/** + A NSString value (UTI) indicating the source image's file extension. Example: "public.jpeg-2000", "com.nikon.raw-image", "public.tiff" + Some image file format share the same data structure but has different tag explanation, like TIFF and NEF/SRW, see https://en.wikipedia.org/wiki/TIFF + Changing the file extension cause the different image result. The coder (like ImageIO) may use file extension to choose the correct parser + @note If you provide `TypeIdentifierHint`, the `FileExtensionHint` option above will be ignored (because UTType has high priority) + @note If you really don't want any hint which effect the image result, pass `NSNull.null` instead + */ +FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderDecodeTypeIdentifierHint; + +/** + A BOOL value indicating whether to use lazy-decoding. Defaults to NO on animated image coder, but defaults to YES on static image coder. + CGImageRef, this image object typically support lazy-decoding, via the `CGDataProviderCreateDirectAccess` or `CGDataProviderCreateSequential` + Which allows you to provide a lazy-called callback to access bitmap buffer, so that you can achieve lazy-decoding when consumer actually need bitmap buffer + UIKit on iOS use heavy on this and ImageIO codec prefers to lazy-decoding for common Hardware-Accelerate format like JPEG/PNG/HEIC + But however, the consumer may access bitmap buffer when running on main queue, like CoreAnimation layer render image. So this is a trade-off + You can force us to disable the lazy-decoding and always allocate bitmap buffer on RAM, but this may have higher ratio of OOM (out of memory) + @note The default value is NO for animated image coder (means `animatedImageFrameAtIndex:`) + @note The default value is YES for static image coder (means `decodedImageWithData:`) + @note works for `SDImageCoder`, `SDProgressiveImageCoder`, `SDAnimatedImageCoder`. + */ +FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderDecodeUseLazyDecoding; + +/** + A NSUInteger value to provide the limit bytes during decoding. This can help to avoid OOM on large frame count animated image or large pixel static image when you don't know how much RAM it occupied before decoding + The decoder will do these logic based on limit bytes: + 1. Get the total frame count (static image means 1) + 2. Calculate the `framePixelSize` width/height to `sqrt(limitBytes / frameCount / bytesPerPixel)`, keeping aspect ratio (at least 1x1) + 3. If the `framePixelSize < originalImagePixelSize`, then do thumbnail decoding (see `SDImageCoderDecodeThumbnailPixelSize`) use the `framePixelSize` and `preseveAspectRatio = YES` + 4. Else, use the full pixel decoding (small than limit bytes) + 5. Whatever result, this does not effect the animated/static behavior of image. So even if you set `limitBytes = 1 && frameCount = 100`, we will stll create animated image with each frame `1x1` pixel size. + @note You can use the logic from `+[SDImageCoder scaledSizeWithImageSize:limitBytes:bytesPerPixel:frameCount:]` + @note This option has higher priority than `.decodeThumbnailPixelSize` + */ +FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderDecodeScaleDownLimitBytes; + +/** + A Boolean (`SDImageHDRType.rawValue`) value (stored inside NSNumber) to provide converting to HDR during decoding. Currently if number is 0 (`SDImageHDRTypeSDR`), use SDR, else use HDR. But we may extend this option to represent `SDImageHDRType` all cases in the future (means, think this options as uint number, but not actual boolean) + @note Supported by iOS 17 and above when using ImageIO coder (third-party coder can support lower firmware) + Defaults to @(NO), decoder will automatically convert SDR. + @note works for `SDImageCoder` + */ +FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderDecodeToHDR; + +#pragma mark - Image Encoding Options +/** + A NSUInteger (`SDImageHDRType.rawValue`) value (stored inside NSNumber) to provide converting to HDR during encoding. Read the below carefully to choose the value. + @note 0(`SDImageHDRTypeSDR`) means SDR; 1(`SDImageHDRTypeISOHDR`) means ISO HDR (at least using 10 bits per components or above, supported by AVIF/HEIF/JPEG-XL); 2(`SDImageHDRTypeISOGainMap`) means ISO Gain Map HDR (may use 8 bits per components, supported by AVIF/HEIF/JPEG-XL, as well as traditional JPEG) + @note Gain Map like a mask image with metadata, which contains the depth/bright information for pixels (1/4 resolution), which used to convert between HDR and SDR. + @note If you use CIImage as HDR pipeline, you can export as CGImage for encoding. (But it's also recommanded to use CIImage's `JPEGRepresentationOfImage` or `HEIFRepresentationOfImage`) + @note Supported by iOS 18 and above when using ImageIO coder (third-party coder can support lower firmware) + Defaults to @(0), encoder will automatically convert SDR. + @note works for `SDImageCoder` + */ +FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderEncodeToHDR; + +/** + A Boolean value indicating whether to encode the first frame only for animated image during encoding. (NSNumber). If not provide, encode animated image if need. + @note works for `SDImageCoder`. + */ +FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderEncodeFirstFrameOnly; +/** + A double value between 0.0-1.0 indicating the encode compression quality to produce the image data. 1.0 resulting in no compression and 0.0 resulting in the maximum compression possible. If not provide, use 1.0. (NSNumber) + @note works for `SDImageCoder` + */ +FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderEncodeCompressionQuality; + +/** + A UIColor(NSColor) value to used for non-alpha image encoding when the input image has alpha channel, the background color will be used to compose the alpha one. If not provide, use white color. + @note works for `SDImageCoder` + */ +FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderEncodeBackgroundColor; + +/** + A CGSize value indicating the max image resolution in pixels during encoding. For vector image, this also effect the output vector data information about width and height. The encoder will not generate the encoded image larger than this limit. Note it always use the aspect ratio of input image.. + Defaults to CGSizeZero, which means no max size limit at all. + @note Supports for animated image as well. + @note The output image's width is limited to pixel size's width, the output image's height is limited to pixel size's height. For common cases, you can just pass a square size to limit both. + @note works for `SDImageCoder` + */ +FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderEncodeMaxPixelSize; + +/** + A NSUInteger value specify the max output data bytes size after encoding. Some lossy format like JPEG/HEIF supports the hint for codec to automatically reduce the quality and match the file size you want. Note this option will override the `SDImageCoderEncodeCompressionQuality`, because now the quality is decided by the encoder. (NSNumber) + @note This is a hint, no guarantee for output size because of compression algorithm limit. And this options does not works for vector images. + @note works for `SDImageCoder` + */ +FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderEncodeMaxFileSize; + +/** + A Boolean value indicating the encoding format should contains a thumbnail image into the output data. Only some of image format (like JPEG/HEIF/AVIF) support this behavior. The embed thumbnail will be used during next time thumbnail decoding (provided `.thumbnailPixelSize`), which is faster than full image thumbnail decoding. (NSNumber) + Defaults to NO, which does not embed any thumbnail. + @note The thumbnail image's pixel size is not defined, the encoder can choose the proper pixel size which is suitable for encoding quality. + @note works for `SDImageCoder` + */ +FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderEncodeEmbedThumbnail; + +/** + A SDWebImageContext object which hold the original context options from top-level API. (SDWebImageContext) + This option is ignored for all built-in coders and take no effect. + But this may be useful for some custom coders, because some business logic may dependent on things other than image or image data information only. + Only the unknown context from top-level API (See SDWebImageDefine.h) may be passed in during image loading. + See `SDWebImageContext` for more detailed information. + @warning Deprecated. This does nothing from 5.14.0. Use `SDWebImageContextImageDecodeOptions` to pass additional information in top-level API, and use `SDImageCoderOptions` to retrieve options from coder. + */ +FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderWebImageContext API_DEPRECATED("No longer supported. Use SDWebImageContextDecodeOptions in loader API to provide options. Use SDImageCoderOptions in coder API to retrieve options.", macos(10.10, 10.10), ios(8.0, 8.0), tvos(9.0, 9.0), watchos(2.0, 2.0)); + +#pragma mark - Coder +/** + This is the image coder protocol to provide custom image decoding/encoding. + These methods are all required to implement. + @note Pay attention that these methods are not called from main queue. + */ +@protocol SDImageCoder + +@required +#pragma mark - Decoding +/** + Returns YES if this coder can decode some data. Otherwise, the data should be passed to another coder. + + @param data The image data so we can look at it + @return YES if this coder can decode the data, NO otherwise + */ +- (BOOL)canDecodeFromData:(nullable NSData *)data; + +/** + Decode the image data to image. + @note This protocol may supports decode animated image frames. You can use `+[SDImageCoderHelper animatedImageWithFrames:]` to produce an animated image with frames. + + @param data The image data to be decoded + @param options A dictionary containing any decoding options. Pass @{SDImageCoderDecodeScaleFactor: @(1.0)} to specify scale factor for image. Pass @{SDImageCoderDecodeFirstFrameOnly: @(YES)} to decode the first frame only. + @return The decoded image from data + */ +- (nullable UIImage *)decodedImageWithData:(nullable NSData *)data + options:(nullable SDImageCoderOptions *)options; + +#pragma mark - Encoding + +/** + Returns YES if this coder can encode some image. Otherwise, it should be passed to another coder. + For custom coder which introduce new image format, you'd better define a new `SDImageFormat` using like this. If you're creating public coder plugin for new image format, also update `https://github.com/rs/SDWebImage/wiki/Coder-Plugin-List` to avoid same value been defined twice. + * @code + static const SDImageFormat SDImageFormatHEIF = 10; + * @endcode + + @param format The image format + @return YES if this coder can encode the image, NO otherwise + */ +- (BOOL)canEncodeToFormat:(SDImageFormat)format NS_SWIFT_NAME(canEncode(to:)); + +/** + Encode the image to image data. + @note This protocol may supports encode animated image frames. You can use `+[SDImageCoderHelper framesFromAnimatedImage:]` to assemble an animated image with frames. But this consume time is not always reversible. In 5.15.0, we introduce `encodedDataWithFrames` API for better animated image encoding. Use that instead. + @note Which means, this just forward to `encodedDataWithFrames([SDImageFrame(image: image, duration: 0], image.sd_imageLoopCount))` + + @param image The image to be encoded + @param format The image format to encode, you should note `SDImageFormatUndefined` format is also possible + @param options A dictionary containing any encoding options. Pass @{SDImageCoderEncodeCompressionQuality: @(1)} to specify compression quality. + @return The encoded image data + */ +- (nullable NSData *)encodedDataWithImage:(nullable UIImage *)image + format:(SDImageFormat)format + options:(nullable SDImageCoderOptions *)options; + +#pragma mark - Animated Encoding +@optional +/** + Encode the animated image frames to image data. + + @param frames The animated image frames to be encoded, should be at least 1 element, or it will fallback to static image encode. + @param loopCount The final animated image loop count. 0 means infinity loop. This config ignore each frame's `sd_imageLoopCount` + @param format The image format to encode, you should note `SDImageFormatUndefined` format is also possible + @param options A dictionary containing any encoding options. Pass @{SDImageCoderEncodeCompressionQuality: @(1)} to specify compression quality. + @return The encoded image data + */ +- (nullable NSData *)encodedDataWithFrames:(nonnull NSArray*)frames + loopCount:(NSUInteger)loopCount + format:(SDImageFormat)format + options:(nullable SDImageCoderOptions *)options; +@end + +#pragma mark - Progressive Coder +/** + This is the image coder protocol to provide custom progressive image decoding. + These methods are all required to implement. + @note Pay attention that these methods are not called from main queue. + */ +@protocol SDProgressiveImageCoder + +@required +/** + Returns YES if this coder can incremental decode some data. Otherwise, it should be passed to another coder. + + @param data The image data so we can look at it + @return YES if this coder can decode the data, NO otherwise + */ +- (BOOL)canIncrementalDecodeFromData:(nullable NSData *)data; + +/** + Because incremental decoding need to keep the decoded context, we will alloc a new instance with the same class for each download operation to avoid conflicts + This init method should not return nil + + @param options A dictionary containing any progressive decoding options (instance-level). Pass @{SDImageCoderDecodeScaleFactor: @(1.0)} to specify scale factor for progressive animated image (each frames should use the same scale). + @return A new instance to do incremental decoding for the specify image format + */ +- (nonnull instancetype)initIncrementalWithOptions:(nullable SDImageCoderOptions *)options; + +/** + Update the incremental decoding when new image data available + + @param data The image data has been downloaded so far + @param finished Whether the download has finished + */ +- (void)updateIncrementalData:(nullable NSData *)data finished:(BOOL)finished; + +/** + Incremental decode the current image data to image. + @note Due to the performance issue for progressive decoding and the integration for image view. This method may only return the first frame image even if the image data is animated image. If you want progressive animated image decoding, conform to `SDAnimatedImageCoder` protocol as well and use `animatedImageFrameAtIndex:` instead. + + @param options A dictionary containing any progressive decoding options. Pass @{SDImageCoderDecodeScaleFactor: @(1.0)} to specify scale factor for progressive image + @return The decoded image from current data + */ +- (nullable UIImage *)incrementalDecodedImageWithOptions:(nullable SDImageCoderOptions *)options; + +@end + +#pragma mark - Animated Image Provider +/** + This is the animated image protocol to provide the basic function for animated image rendering. It's adopted by `SDAnimatedImage` and `SDAnimatedImageCoder` + */ +@protocol SDAnimatedImageProvider + +@required +/** + The original animated image data for current image. If current image is not an animated format, return nil. + We may use this method to grab back the original image data if need, such as NSCoding or compare. + + @return The animated image data + */ +@property (nonatomic, copy, readonly, nullable) NSData *animatedImageData; + +/** + Total animated frame count. + If the frame count is less than 1, then the methods below will be ignored. + + @return Total animated frame count. + */ +@property (nonatomic, assign, readonly) NSUInteger animatedImageFrameCount; +/** + Animation loop count, 0 means infinite looping. + + @return Animation loop count + */ +@property (nonatomic, assign, readonly) NSUInteger animatedImageLoopCount; +/** + Returns the frame image from a specified index. + @note The index maybe randomly if one image was set to different imageViews, keep it re-entrant. (It's not recommend to store the images into array because it's memory consuming) + + @param index Frame index (zero based). + @return Frame's image + */ +- (nullable UIImage *)animatedImageFrameAtIndex:(NSUInteger)index; +/** + Returns the frames's duration from a specified index. + @note The index maybe randomly if one image was set to different imageViews, keep it re-entrant. (It's recommend to store the durations into array because it's not memory-consuming) + + @param index Frame index (zero based). + @return Frame's duration + */ +- (NSTimeInterval)animatedImageDurationAtIndex:(NSUInteger)index; + +@end + +#pragma mark - Animated Coder +/** + This is the animated image coder protocol for custom animated image class like `SDAnimatedImage`. Through it inherit from `SDImageCoder`. We currentlly only use the method `canDecodeFromData:` to detect the proper coder for specify animated image format. + */ +@protocol SDAnimatedImageCoder + +@required +/** + Because animated image coder should keep the original data, we will alloc a new instance with the same class for the specify animated image data + The init method should return nil if it can't decode the specify animated image data to produce any frame. + After the instance created, we may call methods in `SDAnimatedImageProvider` to produce animated image frame. + + @param data The animated image data to be decode + @param options A dictionary containing any animated decoding options (instance-level). Pass @{SDImageCoderDecodeScaleFactor: @(1.0)} to specify scale factor for animated image (each frames should use the same scale). + @return A new instance to do animated decoding for specify image data + */ +- (nullable instancetype)initWithAnimatedImageData:(nullable NSData *)data options:(nullable SDImageCoderOptions *)options; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDImageCoder.m b/Pods/SDWebImage/SDWebImage/Core/SDImageCoder.m new file mode 100644 index 0000000..ca1febf --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDImageCoder.m @@ -0,0 +1,29 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDImageCoder.h" + +SDImageCoderOption const SDImageCoderDecodeFirstFrameOnly = @"decodeFirstFrameOnly"; +SDImageCoderOption const SDImageCoderDecodeScaleFactor = @"decodeScaleFactor"; +SDImageCoderOption const SDImageCoderDecodePreserveAspectRatio = @"decodePreserveAspectRatio"; +SDImageCoderOption const SDImageCoderDecodeThumbnailPixelSize = @"decodeThumbnailPixelSize"; +SDImageCoderOption const SDImageCoderDecodeFileExtensionHint = @"decodeFileExtensionHint"; +SDImageCoderOption const SDImageCoderDecodeTypeIdentifierHint = @"decodeTypeIdentifierHint"; +SDImageCoderOption const SDImageCoderDecodeUseLazyDecoding = @"decodeUseLazyDecoding"; +SDImageCoderOption const SDImageCoderDecodeScaleDownLimitBytes = @"decodeScaleDownLimitBytes"; +SDImageCoderOption const SDImageCoderDecodeToHDR = @"decodeToHDR"; + +SDImageCoderOption const SDImageCoderEncodeToHDR = @"encodeToHDR"; +SDImageCoderOption const SDImageCoderEncodeFirstFrameOnly = @"encodeFirstFrameOnly"; +SDImageCoderOption const SDImageCoderEncodeCompressionQuality = @"encodeCompressionQuality"; +SDImageCoderOption const SDImageCoderEncodeBackgroundColor = @"encodeBackgroundColor"; +SDImageCoderOption const SDImageCoderEncodeMaxPixelSize = @"encodeMaxPixelSize"; +SDImageCoderOption const SDImageCoderEncodeMaxFileSize = @"encodeMaxFileSize"; +SDImageCoderOption const SDImageCoderEncodeEmbedThumbnail = @"encodeEmbedThumbnail"; + +SDImageCoderOption const SDImageCoderWebImageContext = @"webImageContext"; diff --git a/Pods/SDWebImage/SDWebImage/Core/SDImageCoderHelper.h b/Pods/SDWebImage/SDWebImage/Core/SDImageCoderHelper.h new file mode 100644 index 0000000..f4b6f82 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDImageCoderHelper.h @@ -0,0 +1,250 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" +#import "SDImageFrame.h" + +/// The options controls how we force pre-draw the image (to avoid lazy-decoding). Which need OS's framework compatibility +typedef NS_ENUM(NSUInteger, SDImageCoderDecodeSolution) { + /// automatically choose the solution based on image format, hardware, OS version. This keep balance for compatibility and performance. Default after SDWebImage 5.13.0 + SDImageCoderDecodeSolutionAutomatic, + /// always use CoreGraphics to draw on bitmap context and trigger decode. Best compatibility. Default before SDWebImage 5.13.0 + SDImageCoderDecodeSolutionCoreGraphics, + /// available on iOS/tvOS 15+, use UIKit's new CGImageDecompressor/CMPhoto to decode. Best performance. If failed, will fallback to CoreGraphics as well + SDImageCoderDecodeSolutionUIKit +}; + +/// The policy to force-decode the origin CGImage (produced by Image Coder Plugin) +/// Some CGImage may be lazy, or not lazy, but need extra copy to render on screen +/// The force-decode step help to `pre-process` to get the best suitable CGImage to render, which can increase frame rate +/// The downside is that force-decode may consume RAM and CPU, and may loss the `lazy` support (lazy CGImage can be purged when memory warning, and re-created if need), see more: `SDImageCoderDecodeUseLazyDecoding` +typedef NS_ENUM(NSUInteger, SDImageForceDecodePolicy) { + /// Based on input CGImage's colorspace, alignment, bitmapinfo, if it may trigger `CA::copy_image` extra copy, we will force-decode, else don't + SDImageForceDecodePolicyAutomatic, + /// Never force decode input CGImage + SDImageForceDecodePolicyNever, + /// Always force decode input CGImage (only once) + SDImageForceDecodePolicyAlways +}; + +/// These enum is used to represent the High Dynamic Range type during image encoding/decoding. +/// There are alao other HDR type in history before ISO Standard (ISO 21496-1), including Google and Apple's old OSs captured photos, but which is non-standard and we do not support. +typedef NS_ENUM(NSUInteger, SDImageHDRType) { + /// SDR, mostly only 8 bits color per components, RGBA8 + SDImageHDRTypeSDR = 0, + /// ISO HDR (supported by modern format only, like HEIF/AVIF/JPEG-XL) + SDImageHDRTypeISOHDR = 1, + /// ISO Gain Map based HDR (supported by nearly all format, including tranditional JPEG, which stored the gain map into XMP) + SDImageHDRTypeISOGainMap = 2, +}; + +/// Byte alignment the bytes size with alignment +/// - Parameters: +/// - size: The bytes size +/// - alignment: The alignment, in bytes +static inline size_t SDByteAlign(size_t size, size_t alignment) { + return ((size + (alignment - 1)) / alignment) * alignment; +} + +/// The pixel format about the information to call `CGImageCreate` suitable for current hardware rendering +typedef struct SDImagePixelFormat { + /// Typically is pre-multiplied RGBA8888 for alpha image, RGBX8888 for non-alpha image. + CGBitmapInfo bitmapInfo; + /// Typically is 32, the 8 pixels bytesPerRow. + size_t alignment; +} SDImagePixelFormat; + +/** + Provide some common helper methods for building the image decoder/encoder. + */ +@interface SDImageCoderHelper : NSObject + +/** + Return an animated image with frames array. + For UIKit, this will apply the patch and then create animated UIImage. The patch is because that `+[UIImage animatedImageWithImages:duration:]` just use the average of duration for each image. So it will not work if different frame has different duration. Therefore we repeat the specify frame for specify times to let it work. + For AppKit, NSImage does not support animates other than GIF. This will try to encode the frames to GIF format and then create an animated NSImage for rendering. Attention the animated image may loss some detail if the input frames contain full alpha channel because GIF only supports 1 bit alpha channel. (For 1 pixel, either transparent or not) + + @param frames The frames array. If no frames or frames is empty, return nil + @return A animated image for rendering on UIImageView(UIKit) or NSImageView(AppKit) + */ ++ (UIImage * _Nullable)animatedImageWithFrames:(NSArray * _Nullable)frames; + +/** + Return frames array from an animated image. + For UIKit, this will unapply the patch for the description above and then create frames array. This will also work for normal animated UIImage. + For AppKit, NSImage does not support animates other than GIF. This will try to decode the GIF imageRep and then create frames array. + + @param animatedImage A animated image. If it's not animated, return nil + @return The frames array + */ ++ (NSArray * _Nullable)framesFromAnimatedImage:(UIImage * _Nullable)animatedImage NS_SWIFT_NAME(frames(from:)); + +#pragma mark - Preferred Rendering Format +/// For coders who use `CGImageCreate`, use the information below to create an effient CGImage which can be render on GPU without Core Animation's extra copy (`CA::Render::copy_image`), which can be debugged using `Color Copied Image` in Xcode Instruments +/// `CGImageCreate`'s `bytesPerRow`, `space`, `bitmapInfo` params should use the information below. +/** + Return the shared device-dependent RGB color space. This follows The Get Rule. + Because it's shared, you should not retain or release this object. + Typically is sRGB for iOS, screen color space (like Color LCD) for macOS. + + @return The device-dependent RGB color space + */ ++ (CGColorSpaceRef _Nonnull)colorSpaceGetDeviceRGB CF_RETURNS_NOT_RETAINED; + +/** + Tthis returns the pixel format **Preferred from current hardward && OS using runtime detection** + @param containsAlpha Whether the image to render contains alpha channel + */ ++ (SDImagePixelFormat)preferredPixelFormat:(BOOL)containsAlpha; + +/** + Check whether CGImage is hardware supported to rendering on screen, without the trigger of `CA::Render::copy_image` + You can debug the copied image by using Xcode's `Color Copied Image`, the copied image will turn Cyan and occupy double RAM for bitmap buffer. + Typically, when the CGImage's using the method above (`colorspace` / `alignment` / `bitmapInfo`) can render withtout the copy. + */ ++ (BOOL)CGImageIsHardwareSupported:(_Nonnull CGImageRef)cgImage; + +/** + Check whether CGImage contains alpha channel. + + @param cgImage The CGImage + @return Return YES if CGImage contains alpha channel, otherwise return NO + */ ++ (BOOL)CGImageContainsAlpha:(_Nonnull CGImageRef)cgImage; + +/** + Detect whether the CGImage is lazy and not-yet decoded. (lazy means, only when the caller access the underlying bitmap buffer via provider like `CGDataProviderCopyData` or `CGDataProviderRetainBytePtr`, the decoder will allocate memory, it's a lazy allocation) + The implementation use the Core Graphics internal to check whether the CGImage is `CGImageProvider` based, or `CGDataProvider` based. The `CGDataProvider` based is treated as non-lazy. + */ ++ (BOOL)CGImageIsLazy:(_Nonnull CGImageRef)cgImage; + +/** + Check if the CGImage is using HDR color space. + @note This use the same implementation like Apple, to checkl if color space uses transfer functions defined in ITU Rec.2100 + */ ++ (BOOL)CGImageIsHDR:(_Nonnull CGImageRef)cgImage; + +/** + Create a decoded CGImage by the provided CGImage. This follows The Create Rule and you are response to call release after usage. + It will detect whether image contains alpha channel, then create a new bitmap context with the same size of image, and draw it. This can ensure that the image do not need extra decoding after been set to the imageView. + @note This actually call `CGImageCreateDecoded:orientation:` with the Up orientation. + + @param cgImage The CGImage + @return A new created decoded image + */ ++ (CGImageRef _Nullable)CGImageCreateDecoded:(_Nonnull CGImageRef)cgImage CF_RETURNS_RETAINED; + +/** + Create a decoded CGImage by the provided CGImage and orientation. This follows The Create Rule and you are response to call release after usage. + It will detect whether image contains alpha channel, then create a new bitmap context with the same size of image, and draw it. This can ensure that the image do not need extra decoding after been set to the imageView. + + @param cgImage The CGImage + @param orientation The EXIF image orientation. + @return A new created decoded image + */ ++ (CGImageRef _Nullable)CGImageCreateDecoded:(_Nonnull CGImageRef)cgImage orientation:(CGImagePropertyOrientation)orientation CF_RETURNS_RETAINED; + +/** + Create a scaled CGImage by the provided CGImage and size. This follows The Create Rule and you are response to call release after usage. + It will detect whether the image size matching the scale size, if not, stretch the image to the target size. + @note If you need to keep aspect ratio, you can calculate the scale size by using `scaledSizeWithImageSize` first. + @note This scale does not change bits per components (which means RGB888 in, RGB888 out), supports 8/16/32(float) bpc. But the method in UIImage+Transform does not gurantee this. + @note All supported CGImage pixel format: https://developer.apple.com/library/archive/documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_context/dq_context.html#//apple_ref/doc/uid/TP30001066-CH203-BCIBHHBB + + @param cgImage The CGImage + @param size The scale size in pixel. + @return A new created scaled image + */ ++ (CGImageRef _Nullable)CGImageCreateScaled:(_Nonnull CGImageRef)cgImage size:(CGSize)size CF_RETURNS_RETAINED; + +/** Scale the image size based on provided scale size, whether or not to preserve aspect ratio, whether or not to scale up. + @note For example, if you implements thumnail decoding, pass `shouldScaleUp` to NO to avoid the calculated size larger than image size. + + @param imageSize The image size (in pixel or point defined by caller) + @param scaleSize The scale size (in pixel or point defined by caller) + @param preserveAspectRatio Whether or not to preserve aspect ratio + @param shouldScaleUp Whether or not to scale up (or scale down only) + */ ++ (CGSize)scaledSizeWithImageSize:(CGSize)imageSize scaleSize:(CGSize)scaleSize preserveAspectRatio:(BOOL)preserveAspectRatio shouldScaleUp:(BOOL)shouldScaleUp; + +/// Calculate the limited image size with the bytes, when using `SDImageCoderDecodeScaleDownLimitBytes`. This preserve aspect ratio and never scale up +/// @param imageSize The image size (in pixel or point defined by caller) +/// @param limitBytes The limit bytes +/// @param bytesPerPixel The bytes per pixel +/// @param frameCount The image frame count, 0 means 1 frame as well ++ (CGSize)scaledSizeWithImageSize:(CGSize)imageSize limitBytes:(NSUInteger)limitBytes bytesPerPixel:(NSUInteger)bytesPerPixel frameCount:(NSUInteger)frameCount; +/** + Return the decoded image by the provided image. This one unlike `CGImageCreateDecoded:`, will not decode the image which contains alpha channel or animated image. On iOS 15+, this may use `UIImage.preparingForDisplay()` to use CMPhoto for better performance than the old solution. + @param image The image to be decoded + @note This translate to `decodedImageWithImage:policy:` with automatic policy + @return The decoded image + */ ++ (UIImage * _Nullable)decodedImageWithImage:(UIImage * _Nullable)image; + +/** + Return the decoded image by the provided image. This one unlike `CGImageCreateDecoded:`, will not decode the image which contains alpha channel or animated image. On iOS 15+, this may use `UIImage.preparingForDisplay()` to use CMPhoto for better performance than the old solution. + @param image The image to be decoded + @param policy The force decode policy to decode image, will effect the check whether input image need decode + @return The decoded image + */ ++ (UIImage * _Nullable)decodedImageWithImage:(UIImage * _Nullable)image policy:(SDImageForceDecodePolicy)policy; + +/** + Return the decoded and probably scaled down image by the provided image. If the image pixels bytes size large than the limit bytes, will try to scale down. Or just works as `decodedImageWithImage:`, never scale up. + @warning You should not pass too small bytes, the suggestion value should be larger than 1MB. Even we use Tile Decoding to avoid OOM, however, small bytes will consume much more CPU time because we need to iterate more times to draw each tile. + + @param image The image to be decoded and scaled down + @param bytes The limit bytes size. Provide 0 to use the build-in limit. + @note This translate to `decodedAndScaledDownImageWithImage:limitBytes:policy:` with automatic policy + @return The decoded and probably scaled down image + */ ++ (UIImage * _Nullable)decodedAndScaledDownImageWithImage:(UIImage * _Nullable)image limitBytes:(NSUInteger)bytes; + +/** + Return the decoded and probably scaled down image by the provided image. If the image pixels bytes size large than the limit bytes, will try to scale down. Or just works as `decodedImageWithImage:`, never scale up. + @warning You should not pass too small bytes, the suggestion value should be larger than 1MB. Even we use Tile Decoding to avoid OOM, however, small bytes will consume much more CPU time because we need to iterate more times to draw each tile. + + @param image The image to be decoded and scaled down + @param bytes The limit bytes size. Provide 0 to use the build-in limit. + @param policy The force decode policy to decode image, will effect the check whether input image need decode + @return The decoded and probably scaled down image + */ ++ (UIImage * _Nullable)decodedAndScaledDownImageWithImage:(UIImage * _Nullable)image limitBytes:(NSUInteger)bytes policy:(SDImageForceDecodePolicy)policy; + +/** + Control the default force decode solution. Available solutions in `SDImageCoderDecodeSolution`. + @note Defaults to `SDImageCoderDecodeSolutionAutomatic`, which prefers to use UIKit for JPEG/HEIF, and fallback on CoreGraphics. If you want control on your hand, set the other solution. + */ +@property (class, readwrite) SDImageCoderDecodeSolution defaultDecodeSolution; + +/** + Control the default limit bytes to scale down largest images. + This value must be larger than 4 Bytes (at least 1x1 pixel). Defaults to 60MB on iOS/tvOS, 90MB on macOS, 30MB on watchOS. + */ +@property (class, readwrite) NSUInteger defaultScaleDownLimitBytes; + +#if SD_UIKIT || SD_WATCH +/** + Convert an EXIF image orientation to an iOS one. + + @param exifOrientation EXIF orientation + @return iOS orientation + */ ++ (UIImageOrientation)imageOrientationFromEXIFOrientation:(CGImagePropertyOrientation)exifOrientation NS_SWIFT_NAME(imageOrientation(from:)); + +/** + Convert an iOS orientation to an EXIF image orientation. + + @param imageOrientation iOS orientation + @return EXIF orientation + */ ++ (CGImagePropertyOrientation)exifOrientationFromImageOrientation:(UIImageOrientation)imageOrientation; +#endif + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDImageCoderHelper.m b/Pods/SDWebImage/SDWebImage/Core/SDImageCoderHelper.m new file mode 100644 index 0000000..5c2b345 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDImageCoderHelper.m @@ -0,0 +1,1112 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDImageCoderHelper.h" +#import "SDImageFrame.h" +#import "NSImage+Compatibility.h" +#import "NSData+ImageContentType.h" +#import "SDAnimatedImageRep.h" +#import "UIImage+ForceDecode.h" +#import "SDAssociatedObject.h" +#import "UIImage+Metadata.h" +#import "SDInternalMacros.h" +#import "SDGraphicsImageRenderer.h" +#import "SDInternalMacros.h" +#import "SDDeviceHelper.h" +#import "SDImageIOAnimatedCoderInternal.h" +#import + +#define kCGColorSpaceDeviceRGB CFSTR("kCGColorSpaceDeviceRGB") + +#if SD_UIKIT +static inline UIImage *SDImageDecodeUIKit(UIImage *image) { + // See: https://developer.apple.com/documentation/uikit/uiimage/3750834-imagebypreparingfordisplay + // Need CGImage-based + if (@available(iOS 15, tvOS 15, *)) { + UIImage *decodedImage = [image imageByPreparingForDisplay]; + if (decodedImage) { + SDImageCopyAssociatedObject(image, decodedImage); + decodedImage.sd_isDecoded = YES; + return decodedImage; + } + } + return nil; +} + +static inline UIImage *SDImageDecodeAndScaleDownUIKit(UIImage *image, CGSize destResolution) { + // See: https://developer.apple.com/documentation/uikit/uiimage/3750835-imagebypreparingthumbnailofsize + // Need CGImage-based + if (@available(iOS 15, tvOS 15, *)) { + // Calculate thumbnail point size + CGFloat scale = image.scale ?: 1; + CGSize thumbnailSize = CGSizeMake(destResolution.width / scale, destResolution.height / scale); + UIImage *decodedImage = [image imageByPreparingThumbnailOfSize:thumbnailSize]; + if (decodedImage) { + SDImageCopyAssociatedObject(image, decodedImage); + decodedImage.sd_isDecoded = YES; + return decodedImage; + } + } + return nil; +} + +static inline BOOL SDImageSupportsHardwareHEVCDecoder(void) { + static dispatch_once_t onceToken; + static BOOL supportsHardware = NO; + dispatch_once(&onceToken, ^{ + SEL DeviceInfoSelector = SD_SEL_SPI(deviceInfoForKey:); + NSString *HEVCDecoder8bitSupported = @"N8lZxRgC7lfdRS3dRLn+Ag"; +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-performSelector-leaks" + if ([UIDevice.currentDevice respondsToSelector:DeviceInfoSelector] && [UIDevice.currentDevice performSelector:DeviceInfoSelector withObject:HEVCDecoder8bitSupported]) { + supportsHardware = YES; + } +#pragma clang diagnostic pop + }); + return supportsHardware; +} +#endif + +static UIImage * _Nonnull SDImageGetAlphaDummyImage(void) { + static dispatch_once_t onceToken; + static UIImage *dummyImage; + dispatch_once(&onceToken, ^{ + SDGraphicsImageRendererFormat *format = [SDGraphicsImageRendererFormat preferredFormat]; + format.scale = 1; + format.opaque = NO; + CGSize size = CGSizeMake(1, 1); + SDGraphicsImageRenderer *renderer = [[SDGraphicsImageRenderer alloc] initWithSize:size format:format]; + dummyImage = [renderer imageWithActions:^(CGContextRef _Nonnull context) { + CGContextSetFillColorWithColor(context, UIColor.redColor.CGColor); + CGContextFillRect(context, CGRectMake(0, 0, size.width, size.height)); + }]; + NSCAssert(dummyImage, @"The sample alpha image (1x1 pixels) returns nil, OS bug ?"); + }); + return dummyImage; +} + +static UIImage * _Nonnull SDImageGetNonAlphaDummyImage(void) { + static dispatch_once_t onceToken; + static UIImage *dummyImage; + dispatch_once(&onceToken, ^{ + SDGraphicsImageRendererFormat *format = [SDGraphicsImageRendererFormat preferredFormat]; + format.scale = 1; + format.opaque = YES; + CGSize size = CGSizeMake(1, 1); + SDGraphicsImageRenderer *renderer = [[SDGraphicsImageRenderer alloc] initWithSize:size format:format]; + dummyImage = [renderer imageWithActions:^(CGContextRef _Nonnull context) { + CGContextSetFillColorWithColor(context, UIColor.redColor.CGColor); + CGContextFillRect(context, CGRectMake(0, 0, size.width, size.height)); + }]; + NSCAssert(dummyImage, @"The sample non-alpha image (1x1 pixels) returns nil, OS bug ?"); + }); + return dummyImage; +} + +static SDImageCoderDecodeSolution kDefaultDecodeSolution = SDImageCoderDecodeSolutionAutomatic; + +static const size_t kBytesPerPixel = 4; +static const size_t kBitsPerComponent = 8; + +static const CGFloat kBytesPerMB = 1024.0f * 1024.0f; +/* + * Defines the maximum size in MB of the decoded image when the flag `SDWebImageScaleDownLargeImages` is set + * Suggested value for iPad1 and iPhone 3GS: 60. + * Suggested value for iPad2 and iPhone 4: 120. + * Suggested value for iPhone 3G and iPod 2 and earlier devices: 30. + */ +#if SD_MAC +static CGFloat kDestImageLimitBytes = 90.f * kBytesPerMB; +#elif SD_UIKIT +static CGFloat kDestImageLimitBytes = 60.f * kBytesPerMB; +#elif SD_WATCH +static CGFloat kDestImageLimitBytes = 30.f * kBytesPerMB; +#endif + +static const CGFloat kDestSeemOverlap = 2.0f; // the numbers of pixels to overlap the seems where tiles meet. + +#if SD_MAC +@interface SDAnimatedImageRep (Private) +/// This wrap the animated image frames for legacy animated image coder API (`encodedDataWithImage:`). +@property (nonatomic, readwrite, weak) NSArray *frames; +@end +#endif + +@implementation SDImageCoderHelper + ++ (UIImage *)animatedImageWithFrames:(NSArray *)frames { + NSUInteger frameCount = frames.count; + if (frameCount == 0) { + return nil; + } + + UIImage *animatedImage; + +#if SD_UIKIT || SD_WATCH + NSUInteger durations[frameCount]; + for (size_t i = 0; i < frameCount; i++) { + durations[i] = frames[i].duration * 1000; + } + NSUInteger const gcd = gcdArray(frameCount, durations); + __block NSTimeInterval totalDuration = 0; + NSMutableArray *animatedImages = [NSMutableArray arrayWithCapacity:frameCount]; + [frames enumerateObjectsUsingBlock:^(SDImageFrame * _Nonnull frame, NSUInteger idx, BOOL * _Nonnull stop) { + UIImage *image = frame.image; + NSUInteger duration = frame.duration * 1000; + totalDuration += frame.duration; + NSUInteger repeatCount; + if (gcd) { + repeatCount = duration / gcd; + } else { + repeatCount = 1; + } + for (size_t i = 0; i < repeatCount; ++i) { + [animatedImages addObject:image]; + } + }]; + + animatedImage = [UIImage animatedImageWithImages:animatedImages duration:totalDuration]; + +#else + + NSMutableData *imageData = [NSMutableData data]; + CFStringRef imageUTType = [NSData sd_UTTypeFromImageFormat:SDImageFormatGIF]; + // Create an image destination. GIF does not support EXIF image orientation + CGImageDestinationRef imageDestination = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)imageData, imageUTType, frameCount, NULL); + if (!imageDestination) { + // Handle failure. + return nil; + } + + for (size_t i = 0; i < frameCount; i++) { + SDImageFrame *frame = frames[i]; + NSTimeInterval frameDuration = frame.duration; + CGImageRef frameImageRef = frame.image.CGImage; + NSDictionary *frameProperties = @{(__bridge NSString *)kCGImagePropertyGIFDictionary : @{(__bridge NSString *)kCGImagePropertyGIFDelayTime : @(frameDuration)}}; + CGImageDestinationAddImage(imageDestination, frameImageRef, (__bridge CFDictionaryRef)frameProperties); + } + // Finalize the destination. + if (CGImageDestinationFinalize(imageDestination) == NO) { + // Handle failure. + CFRelease(imageDestination); + return nil; + } + CFRelease(imageDestination); + CGFloat scale = MAX(frames.firstObject.image.scale, 1); + + SDAnimatedImageRep *imageRep = [[SDAnimatedImageRep alloc] initWithData:imageData]; + NSSize size = NSMakeSize(imageRep.pixelsWide / scale, imageRep.pixelsHigh / scale); + imageRep.size = size; + imageRep.frames = frames; // Weak assign to avoid effect lazy semantic of NSBitmapImageRep + animatedImage = [[NSImage alloc] initWithSize:size]; + [animatedImage addRepresentation:imageRep]; +#endif + + return animatedImage; +} + ++ (NSArray *)framesFromAnimatedImage:(UIImage *)animatedImage { + if (!animatedImage) { + return nil; + } + + NSMutableArray *frames; + NSUInteger frameCount = 0; + +#if SD_UIKIT || SD_WATCH + NSArray *animatedImages = animatedImage.images; + frameCount = animatedImages.count; + if (frameCount == 0) { + return nil; + } + frames = [NSMutableArray arrayWithCapacity:frameCount]; + + NSTimeInterval avgDuration = animatedImage.duration / frameCount; + if (avgDuration == 0) { + avgDuration = 0.1; // if it's a animated image but no duration, set it to default 100ms (this do not have that 10ms limit like GIF or WebP to allow custom coder provide the limit) + } + + __block NSUInteger repeatCount = 1; + __block UIImage *previousImage = animatedImages.firstObject; + [animatedImages enumerateObjectsUsingBlock:^(UIImage * _Nonnull image, NSUInteger idx, BOOL * _Nonnull stop) { + // ignore first + if (idx == 0) { + return; + } + if ([image isEqual:previousImage]) { + repeatCount++; + } else { + SDImageFrame *frame = [SDImageFrame frameWithImage:previousImage duration:avgDuration * repeatCount]; + [frames addObject:frame]; + repeatCount = 1; + } + previousImage = image; + }]; + // last one + SDImageFrame *frame = [SDImageFrame frameWithImage:previousImage duration:avgDuration * repeatCount]; + [frames addObject:frame]; + +#else + + NSRect imageRect = NSMakeRect(0, 0, animatedImage.size.width, animatedImage.size.height); + NSImageRep *imageRep = [animatedImage bestRepresentationForRect:imageRect context:nil hints:nil]; + // Check weak assigned frames firstly + if ([imageRep isKindOfClass:[SDAnimatedImageRep class]]) { + SDAnimatedImageRep *animatedImageRep = (SDAnimatedImageRep *)imageRep; + if (animatedImageRep.frames) { + return animatedImageRep.frames; + } + } + + NSBitmapImageRep *bitmapImageRep; + if ([imageRep isKindOfClass:[NSBitmapImageRep class]]) { + bitmapImageRep = (NSBitmapImageRep *)imageRep; + } + if (!bitmapImageRep) { + return nil; + } + frameCount = [[bitmapImageRep valueForProperty:NSImageFrameCount] unsignedIntegerValue]; + if (frameCount == 0) { + return nil; + } + frames = [NSMutableArray arrayWithCapacity:frameCount]; + CGFloat scale = animatedImage.scale; + + for (size_t i = 0; i < frameCount; i++) { + // NSBitmapImageRep need to manually change frame. "Good taste" API + [bitmapImageRep setProperty:NSImageCurrentFrame withValue:@(i)]; + NSTimeInterval frameDuration = [[bitmapImageRep valueForProperty:NSImageCurrentFrameDuration] doubleValue]; + NSImage *frameImage = [[NSImage alloc] initWithCGImage:bitmapImageRep.CGImage scale:scale orientation:kCGImagePropertyOrientationUp]; + SDImageFrame *frame = [SDImageFrame frameWithImage:frameImage duration:frameDuration]; + [frames addObject:frame]; + } +#endif + + return [frames copy]; +} + ++ (CGColorSpaceRef)colorSpaceGetDeviceRGB { +#if SD_MAC + NSScreen *mainScreen = nil; + if (@available(macOS 10.12, *)) { + mainScreen = [NSScreen mainScreen]; + } else { + mainScreen = [NSScreen screens].firstObject; + } + CGColorSpaceRef colorSpace = mainScreen.colorSpace.CGColorSpace; + return colorSpace; +#else + static CGColorSpaceRef colorSpace; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceSRGB); + }); + return colorSpace; +#endif +} + ++ (SDImagePixelFormat)preferredPixelFormat:(BOOL)containsAlpha { + CGImageRef cgImage; + if (containsAlpha) { + cgImage = SDImageGetAlphaDummyImage().CGImage; + } else { + cgImage = SDImageGetNonAlphaDummyImage().CGImage; + } + CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(cgImage); + size_t bitsPerComponent = 8; + if (SD_OPTIONS_CONTAINS(bitmapInfo, kCGBitmapFloatComponents)) { + bitsPerComponent = 16; + } + size_t components = 4; // Hardcode now + // https://github.com/path/FastImageCache#byte-alignment + // A properly aligned bytes-per-row value must be a multiple of 8 pixels × bytes per pixel. + size_t alignment = (bitsPerComponent / 8) * components * 8; + SDImagePixelFormat pixelFormat = { + .bitmapInfo = bitmapInfo, + .alignment = alignment + }; + return pixelFormat; +} + ++ (BOOL)CGImageIsHardwareSupported:(CGImageRef)cgImage { + BOOL supported = YES; + // 1. Check byte alignment + size_t bytesPerRow = CGImageGetBytesPerRow(cgImage); + BOOL hasAlpha = [self CGImageContainsAlpha:cgImage]; + SDImagePixelFormat pixelFormat = [self preferredPixelFormat:hasAlpha]; + if (SDByteAlign(bytesPerRow, pixelFormat.alignment) == bytesPerRow) { + // byte aligned, OK + supported &= YES; + } else { + // not aligned + supported &= NO; + } + if (!supported) return supported; + + // 2. Check color space + CGColorSpaceRef colorSpace = CGImageGetColorSpace(cgImage); + CGColorSpaceRef perferredColorSpace = [self colorSpaceGetDeviceRGB]; + if (colorSpace == perferredColorSpace) { + return supported; + } else { + if (@available(iOS 10.0, tvOS 10.0, macOS 10.6, watchOS 3.0, *)) { + NSString *colorspaceName = (__bridge_transfer NSString *)CGColorSpaceCopyName(colorSpace); + // Seems sRGB/deviceRGB always supported, P3 not always + if ([colorspaceName isEqualToString:(__bridge NSString *)kCGColorSpaceDeviceRGB] + || [colorspaceName isEqualToString:(__bridge NSString *)kCGColorSpaceSRGB]) { + supported &= YES; + } else { + supported &= NO; + } + return supported; + } else { + // Fallback on earlier versions + return supported; + } + } +} + ++ (BOOL)CGImageContainsAlpha:(CGImageRef)cgImage { + if (!cgImage) { + return NO; + } + CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(cgImage); + BOOL hasAlpha = !(alphaInfo == kCGImageAlphaNone || + alphaInfo == kCGImageAlphaNoneSkipFirst || + alphaInfo == kCGImageAlphaNoneSkipLast); + return hasAlpha; +} + ++ (BOOL)CGImageIsLazy:(CGImageRef)cgImage { + if (!cgImage) { + return NO; + } + // CoreGraphics use CGImage's C struct filed (offset 0xd8 on iOS 17.0) + // But since the description of `CGImageRef` always contains the `[DP]` (DataProvider) and `[IP]` (ImageProvider), we can use this as a hint + NSString *description = (__bridge_transfer NSString *)CFCopyDescription(cgImage); + if (description) { + // Solution 1: Parse the description to get provider + // (IP) -> YES + // (DP) -> NO + NSArray *lines = [description componentsSeparatedByString:@"\n"]; + if (lines.count > 0) { + NSString *firstLine = lines[0]; + NSRange startRange = [firstLine rangeOfString:@"("]; + NSRange endRange = [firstLine rangeOfString:@")"]; + if (startRange.location != NSNotFound && endRange.location != NSNotFound) { + NSRange resultRange = NSMakeRange(startRange.location + 1, endRange.location - startRange.location - 1); + NSString *providerString = [firstLine substringWithRange:resultRange]; + if ([providerString isEqualToString:@"IP"]) { + return YES; + } else if ([providerString isEqualToString:@"DP"]) { + return NO; + } else { + // New cases ? fallback + } + } + } + } + // Solution 2: Use UTI metadata + CFStringRef uttype = CGImageGetUTType(cgImage); + if (uttype) { + // Only ImageIO can set `com.apple.ImageIO.imageSourceTypeIdentifier` metadata for lazy decoded CGImage + return YES; + } else { + return NO; + } +} + ++ (BOOL)CGImageIsHDR:(_Nonnull CGImageRef)cgImage { + if (!cgImage) { + return NO; + } + if (@available(macOS 11.0, iOS 14, tvOS 14, watchOS 7.0, *)) { + CGColorSpaceRef colorSpace = CGImageGetColorSpace(cgImage); + if (colorSpace) { + // Actually `CGColorSpaceIsHDR` use the same impl, but deprecated + return CGColorSpaceUsesITUR_2100TF(colorSpace); + } + } + return NO; +} + ++ (CGImageRef)CGImageCreateDecoded:(CGImageRef)cgImage { + return [self CGImageCreateDecoded:cgImage orientation:kCGImagePropertyOrientationUp]; +} + ++ (CGImageRef)CGImageCreateDecoded:(CGImageRef)cgImage orientation:(CGImagePropertyOrientation)orientation { + if (!cgImage) { + return NULL; + } + size_t width = CGImageGetWidth(cgImage); + size_t height = CGImageGetHeight(cgImage); + if (width == 0 || height == 0) return NULL; + size_t newWidth; + size_t newHeight; + switch (orientation) { + case kCGImagePropertyOrientationLeft: + case kCGImagePropertyOrientationLeftMirrored: + case kCGImagePropertyOrientationRight: + case kCGImagePropertyOrientationRightMirrored: { + // These orientation should swap width & height + newWidth = height; + newHeight = width; + } + break; + default: { + newWidth = width; + newHeight = height; + } + break; + } + + BOOL hasAlpha = [self CGImageContainsAlpha:cgImage]; + // kCGImageAlphaNone is not supported in CGBitmapContextCreate. + // Check #3330 for more detail about why this bitmap is choosen. + // From v5.17.0, use runtime detection of bitmap info instead of hardcode. + CGBitmapInfo bitmapInfo = [SDImageCoderHelper preferredPixelFormat:hasAlpha].bitmapInfo; + CGContextRef context = CGBitmapContextCreate(NULL, newWidth, newHeight, 8, 0, [self colorSpaceGetDeviceRGB], bitmapInfo); + if (!context) { + return NULL; + } + + // Apply transform + CGAffineTransform transform = SDCGContextTransformFromOrientation(orientation, CGSizeMake(newWidth, newHeight)); + CGContextConcatCTM(context, transform); + CGContextDrawImage(context, CGRectMake(0, 0, width, height), cgImage); // The rect is bounding box of CGImage, don't swap width & height + CGImageRef newImageRef = CGBitmapContextCreateImage(context); + CGContextRelease(context); + + return newImageRef; +} + ++ (CGImageRef)CGImageCreateScaled:(CGImageRef)cgImage size:(CGSize)size { + if (!cgImage) { + return NULL; + } + if (size.width == 0 || size.height == 0) { + return NULL; + } + size_t width = CGImageGetWidth(cgImage); + size_t height = CGImageGetHeight(cgImage); + if (width == size.width && height == size.height) { + // Already same size + CGImageRetain(cgImage); + return cgImage; + } + size_t bitsPerComponent = CGImageGetBitsPerComponent(cgImage); + if (bitsPerComponent != 8 && bitsPerComponent != 16 && bitsPerComponent != 32) { + // Unsupported + return NULL; + } + size_t bitsPerPixel = CGImageGetBitsPerPixel(cgImage); + CGColorSpaceRef colorSpace = CGImageGetColorSpace(cgImage); + CGColorRenderingIntent renderingIntent = CGImageGetRenderingIntent(cgImage); + CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(cgImage); + CGImageAlphaInfo alphaInfo = bitmapInfo & kCGBitmapAlphaInfoMask; + CGImageByteOrderInfo byteOrderInfo = bitmapInfo & kCGBitmapByteOrderMask; + CGBitmapInfo alphaBitmapInfo = (uint32_t)byteOrderInfo; + + // Input need to convert with alpha + if (alphaInfo == kCGImageAlphaNone) { + // Convert RGB8/16/F -> ARGB8/16/F + alphaBitmapInfo |= kCGImageAlphaFirst; + } else { + alphaBitmapInfo |= alphaInfo; + } + uint32_t components; + if (alphaInfo == kCGImageAlphaOnly) { + // Alpha only, simple to 1 channel + components = 1; + } else { + components = 4; + } + if (SD_OPTIONS_CONTAINS(bitmapInfo, kCGBitmapFloatComponents)) { + // Keep float components + alphaBitmapInfo |= kCGBitmapFloatComponents; + } + __block vImage_Buffer input_buffer = {}, output_buffer = {}; + @onExit { + if (input_buffer.data) free(input_buffer.data); + if (output_buffer.data) free(output_buffer.data); + }; + // Always provide alpha channel + vImage_CGImageFormat format = (vImage_CGImageFormat) { + .bitsPerComponent = (uint32_t)bitsPerComponent, + .bitsPerPixel = (uint32_t)bitsPerComponent * components, + .colorSpace = colorSpace, + .bitmapInfo = alphaBitmapInfo, + .version = 0, + .decode = NULL, + .renderingIntent = renderingIntent + }; + // input + vImage_Error ret = vImageBuffer_InitWithCGImage(&input_buffer, &format, NULL, cgImage, kvImageNoFlags); + if (ret != kvImageNoError) return NULL; + // output + vImageBuffer_Init(&output_buffer, size.height, size.width, (uint32_t)bitsPerComponent * components, kvImageNoFlags); + if (!output_buffer.data) return NULL; + + if (components == 4) { + if (bitsPerComponent == 32) { + ret = vImageScale_ARGBFFFF(&input_buffer, &output_buffer, NULL, kvImageHighQualityResampling); + } else if (bitsPerComponent == 16) { + ret = vImageScale_ARGB16U(&input_buffer, &output_buffer, NULL, kvImageHighQualityResampling); + } else if (bitsPerComponent == 8) { + ret = vImageScale_ARGB8888(&input_buffer, &output_buffer, NULL, kvImageHighQualityResampling); + } + } else { + if (bitsPerComponent == 32) { + ret = vImageScale_PlanarF(&input_buffer, &output_buffer, NULL, kvImageHighQualityResampling); + } else if (bitsPerComponent == 16) { + ret = vImageScale_Planar16U(&input_buffer, &output_buffer, NULL, kvImageHighQualityResampling); + } else if (bitsPerComponent == 8) { + ret = vImageScale_Planar8(&input_buffer, &output_buffer, NULL, kvImageHighQualityResampling); + } + } + if (ret != kvImageNoError) return NULL; + + // Convert back to non-alpha for RGB input to preserve pixel format + if (alphaInfo == kCGImageAlphaNone) { + // in-place, no extra allocation + if (bitsPerComponent == 32) { + ret = vImageConvert_ARGBFFFFtoRGBFFF(&output_buffer, &output_buffer, kvImageNoFlags); + } else if (bitsPerComponent == 16) { + ret = vImageConvert_ARGB16UtoRGB16U(&output_buffer, &output_buffer, kvImageNoFlags); + } else if (bitsPerComponent == 8) { + ret = vImageConvert_ARGB8888toRGB888(&output_buffer, &output_buffer, kvImageNoFlags); + } + if (ret != kvImageNoError) return NULL; + } + vImage_CGImageFormat output_format = (vImage_CGImageFormat) { + .bitsPerComponent = (uint32_t)bitsPerComponent, + .bitsPerPixel = (uint32_t)bitsPerPixel, + .colorSpace = colorSpace, + .bitmapInfo = bitmapInfo, + .version = 0, + .decode = NULL, + .renderingIntent = renderingIntent + }; + CGImageRef outputImage = vImageCreateCGImageFromBuffer(&output_buffer, &output_format, NULL, NULL, kvImageNoFlags, &ret); + if (ret != kvImageNoError) { + CGImageRelease(outputImage); + return NULL; + } + + return outputImage; +} + ++ (CGSize)scaledSizeWithImageSize:(CGSize)imageSize scaleSize:(CGSize)scaleSize preserveAspectRatio:(BOOL)preserveAspectRatio shouldScaleUp:(BOOL)shouldScaleUp { + CGFloat width = imageSize.width; + CGFloat height = imageSize.height; + CGFloat resultWidth; + CGFloat resultHeight; + + if (width <= 0 || height <= 0 || scaleSize.width <= 0 || scaleSize.height <= 0) { + // Protect + resultWidth = width; + resultHeight = height; + } else { + // Scale to fit + if (preserveAspectRatio) { + CGFloat pixelRatio = width / height; + CGFloat scaleRatio = scaleSize.width / scaleSize.height; + if (pixelRatio > scaleRatio) { + resultWidth = scaleSize.width; + resultHeight = ceil(scaleSize.width / pixelRatio); + } else { + resultHeight = scaleSize.height; + resultWidth = ceil(scaleSize.height * pixelRatio); + } + } else { + // Stretch + resultWidth = scaleSize.width; + resultHeight = scaleSize.height; + } + if (!shouldScaleUp) { + // Scale down only + resultWidth = MIN(width, resultWidth); + resultHeight = MIN(height, resultHeight); + } + } + + return CGSizeMake(resultWidth, resultHeight); +} + ++ (CGSize)scaledSizeWithImageSize:(CGSize)imageSize limitBytes:(NSUInteger)limitBytes bytesPerPixel:(NSUInteger)bytesPerPixel frameCount:(NSUInteger)frameCount { + if (CGSizeEqualToSize(imageSize, CGSizeZero)) return CGSizeMake(1, 1); + NSUInteger totalFramePixelSize = limitBytes / bytesPerPixel / (frameCount ?: 1); + CGFloat ratio = imageSize.height / imageSize.width; + CGFloat width = sqrt(totalFramePixelSize / ratio); + CGFloat height = width * ratio; + width = MAX(1, floor(width)); + height = MAX(1, floor(height)); + CGSize size = CGSizeMake(width, height); + + return size; +} + ++ (UIImage *)decodedImageWithImage:(UIImage *)image { + return [self decodedImageWithImage:image policy:SDImageForceDecodePolicyAutomatic]; +} + ++ (UIImage *)decodedImageWithImage:(UIImage *)image policy:(SDImageForceDecodePolicy)policy { + if (![self shouldDecodeImage:image policy:policy]) { + return image; + } + + UIImage *decodedImage; + SDImageCoderDecodeSolution decodeSolution = self.defaultDecodeSolution; +#if SD_UIKIT + if (decodeSolution == SDImageCoderDecodeSolutionAutomatic) { + // See #3365, CMPhoto iOS 15 only supports JPEG/HEIF format, or it will print an error log :( + SDImageFormat format = image.sd_imageFormat; + if ((format == SDImageFormatHEIC || format == SDImageFormatHEIF) && SDImageSupportsHardwareHEVCDecoder()) { + decodedImage = SDImageDecodeUIKit(image); + } else if (format == SDImageFormatJPEG) { + decodedImage = SDImageDecodeUIKit(image); + } + } else if (decodeSolution == SDImageCoderDecodeSolutionUIKit) { + // Arbitrarily call CMPhoto + decodedImage = SDImageDecodeUIKit(image); + } + if (decodedImage) { + return decodedImage; + } +#endif + + CGImageRef imageRef = image.CGImage; + if (!imageRef) { + // Only decode for CGImage-based + return image; + } + + if (decodeSolution == SDImageCoderDecodeSolutionCoreGraphics) { + CGImageRef decodedImageRef = [self CGImageCreateDecoded:imageRef]; +#if SD_MAC + decodedImage = [[UIImage alloc] initWithCGImage:decodedImageRef scale:image.scale orientation:kCGImagePropertyOrientationUp]; +#else + decodedImage = [[UIImage alloc] initWithCGImage:decodedImageRef scale:image.scale orientation:image.imageOrientation]; +#endif + CGImageRelease(decodedImageRef); + } else { + // Prefer to use new Image Renderer to re-draw image, instead of low-level CGBitmapContext and CGContextDrawImage + // This can keep both OS compatible and don't fight with Apple's performance optimization + SDGraphicsImageRendererFormat *format = SDGraphicsImageRendererFormat.preferredFormat; + // To support most OS compatible like Dynamic Range, prefer the image level format +#if SD_UIKIT + if (@available(iOS 10.0, tvOS 10.0, *)) { + format.uiformat = image.imageRendererFormat; + } else { +#endif + format.opaque = ![self CGImageContainsAlpha:imageRef];; + format.scale = image.scale; +#if SD_UIKIT + } +#endif + CGSize imageSize = image.size; + SDGraphicsImageRenderer *renderer = [[SDGraphicsImageRenderer alloc] initWithSize:imageSize format:format]; + decodedImage = [renderer imageWithActions:^(CGContextRef _Nonnull context) { + [image drawInRect:CGRectMake(0, 0, imageSize.width, imageSize.height)]; + }]; + } + SDImageCopyAssociatedObject(image, decodedImage); + decodedImage.sd_isDecoded = YES; + return decodedImage; +} + ++ (UIImage *)decodedAndScaledDownImageWithImage:(UIImage *)image limitBytes:(NSUInteger)bytes { + return [self decodedAndScaledDownImageWithImage:image limitBytes:bytes policy:SDImageForceDecodePolicyAutomatic]; +} + ++ (UIImage *)decodedAndScaledDownImageWithImage:(UIImage *)image limitBytes:(NSUInteger)bytes policy:(SDImageForceDecodePolicy)policy { + if (![self shouldDecodeImage:image policy:policy]) { + return image; + } + + CGFloat destTotalPixels; + CGFloat tileTotalPixels; + if (bytes == 0) { + bytes = [self defaultScaleDownLimitBytes]; + } + bytes = MAX(bytes, kBytesPerPixel); + destTotalPixels = bytes / kBytesPerPixel; + tileTotalPixels = destTotalPixels / 3; + + CGImageRef sourceImageRef = image.CGImage; + if (!sourceImageRef) { + // Only decode for CGImage-based + return image; + } + CGSize sourceResolution = CGSizeZero; + sourceResolution.width = CGImageGetWidth(sourceImageRef); + sourceResolution.height = CGImageGetHeight(sourceImageRef); + + if (![self shouldScaleDownImagePixelSize:sourceResolution limitBytes:bytes]) { + return [self decodedImageWithImage:image]; + } + + CGFloat sourceTotalPixels = sourceResolution.width * sourceResolution.height; + // Determine the scale ratio to apply to the input image + // that results in an output image of the defined size. + // see kDestImageSizeMB, and how it relates to destTotalPixels. + CGFloat imageScale = sqrt(destTotalPixels / sourceTotalPixels); + CGSize destResolution = CGSizeZero; + destResolution.width = MAX(1, (int)(sourceResolution.width * imageScale)); + destResolution.height = MAX(1, (int)(sourceResolution.height * imageScale)); + + UIImage *decodedImage; +#if SD_UIKIT + SDImageCoderDecodeSolution decodeSolution = self.defaultDecodeSolution; + if (decodeSolution == SDImageCoderDecodeSolutionAutomatic) { + // See #3365, CMPhoto iOS 15 only supports JPEG/HEIF format, or it will print an error log :( + SDImageFormat format = image.sd_imageFormat; + if ((format == SDImageFormatHEIC || format == SDImageFormatHEIF) && SDImageSupportsHardwareHEVCDecoder()) { + decodedImage = SDImageDecodeAndScaleDownUIKit(image, destResolution); + } else if (format == SDImageFormatJPEG) { + decodedImage = SDImageDecodeAndScaleDownUIKit(image, destResolution); + } + } else if (decodeSolution == SDImageCoderDecodeSolutionUIKit) { + // Arbitrarily call CMPhoto + decodedImage = SDImageDecodeAndScaleDownUIKit(image, destResolution); + } + if (decodedImage) { + return decodedImage; + } +#endif + + // autorelease the bitmap context and all vars to help system to free memory when there are memory warning. + // on iOS7, do not forget to call [[SDImageCache sharedImageCache] clearMemory]; + @autoreleasepool { + // device color space + CGColorSpaceRef colorspaceRef = [self colorSpaceGetDeviceRGB]; + BOOL hasAlpha = [self CGImageContainsAlpha:sourceImageRef]; + + // kCGImageAlphaNone is not supported in CGBitmapContextCreate. + // Check #3330 for more detail about why this bitmap is choosen. + // From v5.17.0, use runtime detection of bitmap info instead of hardcode. + CGBitmapInfo bitmapInfo = [SDImageCoderHelper preferredPixelFormat:hasAlpha].bitmapInfo; + CGContextRef destContext = CGBitmapContextCreate(NULL, + destResolution.width, + destResolution.height, + kBitsPerComponent, + 0, + colorspaceRef, + bitmapInfo); + + if (destContext == NULL) { + return image; + } + CGContextSetInterpolationQuality(destContext, kCGInterpolationHigh); + + // Now define the size of the rectangle to be used for the + // incremental bits from the input image to the output image. + // we use a source tile width equal to the width of the source + // image due to the way that iOS retrieves image data from disk. + // iOS must decode an image from disk in full width 'bands', even + // if current graphics context is clipped to a subrect within that + // band. Therefore we fully utilize all of the pixel data that results + // from a decoding operation by anchoring our tile size to the full + // width of the input image. + CGRect sourceTile = CGRectZero; + sourceTile.size.width = sourceResolution.width; + // The source tile height is dynamic. Since we specified the size + // of the source tile in MB, see how many rows of pixels high it + // can be given the input image width. + sourceTile.size.height = MAX(1, (int)(tileTotalPixels / sourceTile.size.width)); + sourceTile.origin.x = 0.0f; + // The output tile is the same proportions as the input tile, but + // scaled to image scale. + CGRect destTile; + destTile.size.width = destResolution.width; + destTile.size.height = sourceTile.size.height * imageScale; + destTile.origin.x = 0.0f; + // The source seem overlap is proportionate to the destination seem overlap. + // this is the amount of pixels to overlap each tile as we assemble the output image. + float sourceSeemOverlap = (int)((kDestSeemOverlap/destResolution.height)*sourceResolution.height); + CGImageRef sourceTileImageRef; + // calculate the number of read/write operations required to assemble the + // output image. + int iterations = (int)( sourceResolution.height / sourceTile.size.height ); + // If tile height doesn't divide the image height evenly, add another iteration + // to account for the remaining pixels. + int remainder = (int)sourceResolution.height % (int)sourceTile.size.height; + if(remainder) { + iterations++; + } + // Add seem overlaps to the tiles, but save the original tile height for y coordinate calculations. + float sourceTileHeightMinusOverlap = sourceTile.size.height; + sourceTile.size.height += sourceSeemOverlap; + destTile.size.height += kDestSeemOverlap; + for( int y = 0; y < iterations; ++y ) { + sourceTile.origin.y = y * sourceTileHeightMinusOverlap + sourceSeemOverlap; + destTile.origin.y = destResolution.height - (( y + 1 ) * sourceTileHeightMinusOverlap * imageScale + kDestSeemOverlap); + sourceTileImageRef = CGImageCreateWithImageInRect( sourceImageRef, sourceTile ); + if( y == iterations - 1 && remainder ) { + float dify = destTile.size.height; + destTile.size.height = CGImageGetHeight( sourceTileImageRef ) * imageScale + kDestSeemOverlap; + dify -= destTile.size.height; + destTile.origin.y = MIN(0, destTile.origin.y + dify); + } + CGContextDrawImage( destContext, destTile, sourceTileImageRef ); + CGImageRelease( sourceTileImageRef ); + } + + CGImageRef destImageRef = CGBitmapContextCreateImage(destContext); + CGContextRelease(destContext); + if (destImageRef == NULL) { + return image; + } +#if SD_MAC + decodedImage = [[UIImage alloc] initWithCGImage:destImageRef scale:image.scale orientation:kCGImagePropertyOrientationUp]; +#else + decodedImage = [[UIImage alloc] initWithCGImage:destImageRef scale:image.scale orientation:image.imageOrientation]; +#endif + CGImageRelease(destImageRef); + SDImageCopyAssociatedObject(image, decodedImage); + decodedImage.sd_isDecoded = YES; + return decodedImage; + } +} + ++ (SDImageCoderDecodeSolution)defaultDecodeSolution { + return kDefaultDecodeSolution; +} + ++ (void)setDefaultDecodeSolution:(SDImageCoderDecodeSolution)defaultDecodeSolution { + kDefaultDecodeSolution = defaultDecodeSolution; +} + ++ (NSUInteger)defaultScaleDownLimitBytes { + return kDestImageLimitBytes; +} + ++ (void)setDefaultScaleDownLimitBytes:(NSUInteger)defaultScaleDownLimitBytes { + if (defaultScaleDownLimitBytes < kBytesPerPixel) { + return; + } + kDestImageLimitBytes = defaultScaleDownLimitBytes; +} + +#if SD_UIKIT || SD_WATCH +// Convert an EXIF image orientation to an iOS one. ++ (UIImageOrientation)imageOrientationFromEXIFOrientation:(CGImagePropertyOrientation)exifOrientation { + UIImageOrientation imageOrientation = UIImageOrientationUp; + switch (exifOrientation) { + case kCGImagePropertyOrientationUp: + imageOrientation = UIImageOrientationUp; + break; + case kCGImagePropertyOrientationDown: + imageOrientation = UIImageOrientationDown; + break; + case kCGImagePropertyOrientationLeft: + imageOrientation = UIImageOrientationLeft; + break; + case kCGImagePropertyOrientationRight: + imageOrientation = UIImageOrientationRight; + break; + case kCGImagePropertyOrientationUpMirrored: + imageOrientation = UIImageOrientationUpMirrored; + break; + case kCGImagePropertyOrientationDownMirrored: + imageOrientation = UIImageOrientationDownMirrored; + break; + case kCGImagePropertyOrientationLeftMirrored: + imageOrientation = UIImageOrientationLeftMirrored; + break; + case kCGImagePropertyOrientationRightMirrored: + imageOrientation = UIImageOrientationRightMirrored; + break; + default: + break; + } + return imageOrientation; +} + +// Convert an iOS orientation to an EXIF image orientation. ++ (CGImagePropertyOrientation)exifOrientationFromImageOrientation:(UIImageOrientation)imageOrientation { + CGImagePropertyOrientation exifOrientation = kCGImagePropertyOrientationUp; + switch (imageOrientation) { + case UIImageOrientationUp: + exifOrientation = kCGImagePropertyOrientationUp; + break; + case UIImageOrientationDown: + exifOrientation = kCGImagePropertyOrientationDown; + break; + case UIImageOrientationLeft: + exifOrientation = kCGImagePropertyOrientationLeft; + break; + case UIImageOrientationRight: + exifOrientation = kCGImagePropertyOrientationRight; + break; + case UIImageOrientationUpMirrored: + exifOrientation = kCGImagePropertyOrientationUpMirrored; + break; + case UIImageOrientationDownMirrored: + exifOrientation = kCGImagePropertyOrientationDownMirrored; + break; + case UIImageOrientationLeftMirrored: + exifOrientation = kCGImagePropertyOrientationLeftMirrored; + break; + case UIImageOrientationRightMirrored: + exifOrientation = kCGImagePropertyOrientationRightMirrored; + break; + default: + break; + } + return exifOrientation; +} +#endif + +#pragma mark - Helper Function ++ (BOOL)shouldDecodeImage:(nullable UIImage *)image policy:(SDImageForceDecodePolicy)policy { + // Prevent "CGBitmapContextCreateImage: invalid context 0x0" error + if (image == nil) { + return NO; + } + // Check policy (never) + if (policy == SDImageForceDecodePolicyNever) { + return NO; + } + // Avoid extra decode + if (image.sd_isDecoded) { + return NO; + } + // do not decode animated images + if (image.sd_isAnimated) { + return NO; + } + // do not decode vector images + if (image.sd_isVector) { + return NO; + } + // FIXME: currently our force decode solution is buggy on HDR CGImage + if (image.sd_isHighDynamicRange) { + return NO; + } + // Check policy (always) + if (policy == SDImageForceDecodePolicyAlways) { + return YES; + } else { + // Check policy (automatic) + CGImageRef cgImage = image.CGImage; + if (cgImage) { + // Check if it's lazy CGImage wrapper or not + BOOL isLazy = [SDImageCoderHelper CGImageIsLazy:cgImage]; + if (isLazy) { + // Lazy CGImage should trigger force decode before rendering + return YES; + } else { + // Now, let's check if this non-lazy CGImage is hardware supported (not byte-aligned will cause extra copy) + BOOL isSupported = [SDImageCoderHelper CGImageIsHardwareSupported:cgImage]; + return !isSupported; + } + } + } + + return YES; +} + ++ (BOOL)shouldScaleDownImagePixelSize:(CGSize)sourceResolution limitBytes:(NSUInteger)bytes { + BOOL shouldScaleDown = YES; + + CGFloat sourceTotalPixels = sourceResolution.width * sourceResolution.height; + if (sourceTotalPixels <= 0) { + return NO; + } + CGFloat destTotalPixels; + if (bytes == 0) { + bytes = [self defaultScaleDownLimitBytes]; + } + bytes = MAX(bytes, kBytesPerPixel); + destTotalPixels = bytes / kBytesPerPixel; + CGFloat imageScale = destTotalPixels / sourceTotalPixels; + if (imageScale < 1) { + shouldScaleDown = YES; + } else { + shouldScaleDown = NO; + } + + return shouldScaleDown; +} + +static inline CGAffineTransform SDCGContextTransformFromOrientation(CGImagePropertyOrientation orientation, CGSize size) { + // Inspiration from @libfeihu + // We need to calculate the proper transformation to make the image upright. + // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored. + CGAffineTransform transform = CGAffineTransformIdentity; + + switch (orientation) { + case kCGImagePropertyOrientationDown: + case kCGImagePropertyOrientationDownMirrored: + transform = CGAffineTransformTranslate(transform, size.width, size.height); + transform = CGAffineTransformRotate(transform, M_PI); + break; + + case kCGImagePropertyOrientationLeft: + case kCGImagePropertyOrientationLeftMirrored: + transform = CGAffineTransformTranslate(transform, size.width, 0); + transform = CGAffineTransformRotate(transform, M_PI_2); + break; + + case kCGImagePropertyOrientationRight: + case kCGImagePropertyOrientationRightMirrored: + transform = CGAffineTransformTranslate(transform, 0, size.height); + transform = CGAffineTransformRotate(transform, -M_PI_2); + break; + case kCGImagePropertyOrientationUp: + case kCGImagePropertyOrientationUpMirrored: + break; + } + + switch (orientation) { + case kCGImagePropertyOrientationUpMirrored: + case kCGImagePropertyOrientationDownMirrored: + transform = CGAffineTransformTranslate(transform, size.width, 0); + transform = CGAffineTransformScale(transform, -1, 1); + break; + + case kCGImagePropertyOrientationLeftMirrored: + case kCGImagePropertyOrientationRightMirrored: + transform = CGAffineTransformTranslate(transform, size.height, 0); + transform = CGAffineTransformScale(transform, -1, 1); + break; + case kCGImagePropertyOrientationUp: + case kCGImagePropertyOrientationDown: + case kCGImagePropertyOrientationLeft: + case kCGImagePropertyOrientationRight: + break; + } + + return transform; +} + +#if SD_UIKIT || SD_WATCH +static NSUInteger gcd(NSUInteger a, NSUInteger b) { + NSUInteger c; + while (a != 0) { + c = a; + a = b % a; + b = c; + } + return b; +} + +static NSUInteger gcdArray(size_t const count, NSUInteger const * const values) { + if (count == 0) { + return 0; + } + NSUInteger result = values[0]; + for (size_t i = 1; i < count; ++i) { + result = gcd(values[i], result); + } + return result; +} +#endif + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDImageCodersManager.h b/Pods/SDWebImage/SDWebImage/Core/SDImageCodersManager.h new file mode 100644 index 0000000..14b655d --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDImageCodersManager.h @@ -0,0 +1,58 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDImageCoder.h" + +/** + Global object holding the array of coders, so that we avoid passing them from object to object. + Uses a priority queue behind scenes, which means the latest added coders have the highest priority. + This is done so when encoding/decoding something, we go through the list and ask each coder if they can handle the current data. + That way, users can add their custom coders while preserving our existing prebuilt ones + + Note: the `coders` getter will return the coders in their reversed order + Example: + - by default we internally set coders = `IOCoder`, `GIFCoder`, `APNGCoder` + - calling `coders` will return `@[IOCoder, GIFCoder, APNGCoder]` + - call `[addCoder:[MyCrazyCoder new]]` + - calling `coders` now returns `@[IOCoder, GIFCoder, APNGCoder, MyCrazyCoder]` + + Coders + ------ + A coder must conform to the `SDImageCoder` protocol or even to `SDProgressiveImageCoder` if it supports progressive decoding + Conformance is important because that way, they will implement `canDecodeFromData` or `canEncodeToFormat` + Those methods are called on each coder in the array (using the priority order) until one of them returns YES. + That means that coder can decode that data / encode to that format + */ +@interface SDImageCodersManager : NSObject + +/** + Returns the global shared coders manager instance. + */ +@property (nonatomic, class, readonly, nonnull) SDImageCodersManager *sharedManager; + +/** + All coders in coders manager. The coders array is a priority queue, which means the later added coder will have the highest priority + */ +@property (nonatomic, copy, nullable) NSArray> *coders; + +/** + Add a new coder to the end of coders array. Which has the highest priority. + + @param coder coder + */ +- (void)addCoder:(nonnull id)coder; + +/** + Remove a coder in the coders array. + + @param coder coder + */ +- (void)removeCoder:(nonnull id)coder; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDImageCodersManager.m b/Pods/SDWebImage/SDWebImage/Core/SDImageCodersManager.m new file mode 100644 index 0000000..0abb962 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDImageCodersManager.m @@ -0,0 +1,145 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDImageCodersManager.h" +#import "SDImageIOCoder.h" +#import "SDImageGIFCoder.h" +#import "SDImageAPNGCoder.h" +#import "SDImageHEICCoder.h" +#import "SDInternalMacros.h" + +@interface SDImageCodersManager () + +@property (nonatomic, strong, nonnull) NSMutableArray> *imageCoders; + +@end + +@implementation SDImageCodersManager { + SD_LOCK_DECLARE(_codersLock); +} + ++ (nonnull instancetype)sharedManager { + static dispatch_once_t once; + static id instance; + dispatch_once(&once, ^{ + instance = [self new]; + }); + return instance; +} + +- (instancetype)init { + if (self = [super init]) { + // initialize with default coders + _imageCoders = [NSMutableArray arrayWithArray:@[[SDImageIOCoder sharedCoder], [SDImageGIFCoder sharedCoder], [SDImageAPNGCoder sharedCoder]]]; + SD_LOCK_INIT(_codersLock); + } + return self; +} + +- (NSArray> *)coders { + SD_LOCK(_codersLock); + NSArray> *coders = [_imageCoders copy]; + SD_UNLOCK(_codersLock); + return coders; +} + +- (void)setCoders:(NSArray> *)coders { + SD_LOCK(_codersLock); + [_imageCoders removeAllObjects]; + if (coders.count) { + [_imageCoders addObjectsFromArray:coders]; + } + SD_UNLOCK(_codersLock); +} + +#pragma mark - Coder IO operations + +- (void)addCoder:(nonnull id)coder { + if (![coder conformsToProtocol:@protocol(SDImageCoder)]) { + return; + } + SD_LOCK(_codersLock); + [_imageCoders addObject:coder]; + SD_UNLOCK(_codersLock); +} + +- (void)removeCoder:(nonnull id)coder { + if (![coder conformsToProtocol:@protocol(SDImageCoder)]) { + return; + } + SD_LOCK(_codersLock); + [_imageCoders removeObject:coder]; + SD_UNLOCK(_codersLock); +} + +#pragma mark - SDImageCoder +- (BOOL)canDecodeFromData:(NSData *)data { + NSArray> *coders = self.coders; + for (id coder in coders.reverseObjectEnumerator) { + if ([coder canDecodeFromData:data]) { + return YES; + } + } + return NO; +} + +- (BOOL)canEncodeToFormat:(SDImageFormat)format { + NSArray> *coders = self.coders; + for (id coder in coders.reverseObjectEnumerator) { + if ([coder canEncodeToFormat:format]) { + return YES; + } + } + return NO; +} + +- (UIImage *)decodedImageWithData:(NSData *)data options:(nullable SDImageCoderOptions *)options { + if (!data) { + return nil; + } + UIImage *image; + NSArray> *coders = self.coders; + for (id coder in coders.reverseObjectEnumerator) { + if ([coder canDecodeFromData:data]) { + image = [coder decodedImageWithData:data options:options]; + break; + } + } + + return image; +} + +- (NSData *)encodedDataWithImage:(UIImage *)image format:(SDImageFormat)format options:(nullable SDImageCoderOptions *)options { + if (!image) { + return nil; + } + NSArray> *coders = self.coders; + for (id coder in coders.reverseObjectEnumerator) { + if ([coder canEncodeToFormat:format]) { + return [coder encodedDataWithImage:image format:format options:options]; + } + } + return nil; +} + +- (NSData *)encodedDataWithFrames:(NSArray *)frames loopCount:(NSUInteger)loopCount format:(SDImageFormat)format options:(SDImageCoderOptions *)options { + if (!frames || frames.count < 1) { + return nil; + } + NSArray> *coders = self.coders; + for (id coder in coders.reverseObjectEnumerator) { + if ([coder canEncodeToFormat:format]) { + if ([coder respondsToSelector:@selector(encodedDataWithFrames:loopCount:format:options:)]) { + return [coder encodedDataWithFrames:frames loopCount:loopCount format:format options:options]; + } + } + } + return nil; +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDImageFrame.h b/Pods/SDWebImage/SDWebImage/Core/SDImageFrame.h new file mode 100644 index 0000000..41f3965 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDImageFrame.h @@ -0,0 +1,44 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" + +/** + This class is used for creating animated images via `animatedImageWithFrames` in `SDImageCoderHelper`. + @note If you need to specify animated images loop count, use `sd_imageLoopCount` property in `UIImage+Metadata.h`. + */ +@interface SDImageFrame : NSObject + +/** + The image of current frame. You should not set an animated image. + */ +@property (nonatomic, strong, readonly, nonnull) UIImage *image; +/** + The duration of current frame to be displayed. The number is seconds but not milliseconds. You should not set this to zero. + */ +@property (nonatomic, readonly, assign) NSTimeInterval duration; + +/// Create a frame instance with specify image and duration +/// @param image current frame's image +/// @param duration current frame's duration +- (nonnull instancetype)initWithImage:(nonnull UIImage *)image duration:(NSTimeInterval)duration; + +/** + Create a frame instance with specify image and duration + + @param image current frame's image + @param duration current frame's duration + @return frame instance + */ ++ (nonnull instancetype)frameWithImage:(nonnull UIImage *)image duration:(NSTimeInterval)duration; + +- (nonnull instancetype)init NS_UNAVAILABLE; ++ (nonnull instancetype)new NS_UNAVAILABLE; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDImageFrame.m b/Pods/SDWebImage/SDWebImage/Core/SDImageFrame.m new file mode 100644 index 0000000..bd207ae --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDImageFrame.m @@ -0,0 +1,34 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDImageFrame.h" + +@interface SDImageFrame () + +@property (nonatomic, strong, readwrite, nonnull) UIImage *image; +@property (nonatomic, readwrite, assign) NSTimeInterval duration; + +@end + +@implementation SDImageFrame + +- (instancetype)initWithImage:(UIImage *)image duration:(NSTimeInterval)duration { + self = [super init]; + if (self) { + _image = image; + _duration = duration; + } + return self; +} + ++ (instancetype)frameWithImage:(UIImage *)image duration:(NSTimeInterval)duration { + SDImageFrame *frame = [[SDImageFrame alloc] initWithImage:image duration:duration]; + return frame; +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDImageGIFCoder.h b/Pods/SDWebImage/SDWebImage/Core/SDImageGIFCoder.h new file mode 100644 index 0000000..5ef67ac --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDImageGIFCoder.h @@ -0,0 +1,22 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDImageIOAnimatedCoder.h" + +/** + Built in coder using ImageIO that supports animated GIF encoding/decoding + @note `SDImageIOCoder` supports GIF but only as static (will use the 1st frame). + @note Use `SDImageGIFCoder` for fully animated GIFs. For `UIImageView`, it will produce animated `UIImage`(`NSImage` on macOS) for rendering. For `SDAnimatedImageView`, it will use `SDAnimatedImage` for rendering. + @note The recommended approach for animated GIFs is using `SDAnimatedImage` with `SDAnimatedImageView`. It's more performant than `UIImageView` for GIF displaying(especially on memory usage) + */ +@interface SDImageGIFCoder : SDImageIOAnimatedCoder + +@property (nonatomic, class, readonly, nonnull) SDImageGIFCoder *sharedCoder; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDImageGIFCoder.m b/Pods/SDWebImage/SDWebImage/Core/SDImageGIFCoder.m new file mode 100644 index 0000000..a1838b1 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDImageGIFCoder.m @@ -0,0 +1,58 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDImageGIFCoder.h" +#import "SDImageIOAnimatedCoderInternal.h" +#if SD_MAC +#import +#else +#import +#endif + +@implementation SDImageGIFCoder + ++ (instancetype)sharedCoder { + static SDImageGIFCoder *coder; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + coder = [[SDImageGIFCoder alloc] init]; + }); + return coder; +} + +#pragma mark - Subclass Override + ++ (SDImageFormat)imageFormat { + return SDImageFormatGIF; +} + ++ (NSString *)imageUTType { + return (__bridge NSString *)kSDUTTypeGIF; +} + ++ (NSString *)dictionaryProperty { + return (__bridge NSString *)kCGImagePropertyGIFDictionary; +} + ++ (NSString *)unclampedDelayTimeProperty { + return (__bridge NSString *)kCGImagePropertyGIFUnclampedDelayTime; +} + ++ (NSString *)delayTimeProperty { + return (__bridge NSString *)kCGImagePropertyGIFDelayTime; +} + ++ (NSString *)loopCountProperty { + return (__bridge NSString *)kCGImagePropertyGIFLoopCount; +} + ++ (NSUInteger)defaultLoopCount { + return 1; +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDImageGraphics.h b/Pods/SDWebImage/SDWebImage/Core/SDImageGraphics.h new file mode 100644 index 0000000..131d685 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDImageGraphics.h @@ -0,0 +1,28 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" +#import + +/** + These following graphics context method are provided to easily write cross-platform(AppKit/UIKit) code. + For UIKit, these methods just call the same method in `UIGraphics.h`. See the documentation for usage. + For AppKit, these methods use `NSGraphicsContext` to create image context and match the behavior like UIKit. + @note If you don't care bitmap format (ARGB8888) and just draw image, use `SDGraphicsImageRenderer` instead. It's more performant on RAM usage.` + */ + +/// Returns the current graphics context. +FOUNDATION_EXPORT CGContextRef __nullable SDGraphicsGetCurrentContext(void) CF_RETURNS_NOT_RETAINED; +/// Creates a bitmap-based graphics context and makes it the current context. +FOUNDATION_EXPORT void SDGraphicsBeginImageContext(CGSize size); +/// Creates a bitmap-based graphics context with the specified options. +FOUNDATION_EXPORT void SDGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale); +/// Removes the current bitmap-based graphics context from the top of the stack. +FOUNDATION_EXPORT void SDGraphicsEndImageContext(void); +/// Returns an image based on the contents of the current bitmap-based graphics context. +FOUNDATION_EXPORT UIImage * __nullable SDGraphicsGetImageFromCurrentImageContext(void); diff --git a/Pods/SDWebImage/SDWebImage/Core/SDImageGraphics.m b/Pods/SDWebImage/SDWebImage/Core/SDImageGraphics.m new file mode 100644 index 0000000..2e877f3 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDImageGraphics.m @@ -0,0 +1,126 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDImageGraphics.h" +#import "NSImage+Compatibility.h" +#import "SDImageCoderHelper.h" +#import "objc/runtime.h" + +#if SD_MAC +static void *kNSGraphicsContextScaleFactorKey; + +static CGContextRef SDCGContextCreateBitmapContext(CGSize size, BOOL opaque, CGFloat scale) { + if (scale == 0) { + // Match `UIGraphicsBeginImageContextWithOptions`, reset to the scale factor of the device’s main screen if scale is 0. + NSScreen *mainScreen = nil; + if (@available(macOS 10.12, *)) { + mainScreen = [NSScreen mainScreen]; + } else { + mainScreen = [NSScreen screens].firstObject; + } + scale = mainScreen.backingScaleFactor ?: 1.0f; + } + size_t width = ceil(size.width * scale); + size_t height = ceil(size.height * scale); + if (width < 1 || height < 1) return NULL; + + CGColorSpaceRef space = [SDImageCoderHelper colorSpaceGetDeviceRGB]; + // kCGImageAlphaNone is not supported in CGBitmapContextCreate. + // Check #3330 for more detail about why this bitmap is choosen. + // From v5.17.0, use runtime detection of bitmap info instead of hardcode. + // However, macOS's runtime detection will also call this function, cause recursive, so still hardcode here + CGBitmapInfo bitmapInfo; + if (!opaque) { + // [NSImage imageWithSize:flipped:drawingHandler:] returns float(16-bits) RGBA8888 on alpha image, which we don't need + bitmapInfo = kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedLast; + } else { + bitmapInfo = kCGBitmapByteOrderDefault | kCGImageAlphaNoneSkipLast; + } + CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8, 0, space, bitmapInfo); + if (!context) { + return NULL; + } + CGContextScaleCTM(context, scale, scale); + + return context; +} +#endif + +CGContextRef SDGraphicsGetCurrentContext(void) { +#if SD_UIKIT || SD_WATCH + return UIGraphicsGetCurrentContext(); +#else + return NSGraphicsContext.currentContext.CGContext; +#endif +} + +void SDGraphicsBeginImageContext(CGSize size) { +#if SD_UIKIT || SD_WATCH + UIGraphicsBeginImageContext(size); +#else + SDGraphicsBeginImageContextWithOptions(size, NO, 1.0); +#endif +} + +void SDGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale) { +#if SD_UIKIT || SD_WATCH + UIGraphicsBeginImageContextWithOptions(size, opaque, scale); +#else + CGContextRef context = SDCGContextCreateBitmapContext(size, opaque, scale); + if (!context) { + return; + } + NSGraphicsContext *graphicsContext = [NSGraphicsContext graphicsContextWithCGContext:context flipped:NO]; + objc_setAssociatedObject(graphicsContext, &kNSGraphicsContextScaleFactorKey, @(scale), OBJC_ASSOCIATION_RETAIN); + CGContextRelease(context); + [NSGraphicsContext saveGraphicsState]; + NSGraphicsContext.currentContext = graphicsContext; +#endif +} + +void SDGraphicsEndImageContext(void) { +#if SD_UIKIT || SD_WATCH + UIGraphicsEndImageContext(); +#else + [NSGraphicsContext restoreGraphicsState]; +#endif +} + +UIImage * SDGraphicsGetImageFromCurrentImageContext(void) { +#if SD_UIKIT || SD_WATCH + return UIGraphicsGetImageFromCurrentImageContext(); +#else + NSGraphicsContext *context = NSGraphicsContext.currentContext; + CGContextRef contextRef = context.CGContext; + if (!contextRef) { + return nil; + } + CGImageRef imageRef = CGBitmapContextCreateImage(contextRef); + if (!imageRef) { + return nil; + } + CGFloat scale = 0; + NSNumber *scaleFactor = objc_getAssociatedObject(context, &kNSGraphicsContextScaleFactorKey); + if ([scaleFactor isKindOfClass:[NSNumber class]]) { + scale = scaleFactor.doubleValue; + } + if (!scale) { + // reset to the scale factor of the device’s main screen if scale is 0. + NSScreen *mainScreen = nil; + if (@available(macOS 10.12, *)) { + mainScreen = [NSScreen mainScreen]; + } else { + mainScreen = [NSScreen screens].firstObject; + } + scale = mainScreen.backingScaleFactor ?: 1.0f; + } + NSImage *image = [[NSImage alloc] initWithCGImage:imageRef scale:scale orientation:kCGImagePropertyOrientationUp]; + CGImageRelease(imageRef); + return image; +#endif +} diff --git a/Pods/SDWebImage/SDWebImage/Core/SDImageHEICCoder.h b/Pods/SDWebImage/SDWebImage/Core/SDImageHEICCoder.h new file mode 100644 index 0000000..f7dd661 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDImageHEICCoder.h @@ -0,0 +1,25 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import +#import "SDImageIOAnimatedCoder.h" + +/** + This coder is used for HEIC (HEIF with HEVC container codec) image format. + Image/IO provide the static HEIC (.heic) support in iOS 11/macOS 10.13/tvOS 11/watchOS 4+. + Image/IO provide the animated HEIC (.heics) support in iOS 13/macOS 10.15/tvOS 13/watchOS 6+. + See https://nokiatech.github.io/heif/technical.html for the standard. + @note This coder is not in the default coder list for now, since HEIC animated image is really rare, and Apple's implementation still contains performance issues. You can enable if you need this. + @note If you need to support lower firmware version for HEIF, you can have a try at https://github.com/SDWebImage/SDWebImageHEIFCoder + */ +API_AVAILABLE(ios(13.0), tvos(13.0), macos(10.15), watchos(6.0)) +@interface SDImageHEICCoder : SDImageIOAnimatedCoder + +@property (nonatomic, class, readonly, nonnull) SDImageHEICCoder *sharedCoder; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDImageHEICCoder.m b/Pods/SDWebImage/SDWebImage/Core/SDImageHEICCoder.m new file mode 100644 index 0000000..5e03a8d --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDImageHEICCoder.m @@ -0,0 +1,109 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import "SDImageHEICCoder.h" +#import "SDImageIOAnimatedCoderInternal.h" + +// These constants are available from iOS 13+ and Xcode 11. This raw value is used for toolchain and firmware compatibility +static NSString * kSDCGImagePropertyHEICSDictionary = @"{HEICS}"; +static NSString * kSDCGImagePropertyHEICSLoopCount = @"LoopCount"; +static NSString * kSDCGImagePropertyHEICSDelayTime = @"DelayTime"; +static NSString * kSDCGImagePropertyHEICSUnclampedDelayTime = @"UnclampedDelayTime"; + +@implementation SDImageHEICCoder + ++ (void)initialize { + if (@available(iOS 13, tvOS 13, macOS 10.15, watchOS 6, *)) { + // Use SDK instead of raw value + kSDCGImagePropertyHEICSDictionary = (__bridge NSString *)kCGImagePropertyHEICSDictionary; + kSDCGImagePropertyHEICSLoopCount = (__bridge NSString *)kCGImagePropertyHEICSLoopCount; + kSDCGImagePropertyHEICSDelayTime = (__bridge NSString *)kCGImagePropertyHEICSDelayTime; + kSDCGImagePropertyHEICSUnclampedDelayTime = (__bridge NSString *)kCGImagePropertyHEICSUnclampedDelayTime; + } +} + ++ (instancetype)sharedCoder { + static SDImageHEICCoder *coder; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + coder = [[SDImageHEICCoder alloc] init]; + }); + return coder; +} + +#pragma mark - SDImageCoder + +- (BOOL)canDecodeFromData:(nullable NSData *)data { + switch ([NSData sd_imageFormatForImageData:data]) { + case SDImageFormatHEIC: + // Check HEIC decoding compatibility + return [self.class canDecodeFromFormat:SDImageFormatHEIC]; + case SDImageFormatHEIF: + // Check HEIF decoding compatibility + return [self.class canDecodeFromFormat:SDImageFormatHEIF]; + default: + return NO; + } +} + +- (BOOL)canIncrementalDecodeFromData:(NSData *)data { + return [self canDecodeFromData:data]; +} + +- (BOOL)canEncodeToFormat:(SDImageFormat)format { + switch (format) { + case SDImageFormatHEIC: + // Check HEIC encoding compatibility + return [self.class canEncodeToFormat:SDImageFormatHEIC]; + case SDImageFormatHEIF: + // Check HEIF encoding compatibility + return [self.class canEncodeToFormat:SDImageFormatHEIF]; + default: + return NO; + } +} + +#pragma mark - Subclass Override + ++ (SDImageFormat)imageFormat { + return SDImageFormatHEIC; +} + ++ (NSString *)imageUTType { + // See: https://nokiatech.github.io/heif/technical.html + // Actually HEIC has another concept called `non-timed Image Sequence`, which can be encoded using `public.heic` + return (__bridge NSString *)kSDUTTypeHEIC; +} + ++ (NSString *)animatedImageUTType { + // See: https://nokiatech.github.io/heif/technical.html + // We use `timed Image Sequence`, means, `public.heics` for animated image encoding + return (__bridge NSString *)kSDUTTypeHEICS; +} + ++ (NSString *)dictionaryProperty { + return kSDCGImagePropertyHEICSDictionary; +} + ++ (NSString *)unclampedDelayTimeProperty { + return kSDCGImagePropertyHEICSUnclampedDelayTime; +} + ++ (NSString *)delayTimeProperty { + return kSDCGImagePropertyHEICSDelayTime; +} + ++ (NSString *)loopCountProperty { + return kSDCGImagePropertyHEICSLoopCount; +} + ++ (NSUInteger)defaultLoopCount { + return 0; +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDImageIOAnimatedCoder.h b/Pods/SDWebImage/SDWebImage/Core/SDImageIOAnimatedCoder.h new file mode 100644 index 0000000..02fb6d9 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDImageIOAnimatedCoder.h @@ -0,0 +1,65 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import +#import "SDImageCoder.h" + +/** + This is the abstract class for all animated coder, which use the Image/IO API. You can not use this directly as real coders. A exception will be raised if you use this class. + All of the properties need the subclass to implement and works as expected. + For Image/IO, See Apple's documentation: https://developer.apple.com/documentation/imageio + */ +@interface SDImageIOAnimatedCoder : NSObject + +#pragma mark - Subclass Override +/** + The supported animated image format. Such as `SDImageFormatGIF`. + @note Subclass override. + */ +@property (class, readonly) SDImageFormat imageFormat; +/** + The supported image format UTI Type. Such as `kSDUTTypeGIF`. + This can be used for cases when we can not detect `SDImageFormat. Such as progressive decoding's hint format `kCGImageSourceTypeIdentifierHint`. + @note Subclass override. + */ +@property (class, readonly, nonnull) NSString *imageUTType; +/** + Some image codec use different UTI Type between animated image and static image. + For this case, override this method and return the UTI for animated image encoding. + @note Defaults to use the value of `imageUTType`, so it's @optional actually. + @note Subclass override. + */ +@property (class, readonly, nonnull) NSString *animatedImageUTType; +/** + The image container property key used in Image/IO API. Such as `kCGImagePropertyGIFDictionary`. + @note Subclass override. + */ +@property (class, readonly, nonnull) NSString *dictionaryProperty; +/** + The image unclamped delay time property key used in Image/IO API. Such as `kCGImagePropertyGIFUnclampedDelayTime` + @note Subclass override. + */ +@property (class, readonly, nonnull) NSString *unclampedDelayTimeProperty; +/** + The image delay time property key used in Image/IO API. Such as `kCGImagePropertyGIFDelayTime`. + @note Subclass override. + */ +@property (class, readonly, nonnull) NSString *delayTimeProperty; +/** + The image loop count property key used in Image/IO API. Such as `kCGImagePropertyGIFLoopCount`. + @note Subclass override. + */ +@property (class, readonly, nonnull) NSString *loopCountProperty; +/** + The default loop count when there are no any loop count information inside image container metadata. + For example, for GIF format, the standard use 1 (play once). For APNG format, the standard use 0 (infinity loop). + @note Subclass override. + */ +@property (class, readonly) NSUInteger defaultLoopCount; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDImageIOAnimatedCoder.m b/Pods/SDWebImage/SDWebImage/Core/SDImageIOAnimatedCoder.m new file mode 100644 index 0000000..304530a --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDImageIOAnimatedCoder.m @@ -0,0 +1,1158 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import "SDImageIOAnimatedCoder.h" +#import "SDImageIOAnimatedCoderInternal.h" +#import "NSImage+Compatibility.h" +#import "UIImage+Metadata.h" +#import "NSData+ImageContentType.h" +#import "SDImageCoderHelper.h" +#import "SDAnimatedImageRep.h" +#import "UIImage+ForceDecode.h" +#import "SDInternalMacros.h" + +#import +#import + +#if SD_CHECK_CGIMAGE_RETAIN_SOURCE +#import + +// SPI to check thread safe during Example and Test +static CGImageSourceRef (*SDCGImageGetImageSource)(CGImageRef); +#endif + +// Specify File Size for lossy format encoding, like JPEG +static NSString * kSDCGImageDestinationRequestedFileSize = @"kCGImageDestinationRequestedFileSize"; +// Support Xcode 15 SDK, use raw value instead of symbol +static NSString * kSDCGImageDestinationEncodeRequest = @"kCGImageDestinationEncodeRequest"; +static NSString * kSDCGImageDestinationEncodeToSDR = @"kCGImageDestinationEncodeToSDR"; +static NSString * kSDCGImageDestinationEncodeToISOHDR = @"kCGImageDestinationEncodeToISOHDR"; +static NSString * kSDCGImageDestinationEncodeToISOGainmap = @"kCGImageDestinationEncodeToISOGainmap"; + + +// This strip the un-wanted CGImageProperty, like the internal CGImageSourceRef in iOS 15+ +// However, CGImageCreateCopy still keep those CGImageProperty, not suit for our use case +static CGImageRef __nullable SDCGImageCreateMutableCopy(CGImageRef cg_nullable image, CGBitmapInfo bitmapInfo) { + if (!image) return nil; + size_t width = CGImageGetWidth(image); + size_t height = CGImageGetHeight(image); + size_t bitsPerComponent = CGImageGetBitsPerComponent(image); + size_t bitsPerPixel = CGImageGetBitsPerPixel(image); + size_t bytesPerRow = CGImageGetBytesPerRow(image); + CGColorSpaceRef space = CGImageGetColorSpace(image); + CGDataProviderRef provider = CGImageGetDataProvider(image); + const CGFloat *decode = CGImageGetDecode(image); + bool shouldInterpolate = CGImageGetShouldInterpolate(image); + CGColorRenderingIntent intent = CGImageGetRenderingIntent(image); + CGImageRef newImage = CGImageCreate(width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, space, bitmapInfo, provider, decode, shouldInterpolate, intent); + return newImage; +} + +static inline BOOL SDCGImageIs8Bit(CGImageRef cg_nullable image) { + return CGImageGetBitsPerComponent(image) == 8; +} + +static inline CGImageRef __nullable SDCGImageCreateCopy(CGImageRef cg_nullable image) { + if (!image) return nil; + return SDCGImageCreateMutableCopy(image, CGImageGetBitmapInfo(image)); +} + +static BOOL SDLoadOnePixelBitmapBuffer(CGImageRef imageRef, uint8_t *r, uint8_t *g, uint8_t *b, uint8_t *a) { + CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef); + CGImageAlphaInfo alphaInfo = bitmapInfo & kCGBitmapAlphaInfoMask; + CGBitmapInfo byteOrderInfo = bitmapInfo & kCGBitmapByteOrderMask; + + // Get pixels + CGDataProviderRef provider = CGImageGetDataProvider(imageRef); + if (!provider) { + return NO; + } + CFDataRef data = CGDataProviderCopyData(provider); + if (!data) { + return NO; + } + + CFRange range = CFRangeMake(0, 4); // one pixel + if (CFDataGetLength(data) < range.location + range.length) { + CFRelease(data); + return NO; + } + uint8_t pixel[4] = {0}; + CFDataGetBytes(data, range, pixel); + CFRelease(data); + + BOOL byteOrderNormal = NO; + switch (byteOrderInfo) { + case kCGBitmapByteOrderDefault: { + byteOrderNormal = YES; + } break; + case kCGBitmapByteOrder16Little: + case kCGBitmapByteOrder32Little: { + } break; + case kCGBitmapByteOrder16Big: + case kCGBitmapByteOrder32Big: { + byteOrderNormal = YES; + } break; + default: break; + } + switch (alphaInfo) { + case kCGImageAlphaPremultipliedFirst: + case kCGImageAlphaFirst: { + if (byteOrderNormal) { + // ARGB8888 + *a = pixel[0]; + *r = pixel[1]; + *g = pixel[2]; + *b = pixel[3]; + } else { + // BGRA8888 + *b = pixel[0]; + *g = pixel[1]; + *r = pixel[2]; + *a = pixel[3]; + } + } + break; + case kCGImageAlphaPremultipliedLast: + case kCGImageAlphaLast: { + if (byteOrderNormal) { + // RGBA8888 + *r = pixel[0]; + *g = pixel[1]; + *b = pixel[2]; + *a = pixel[3]; + } else { + // ABGR8888 + *a = pixel[0]; + *b = pixel[1]; + *g = pixel[2]; + *r = pixel[3]; + } + } + break; + case kCGImageAlphaNone: { + if (byteOrderNormal) { + // RGB + *r = pixel[0]; + *g = pixel[1]; + *b = pixel[2]; + } else { + // BGR + *b = pixel[0]; + *g = pixel[1]; + *r = pixel[2]; + } + } + break; + case kCGImageAlphaNoneSkipLast: { + if (byteOrderNormal) { + // RGBX + *r = pixel[0]; + *g = pixel[1]; + *b = pixel[2]; + } else { + // XBGR + *b = pixel[1]; + *g = pixel[2]; + *r = pixel[3]; + } + } + break; + case kCGImageAlphaNoneSkipFirst: { + if (byteOrderNormal) { + // XRGB + *r = pixel[1]; + *g = pixel[2]; + *b = pixel[3]; + } else { + // BGRX + *b = pixel[0]; + *g = pixel[1]; + *r = pixel[2]; + } + } + break; + case kCGImageAlphaOnly: { + // A + *a = pixel[0]; + } + break; + default: + break; + } + + return YES; +} + +static CGImageRef SDImageIOPNGPluginBuggyCreateWorkaround(CGImageRef cgImage) CF_RETURNS_RETAINED { + CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(cgImage); + CGImageAlphaInfo alphaInfo = (bitmapInfo & kCGBitmapAlphaInfoMask); + CGImageAlphaInfo newAlphaInfo = alphaInfo; + if (alphaInfo == kCGImageAlphaLast) { + newAlphaInfo = kCGImageAlphaPremultipliedLast; + } else if (alphaInfo == kCGImageAlphaFirst) { + newAlphaInfo = kCGImageAlphaPremultipliedFirst; + } + if (newAlphaInfo != alphaInfo) { + CGBitmapInfo byteOrderInfo = bitmapInfo & kCGBitmapByteOrderMask; + CGBitmapInfo newBitmapInfo = newAlphaInfo | byteOrderInfo; + if (SD_OPTIONS_CONTAINS(bitmapInfo, kCGBitmapFloatComponents)) { + // Keep float components + newBitmapInfo |= kCGBitmapFloatComponents; + } + // Create new CGImage with corrected alpha info... + CGImageRef newCGImage = SDCGImageCreateMutableCopy(cgImage, newBitmapInfo); + return newCGImage; + } else { + CGImageRetain(cgImage); + return cgImage; + } +} + +static BOOL SDImageIOPNGPluginBuggyNeedWorkaround(void) { + // See: #3605 FB13322459 + // ImageIO on iOS 17 (17.0~17.2), there is one serious problem on ImageIO PNG plugin. The decode result for indexed color PNG use the wrong CGImageAlphaInfo + // The returned CGImageAlphaInfo is alpha last, but the actual bitmap data is premultiplied alpha last, which cause many runtime render bug. + // The bug only exists on 8-bits indexed color, not about 16-bits + // So, we do a hack workaround: + // 1. Decode a indexed color PNG in runtime + // 2. If the bitmap is premultiplied alpha, then assume it's buggy + // 3. If buggy, then all premultiplied `CGImageAlphaInfo` will assume to be non-premultiplied + // :) + + if (@available(iOS 17, tvOS 17, macOS 14, watchOS 11, *)) { + // Continue + } else { + return NO; + } + static BOOL isBuggy = NO; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + NSString *base64String = @"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUyMjKlMgnVAAAAAXRSTlMyiDGJ5gAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII="; + NSData *onePixelIndexedPNGData = [[NSData alloc] initWithBase64EncodedString:base64String options:NSDataBase64DecodingIgnoreUnknownCharacters]; + CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)onePixelIndexedPNGData, nil); + NSCParameterAssert(source); + CGImageRef cgImage = CGImageSourceCreateImageAtIndex(source, 0, nil); + NSCParameterAssert(cgImage); + uint8_t r, g, b, a; + r = g = b = a = 0; + BOOL success = SDLoadOnePixelBitmapBuffer(cgImage, &r, &g, &b, &a); + if (!success) { + isBuggy = NO; // Impossible... + } else { + if (r == 50 && g == 50 && b == 50 && a == 50) { + // Correct value + isBuggy = NO; + } else { + SD_LOG("%@", @"Detected the current OS's ImageIO PNG Decoder is buggy on indexed color PNG. Perform workaround solution..."); + isBuggy = YES; + } + } + CFRelease(source); + CGImageRelease(cgImage); + }); + + return isBuggy; +} + +@interface SDImageIOCoderFrame : NSObject + +@property (nonatomic, assign) NSUInteger index; // Frame index (zero based) +@property (nonatomic, assign) NSTimeInterval duration; // Frame duration in seconds + +@end + +@implementation SDImageIOCoderFrame +@end + +@implementation SDImageIOAnimatedCoder { + size_t _width, _height; + CGImageSourceRef _imageSource; + BOOL _incremental; + SD_LOCK_DECLARE(_lock); // Lock only apply for incremental animation decoding + NSData *_imageData; + CGFloat _scale; + NSUInteger _loopCount; + NSUInteger _frameCount; + NSArray *_frames; + BOOL _finished; + BOOL _preserveAspectRatio; + CGSize _thumbnailSize; + NSUInteger _limitBytes; + BOOL _lazyDecode; + BOOL _decodeToHDR; +} + +#if SD_IMAGEIO_HDR_ENCODING ++ (void)initialize { + if (@available(macOS 15, iOS 18, tvOS 18, watchOS 11, *)) { + // Use SDK instead of raw value + kSDCGImageDestinationEncodeRequest = (__bridge NSString *)kCGImageDestinationEncodeRequest; + kSDCGImageDestinationEncodeToSDR = (__bridge NSString *)kCGImageDestinationEncodeToSDR; + kSDCGImageDestinationEncodeToISOHDR = (__bridge NSString *)kCGImageDestinationEncodeToISOHDR; + kSDCGImageDestinationEncodeToISOGainmap = (__bridge NSString *)kCGImageDestinationEncodeToISOGainmap; + } +} +#endif + +- (void)dealloc +{ + if (_imageSource) { + CFRelease(_imageSource); + _imageSource = NULL; + } +#if SD_UIKIT + [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; +#endif +} + +- (void)didReceiveMemoryWarning:(NSNotification *)notification +{ + if (_imageSource) { + for (size_t i = 0; i < _frameCount; i++) { + CGImageSourceRemoveCacheAtIndex(_imageSource, i); + } + } +} + +#pragma mark - Subclass Override + ++ (SDImageFormat)imageFormat { + @throw [NSException exceptionWithName:NSInternalInconsistencyException + reason:[NSString stringWithFormat:@"For `SDImageIOAnimatedCoder` subclass, you must override %@ method", NSStringFromSelector(_cmd)] + userInfo:nil]; +} + ++ (NSString *)imageUTType { + @throw [NSException exceptionWithName:NSInternalInconsistencyException + reason:[NSString stringWithFormat:@"For `SDImageIOAnimatedCoder` subclass, you must override %@ method", NSStringFromSelector(_cmd)] + userInfo:nil]; +} + ++ (NSString *)animatedImageUTType { + return [self imageUTType]; +} + ++ (NSString *)dictionaryProperty { + @throw [NSException exceptionWithName:NSInternalInconsistencyException + reason:[NSString stringWithFormat:@"For `SDImageIOAnimatedCoder` subclass, you must override %@ method", NSStringFromSelector(_cmd)] + userInfo:nil]; +} + ++ (NSString *)unclampedDelayTimeProperty { + @throw [NSException exceptionWithName:NSInternalInconsistencyException + reason:[NSString stringWithFormat:@"For `SDImageIOAnimatedCoder` subclass, you must override %@ method", NSStringFromSelector(_cmd)] + userInfo:nil]; +} + ++ (NSString *)delayTimeProperty { + @throw [NSException exceptionWithName:NSInternalInconsistencyException + reason:[NSString stringWithFormat:@"For `SDImageIOAnimatedCoder` subclass, you must override %@ method", NSStringFromSelector(_cmd)] + userInfo:nil]; +} + ++ (NSString *)loopCountProperty { + @throw [NSException exceptionWithName:NSInternalInconsistencyException + reason:[NSString stringWithFormat:@"For `SDImageIOAnimatedCoder` subclass, you must override %@ method", NSStringFromSelector(_cmd)] + userInfo:nil]; +} + ++ (NSUInteger)defaultLoopCount { + @throw [NSException exceptionWithName:NSInternalInconsistencyException + reason:[NSString stringWithFormat:@"For `SDImageIOAnimatedCoder` subclass, you must override %@ method", NSStringFromSelector(_cmd)] + userInfo:nil]; +} + +#pragma mark - Utils + ++ (BOOL)canDecodeFromFormat:(SDImageFormat)format { + static dispatch_once_t onceToken; + static NSSet *imageUTTypeSet; + dispatch_once(&onceToken, ^{ + NSArray *imageUTTypes = (__bridge_transfer NSArray *)CGImageSourceCopyTypeIdentifiers(); + imageUTTypeSet = [NSSet setWithArray:imageUTTypes]; + }); + CFStringRef imageUTType = [NSData sd_UTTypeFromImageFormat:format]; + if ([imageUTTypeSet containsObject:(__bridge NSString *)(imageUTType)]) { + // Can decode from target format + return YES; + } + return NO; +} + ++ (BOOL)canEncodeToFormat:(SDImageFormat)format { + static dispatch_once_t onceToken; + static NSSet *imageUTTypeSet; + dispatch_once(&onceToken, ^{ + NSArray *imageUTTypes = (__bridge_transfer NSArray *)CGImageDestinationCopyTypeIdentifiers(); + imageUTTypeSet = [NSSet setWithArray:imageUTTypes]; + }); + CFStringRef imageUTType = [NSData sd_UTTypeFromImageFormat:format]; + if ([imageUTTypeSet containsObject:(__bridge NSString *)(imageUTType)]) { + // Can encode to target format + return YES; + } + return NO; +} + ++ (NSUInteger)imageLoopCountWithSource:(CGImageSourceRef)source { + NSUInteger loopCount = self.defaultLoopCount; + NSDictionary *imageProperties = (__bridge_transfer NSDictionary *)CGImageSourceCopyProperties(source, NULL); + NSDictionary *containerProperties = imageProperties[self.dictionaryProperty]; + if (containerProperties) { + NSNumber *containerLoopCount = containerProperties[self.loopCountProperty]; + if (containerLoopCount != nil) { + loopCount = containerLoopCount.unsignedIntegerValue; + } + } + return loopCount; +} + ++ (NSTimeInterval)frameDurationAtIndex:(NSUInteger)index source:(CGImageSourceRef)source { + NSTimeInterval frameDuration = 0.1; + CFDictionaryRef cfFrameProperties = CGImageSourceCopyPropertiesAtIndex(source, index, NULL); + if (!cfFrameProperties) { + return frameDuration; + } + NSDictionary *frameProperties = (__bridge NSDictionary *)cfFrameProperties; + NSDictionary *containerProperties = frameProperties[self.dictionaryProperty]; + + NSNumber *delayTimeUnclampedProp = containerProperties[self.unclampedDelayTimeProperty]; + if (delayTimeUnclampedProp != nil) { + frameDuration = [delayTimeUnclampedProp doubleValue]; + } else { + NSNumber *delayTimeProp = containerProperties[self.delayTimeProperty]; + if (delayTimeProp != nil) { + frameDuration = [delayTimeProp doubleValue]; + } + } + + // Many annoying ads specify a 0 duration to make an image flash as quickly as possible. + // We follow Firefox's behavior and use a duration of 100 ms for any frames that specify + // a duration of <= 10 ms. See and + // for more information. + + if (frameDuration < 0.011) { + frameDuration = 0.1; + } + + CFRelease(cfFrameProperties); + return frameDuration; +} + ++ (UIImage *)createFrameAtIndex:(NSUInteger)index source:(CGImageSourceRef)source scale:(CGFloat)scale preserveAspectRatio:(BOOL)preserveAspectRatio thumbnailSize:(CGSize)thumbnailSize lazyDecode:(BOOL)lazyDecode animatedImage:(BOOL)animatedImage decodeToHDR:(BOOL)decodeToHDR { + // `animatedImage` means called from `SDAnimatedImageProvider.animatedImageFrameAtIndex` + NSDictionary *options; + if (animatedImage) { + if (!lazyDecode) { + options = @{ + // image decoding and caching should happen at image creation time. + (__bridge NSString *)kCGImageSourceShouldCacheImmediately : @(YES), + }; + } else { + options = @{ + // image decoding will happen at rendering time + (__bridge NSString *)kCGImageSourceShouldCacheImmediately : @(NO), + }; + } + } + // Parse the image properties + NSDictionary *properties = (__bridge_transfer NSDictionary *)CGImageSourceCopyPropertiesAtIndex(source, index, NULL); + CGFloat pixelWidth = [properties[(__bridge NSString *)kCGImagePropertyPixelWidth] doubleValue]; + CGFloat pixelHeight = [properties[(__bridge NSString *)kCGImagePropertyPixelHeight] doubleValue]; + CGImagePropertyOrientation exifOrientation = kCGImagePropertyOrientationUp; + NSNumber *exifOrientationValue = properties[(__bridge NSString *)kCGImagePropertyOrientation]; + if (exifOrientationValue != NULL) { + exifOrientation = [exifOrientationValue unsignedIntValue]; + } + + NSMutableDictionary *decodingOptions; + if (options) { + decodingOptions = [NSMutableDictionary dictionaryWithDictionary:options]; + } else { + decodingOptions = [NSMutableDictionary dictionary]; + } + if (@available(macOS 14, iOS 17, tvOS 17, watchOS 10, *)) { + if (decodeToHDR) { + decodingOptions[(__bridge NSString *)kCGImageSourceDecodeRequest] = (__bridge NSString *)kCGImageSourceDecodeToHDR; + } else { + decodingOptions[(__bridge NSString *)kCGImageSourceDecodeRequest] = (__bridge NSString *)kCGImageSourceDecodeToSDR; + } + } + + CGImageRef imageRef; + BOOL createFullImage = thumbnailSize.width == 0 || thumbnailSize.height == 0 || pixelWidth == 0 || pixelHeight == 0 || (pixelWidth <= thumbnailSize.width && pixelHeight <= thumbnailSize.height); + if (createFullImage) { + imageRef = CGImageSourceCreateImageAtIndex(source, index, (__bridge CFDictionaryRef)[decodingOptions copy]); + } else { + decodingOptions[(__bridge NSString *)kCGImageSourceCreateThumbnailWithTransform] = @(preserveAspectRatio); + CGFloat maxPixelSize; + if (preserveAspectRatio) { + CGFloat pixelRatio = pixelWidth / pixelHeight; + CGFloat thumbnailRatio = thumbnailSize.width / thumbnailSize.height; + if (pixelRatio > thumbnailRatio) { + maxPixelSize = MAX(thumbnailSize.width, thumbnailSize.width / pixelRatio); + } else { + maxPixelSize = MAX(thumbnailSize.height, thumbnailSize.height * pixelRatio); + } + } else { + maxPixelSize = MAX(thumbnailSize.width, thumbnailSize.height); + } + decodingOptions[(__bridge NSString *)kCGImageSourceThumbnailMaxPixelSize] = @(maxPixelSize); + decodingOptions[(__bridge NSString *)kCGImageSourceCreateThumbnailFromImageAlways] = @(YES); + imageRef = CGImageSourceCreateThumbnailAtIndex(source, index, (__bridge CFDictionaryRef)[decodingOptions copy]); + } + if (!imageRef) { + return nil; + } + BOOL isHDRImage = [SDImageCoderHelper CGImageIsHDR:imageRef]; + + // Thumbnail image post-process + if (!createFullImage) { + if (preserveAspectRatio) { + // kCGImageSourceCreateThumbnailWithTransform will apply EXIF transform as well, we should not apply twice + exifOrientation = kCGImagePropertyOrientationUp; + } else { + // `CGImageSourceCreateThumbnailAtIndex` take only pixel dimension, if not `preserveAspectRatio`, we should manual scale to the target size + CGImageRef scaledImageRef = [SDImageCoderHelper CGImageCreateScaled:imageRef size:thumbnailSize]; + if (scaledImageRef) { + CGImageRelease(imageRef); + imageRef = scaledImageRef; + } + } + } + + // Check whether output CGImage is decoded + BOOL isLazy = [SDImageCoderHelper CGImageIsLazy:imageRef]; + if (!lazyDecode && !isHDRImage) { + if (isLazy) { + // Use CoreGraphics to trigger immediately decode to drop lazy CGImage + CGImageRef decodedImageRef = [SDImageCoderHelper CGImageCreateDecoded:imageRef]; + if (decodedImageRef) { + CGImageRelease(imageRef); + imageRef = decodedImageRef; + isLazy = NO; + } + } + } else if (animatedImage && !isHDRImage) { + // iOS 15+, CGImageRef now retains CGImageSourceRef internally. To workaround its thread-safe issue, we have to strip CGImageSourceRef, using Force-Decode (or have to use SPI `CGImageSetImageSource`), See: https://github.com/SDWebImage/SDWebImage/issues/3273 + if (@available(iOS 15, tvOS 15, *)) { + // User pass `lazyDecode == YES`, but we still have to strip the CGImageSourceRef + // CGImageRef newImageRef = CGImageCreateCopy(imageRef); // This one does not strip the CGImageProperty + CGImageRef newImageRef = SDCGImageCreateCopy(imageRef); + if (newImageRef) { + CGImageRelease(imageRef); + imageRef = newImageRef; + } +#if SD_CHECK_CGIMAGE_RETAIN_SOURCE + // Assert here to check CGImageRef should not retain the CGImageSourceRef and has possible thread-safe issue (this is behavior on iOS 15+) + // If assert hit, fire issue to https://github.com/SDWebImage/SDWebImage/issues and we update the condition for this behavior check + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + SDCGImageGetImageSource = dlsym(RTLD_DEFAULT, "CGImageGetImageSource"); + }); + if (SDCGImageGetImageSource) { + NSCAssert(!SDCGImageGetImageSource(imageRef), @"Animated Coder created CGImageRef should not retain CGImageSourceRef, which may cause thread-safe issue without lock"); + } +#endif + } + } + // :) + CFStringRef uttype = CGImageSourceGetType(source); + SDImageFormat imageFormat = [NSData sd_imageFormatFromUTType:uttype]; + if (imageFormat == SDImageFormatPNG && SDCGImageIs8Bit(imageRef) && SDImageIOPNGPluginBuggyNeedWorkaround()) { + CGImageRef newImageRef = SDImageIOPNGPluginBuggyCreateWorkaround(imageRef); + CGImageRelease(imageRef); + imageRef = newImageRef; + } + +#if SD_UIKIT || SD_WATCH + UIImageOrientation imageOrientation = [SDImageCoderHelper imageOrientationFromEXIFOrientation:exifOrientation]; + UIImage *image = [[UIImage alloc] initWithCGImage:imageRef scale:scale orientation:imageOrientation]; +#else + UIImage *image = [[UIImage alloc] initWithCGImage:imageRef scale:scale orientation:exifOrientation]; +#endif + CGImageRelease(imageRef); + image.sd_isDecoded = !isLazy; + + return image; +} + +#pragma mark - Decode +- (BOOL)canDecodeFromData:(nullable NSData *)data { + return ([NSData sd_imageFormatForImageData:data] == self.class.imageFormat); +} + +- (UIImage *)decodedImageWithData:(NSData *)data options:(nullable SDImageCoderOptions *)options { + if (!data) { + return nil; + } + CGFloat scale = 1; + NSNumber *scaleFactor = options[SDImageCoderDecodeScaleFactor]; + if (scaleFactor != nil) { + scale = MAX([scaleFactor doubleValue], 1); + } + + CGSize thumbnailSize = CGSizeZero; + NSValue *thumbnailSizeValue = options[SDImageCoderDecodeThumbnailPixelSize]; + if (thumbnailSizeValue != nil) { +#if SD_MAC + thumbnailSize = thumbnailSizeValue.sizeValue; +#else + thumbnailSize = thumbnailSizeValue.CGSizeValue; +#endif + } + + BOOL preserveAspectRatio = YES; + NSNumber *preserveAspectRatioValue = options[SDImageCoderDecodePreserveAspectRatio]; + if (preserveAspectRatioValue != nil) { + preserveAspectRatio = preserveAspectRatioValue.boolValue; + } + + BOOL lazyDecode = YES; // Defaults YES for static image coder + NSNumber *lazyDecodeValue = options[SDImageCoderDecodeUseLazyDecoding]; + if (lazyDecodeValue != nil) { + lazyDecode = lazyDecodeValue.boolValue; + } + + NSUInteger limitBytes = 0; + NSNumber *limitBytesValue = options[SDImageCoderDecodeScaleDownLimitBytes]; + if (limitBytesValue != nil) { + limitBytes = limitBytesValue.unsignedIntegerValue; + } + + BOOL decodeToHDR = [options[SDImageCoderDecodeToHDR] boolValue]; + +#if SD_MAC + // If don't use thumbnail, prefers the built-in generation of frames (GIF/APNG) + // Which decode frames in time and reduce memory usage + if (limitBytes == 0 && (thumbnailSize.width == 0 || thumbnailSize.height == 0)) { + SDAnimatedImageRep *imageRep = [[SDAnimatedImageRep alloc] initWithData:data]; + if (imageRep) { + NSSize size = NSMakeSize(imageRep.pixelsWide / scale, imageRep.pixelsHigh / scale); + imageRep.size = size; + NSImage *animatedImage = [[NSImage alloc] initWithSize:size]; + [animatedImage addRepresentation:imageRep]; + animatedImage.sd_imageFormat = self.class.imageFormat; + return animatedImage; + } + } +#endif + + NSString *typeIdentifierHint = options[SDImageCoderDecodeTypeIdentifierHint]; + if (!typeIdentifierHint) { + // Check file extension and convert to UTI, from: https://stackoverflow.com/questions/1506251/getting-an-uniform-type-identifier-for-a-given-extension + NSString *fileExtensionHint = options[SDImageCoderDecodeFileExtensionHint]; + if (fileExtensionHint) { + typeIdentifierHint = (__bridge_transfer NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)fileExtensionHint, kUTTypeImage); + // Ignore dynamic UTI + if (UTTypeIsDynamic((__bridge CFStringRef)typeIdentifierHint)) { + typeIdentifierHint = nil; + } + } + } else if ([typeIdentifierHint isEqual:NSNull.null]) { + // Hack if user don't want to imply file extension + typeIdentifierHint = nil; + } + + NSDictionary *creatingOptions = nil; + if (typeIdentifierHint) { + creatingOptions = @{(__bridge NSString *)kCGImageSourceTypeIdentifierHint : typeIdentifierHint}; + } + CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, (__bridge CFDictionaryRef)creatingOptions); + if (!source) { + // Try again without UTType hint, the call site from user may provide the wrong UTType + source = CGImageSourceCreateWithData((__bridge CFDataRef)data, nil); + } + if (!source) { + return nil; + } + + size_t frameCount = CGImageSourceGetCount(source); + UIImage *animatedImage; + + // Parse the image properties + NSDictionary *properties = (__bridge_transfer NSDictionary *)CGImageSourceCopyPropertiesAtIndex(source, 0, NULL); + size_t width = [properties[(__bridge NSString *)kCGImagePropertyPixelWidth] doubleValue]; + size_t height = [properties[(__bridge NSString *)kCGImagePropertyPixelHeight] doubleValue]; + // Scale down to limit bytes if need + if (limitBytes > 0) { + // Hack since ImageIO public API (not CGImageDecompressor/CMPhoto) always return back RGBA8888 CGImage + CGSize imageSize = CGSizeMake(width, height); + CGSize framePixelSize = [SDImageCoderHelper scaledSizeWithImageSize:imageSize limitBytes:limitBytes bytesPerPixel:4 frameCount:frameCount]; + // Override thumbnail size + thumbnailSize = framePixelSize; + preserveAspectRatio = YES; + } + + BOOL decodeFirstFrame = [options[SDImageCoderDecodeFirstFrameOnly] boolValue]; + if (decodeFirstFrame || frameCount <= 1) { + animatedImage = [self.class createFrameAtIndex:0 source:source scale:scale preserveAspectRatio:preserveAspectRatio thumbnailSize:thumbnailSize lazyDecode:lazyDecode animatedImage:NO decodeToHDR:decodeToHDR]; + } else { + NSMutableArray *frames = [NSMutableArray arrayWithCapacity:frameCount]; + + for (size_t i = 0; i < frameCount; i++) { + UIImage *image = [self.class createFrameAtIndex:i source:source scale:scale preserveAspectRatio:preserveAspectRatio thumbnailSize:thumbnailSize lazyDecode:lazyDecode animatedImage:NO decodeToHDR:decodeToHDR]; + if (!image) { + continue; + } + + NSTimeInterval duration = [self.class frameDurationAtIndex:i source:source]; + + SDImageFrame *frame = [SDImageFrame frameWithImage:image duration:duration]; + [frames addObject:frame]; + } + + NSUInteger loopCount = [self.class imageLoopCountWithSource:source]; + + animatedImage = [SDImageCoderHelper animatedImageWithFrames:frames]; + animatedImage.sd_imageLoopCount = loopCount; + } + animatedImage.sd_imageFormat = self.class.imageFormat; + CFRelease(source); + + return animatedImage; +} + +#pragma mark - Progressive Decode + +- (BOOL)canIncrementalDecodeFromData:(NSData *)data { + return ([NSData sd_imageFormatForImageData:data] == self.class.imageFormat); +} + +- (instancetype)initIncrementalWithOptions:(nullable SDImageCoderOptions *)options { + self = [super init]; + if (self) { + NSString *imageUTType = self.class.imageUTType; + _imageSource = CGImageSourceCreateIncremental((__bridge CFDictionaryRef)@{(__bridge NSString *)kCGImageSourceTypeIdentifierHint : imageUTType}); + _incremental = YES; + CGFloat scale = 1; + NSNumber *scaleFactor = options[SDImageCoderDecodeScaleFactor]; + if (scaleFactor != nil) { + scale = MAX([scaleFactor doubleValue], 1); + } + _scale = scale; + CGSize thumbnailSize = CGSizeZero; + NSValue *thumbnailSizeValue = options[SDImageCoderDecodeThumbnailPixelSize]; + if (thumbnailSizeValue != nil) { + #if SD_MAC + thumbnailSize = thumbnailSizeValue.sizeValue; + #else + thumbnailSize = thumbnailSizeValue.CGSizeValue; + #endif + } + _thumbnailSize = thumbnailSize; + BOOL preserveAspectRatio = YES; + NSNumber *preserveAspectRatioValue = options[SDImageCoderDecodePreserveAspectRatio]; + if (preserveAspectRatioValue != nil) { + preserveAspectRatio = preserveAspectRatioValue.boolValue; + } + _preserveAspectRatio = preserveAspectRatio; + NSUInteger limitBytes = 0; + NSNumber *limitBytesValue = options[SDImageCoderDecodeScaleDownLimitBytes]; + if (limitBytesValue != nil) { + limitBytes = limitBytesValue.unsignedIntegerValue; + } + _limitBytes = limitBytes; + BOOL lazyDecode = NO; // Defaults NO for animated image coder + NSNumber *lazyDecodeValue = options[SDImageCoderDecodeUseLazyDecoding]; + if (lazyDecodeValue != nil) { + lazyDecode = lazyDecodeValue.boolValue; + } + _lazyDecode = lazyDecode; + + _decodeToHDR = [options[SDImageCoderDecodeToHDR] boolValue]; + + SD_LOCK_INIT(_lock); +#if SD_UIKIT + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveMemoryWarning:) name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; +#endif + } + return self; +} + +- (void)updateIncrementalData:(NSData *)data finished:(BOOL)finished { + NSCParameterAssert(_incremental); + if (_finished) { + return; + } + _imageData = data; + _finished = finished; + + // The following code is from http://www.cocoaintheshell.com/2011/05/progressive-images-download-imageio/ + // Thanks to the author @Nyx0uf + + // Update the data source, we must pass ALL the data, not just the new bytes + CGImageSourceUpdateData(_imageSource, (__bridge CFDataRef)data, finished); + + if (_width + _height == 0) { + CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(_imageSource, 0, NULL); + if (properties) { + CFTypeRef val = CFDictionaryGetValue(properties, kCGImagePropertyPixelHeight); + if (val) CFNumberGetValue(val, kCFNumberLongType, &_height); + val = CFDictionaryGetValue(properties, kCGImagePropertyPixelWidth); + if (val) CFNumberGetValue(val, kCFNumberLongType, &_width); + CFRelease(properties); + } + } + + SD_LOCK(_lock); + // For animated image progressive decoding because the frame count and duration may be changed. + [self scanAndCheckFramesValidWithImageSource:_imageSource]; + SD_UNLOCK(_lock); + + // Scale down to limit bytes if need + if (_limitBytes > 0) { + // Hack since ImageIO public API (not CGImageDecompressor/CMPhoto) always return back RGBA8888 CGImage + CGSize imageSize = CGSizeMake(_width, _height); + CGSize framePixelSize = [SDImageCoderHelper scaledSizeWithImageSize:imageSize limitBytes:_limitBytes bytesPerPixel:4 frameCount:_frameCount]; + // Override thumbnail size + _thumbnailSize = framePixelSize; + _preserveAspectRatio = YES; + } +} + +- (UIImage *)incrementalDecodedImageWithOptions:(SDImageCoderOptions *)options { + NSCParameterAssert(_incremental); + UIImage *image; + + if (_width + _height > 0) { + // Create the image + CGFloat scale = _scale; + NSNumber *scaleFactor = options[SDImageCoderDecodeScaleFactor]; + if (scaleFactor != nil) { + scale = MAX([scaleFactor doubleValue], 1); + } + image = [self.class createFrameAtIndex:0 source:_imageSource scale:scale preserveAspectRatio:_preserveAspectRatio thumbnailSize:_thumbnailSize lazyDecode:_lazyDecode animatedImage:NO decodeToHDR:_finished ? _decodeToHDR : NO]; + if (image) { + image.sd_imageFormat = self.class.imageFormat; + } + } + + return image; +} + +#pragma mark - Encode +- (BOOL)canEncodeToFormat:(SDImageFormat)format { + return (format == self.class.imageFormat); +} + +- (NSData *)encodedDataWithImage:(UIImage *)image format:(SDImageFormat)format options:(nullable SDImageCoderOptions *)options { + if (!image) { + return nil; + } + if (format != self.class.imageFormat) { + return nil; + } + + NSArray *frames = [SDImageCoderHelper framesFromAnimatedImage:image]; + if (!frames || frames.count == 0) { + SDImageFrame *frame = [SDImageFrame frameWithImage:image duration:0]; + frames = @[frame]; + } + return [self encodedDataWithFrames:frames loopCount:image.sd_imageLoopCount format:format options:options]; +} + +- (NSData *)encodedDataWithFrames:(NSArray *)frames loopCount:(NSUInteger)loopCount format:(SDImageFormat)format options:(SDImageCoderOptions *)options { + UIImage *image = frames.firstObject.image; // Primary image + if (!image) { + return nil; + } + CGImageRef imageRef = image.CGImage; + if (!imageRef) { + // Earily return, supports CGImage only + return nil; + } + BOOL onlyEncodeOnce = [options[SDImageCoderEncodeFirstFrameOnly] boolValue] || frames.count <= 1; + + NSMutableData *imageData = [NSMutableData data]; + NSString *imageUTType; + if (onlyEncodeOnce) { + imageUTType = self.class.imageUTType; + } else { + imageUTType = self.class.animatedImageUTType; + } + + // Create an image destination. Animated Image does not support EXIF image orientation TODO + // The `CGImageDestinationCreateWithData` will log a warning when count is 0, use 1 instead. + CGImageDestinationRef imageDestination = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)imageData, (__bridge CFStringRef)imageUTType, frames.count ?: 1, NULL); + if (!imageDestination) { + // Handle failure. + return nil; + } + NSMutableDictionary *properties = [NSMutableDictionary dictionary]; +#if SD_UIKIT || SD_WATCH + CGImagePropertyOrientation exifOrientation = [SDImageCoderHelper exifOrientationFromImageOrientation:image.imageOrientation]; +#else + CGImagePropertyOrientation exifOrientation = kCGImagePropertyOrientationUp; +#endif + if (exifOrientation != kCGImagePropertyOrientationUp) { + properties[(__bridge NSString *)kCGImagePropertyOrientation] = @(exifOrientation); + } + // Encoding Options + double compressionQuality = 1; + if (options[SDImageCoderEncodeCompressionQuality]) { + compressionQuality = [options[SDImageCoderEncodeCompressionQuality] doubleValue]; + } + properties[(__bridge NSString *)kCGImageDestinationLossyCompressionQuality] = @(compressionQuality); + CGColorRef backgroundColor = [options[SDImageCoderEncodeBackgroundColor] CGColor]; + if (backgroundColor) { + properties[(__bridge NSString *)kCGImageDestinationBackgroundColor] = (__bridge id)(backgroundColor); + } + CGSize maxPixelSize = CGSizeZero; + NSValue *maxPixelSizeValue = options[SDImageCoderEncodeMaxPixelSize]; + if (maxPixelSizeValue != nil) { +#if SD_MAC + maxPixelSize = maxPixelSizeValue.sizeValue; +#else + maxPixelSize = maxPixelSizeValue.CGSizeValue; +#endif + } + // HDR Encoding + NSUInteger encodeToHDR = 0; + if (options[SDImageCoderEncodeToHDR]) { + encodeToHDR = [options[SDImageCoderEncodeToHDR] unsignedIntegerValue]; + } + if (@available(macOS 15, iOS 18, tvOS 18, watchOS 11, *)) { + if (encodeToHDR == SDImageHDRTypeISOHDR) { + properties[kSDCGImageDestinationEncodeRequest] = kSDCGImageDestinationEncodeToISOHDR; + } else if (encodeToHDR == SDImageHDRTypeISOGainMap) { + properties[kSDCGImageDestinationEncodeRequest] = kSDCGImageDestinationEncodeToISOGainmap; + } else { + properties[kSDCGImageDestinationEncodeRequest] = kSDCGImageDestinationEncodeToSDR; + } + } + + CGFloat pixelWidth = (CGFloat)CGImageGetWidth(imageRef); + CGFloat pixelHeight = (CGFloat)CGImageGetHeight(imageRef); + CGFloat finalPixelSize = 0; + BOOL encodeFullImage = maxPixelSize.width == 0 || maxPixelSize.height == 0 || pixelWidth == 0 || pixelHeight == 0 || (pixelWidth <= maxPixelSize.width && pixelHeight <= maxPixelSize.height); + if (!encodeFullImage) { + // Thumbnail Encoding + CGFloat pixelRatio = pixelWidth / pixelHeight; + CGFloat maxPixelSizeRatio = maxPixelSize.width / maxPixelSize.height; + if (pixelRatio > maxPixelSizeRatio) { + finalPixelSize = MAX(maxPixelSize.width, maxPixelSize.width / pixelRatio); + } else { + finalPixelSize = MAX(maxPixelSize.height, maxPixelSize.height * pixelRatio); + } + properties[(__bridge NSString *)kCGImageDestinationImageMaxPixelSize] = @(finalPixelSize); + } + NSUInteger maxFileSize = [options[SDImageCoderEncodeMaxFileSize] unsignedIntegerValue]; + if (maxFileSize > 0) { + properties[kSDCGImageDestinationRequestedFileSize] = @(maxFileSize); + // Remove the quality if we have file size limit + properties[(__bridge NSString *)kCGImageDestinationLossyCompressionQuality] = nil; + } + BOOL embedThumbnail = NO; + if (options[SDImageCoderEncodeEmbedThumbnail]) { + embedThumbnail = [options[SDImageCoderEncodeEmbedThumbnail] boolValue]; + } + properties[(__bridge NSString *)kCGImageDestinationEmbedThumbnail] = @(embedThumbnail); + + if (onlyEncodeOnce) { + // for static single images + CGImageDestinationAddImage(imageDestination, imageRef, (__bridge CFDictionaryRef)properties); + } else { + // for animated images + NSDictionary *containerProperties = @{ + self.class.dictionaryProperty: @{self.class.loopCountProperty : @(loopCount)} + }; + // container level properties (applies for `CGImageDestinationSetProperties`, not individual frames) + CGImageDestinationSetProperties(imageDestination, (__bridge CFDictionaryRef)containerProperties); + + for (size_t i = 0; i < frames.count; i++) { + SDImageFrame *frame = frames[i]; + NSTimeInterval frameDuration = frame.duration; + CGImageRef frameImageRef = frame.image.CGImage; + properties[self.class.dictionaryProperty] = @{self.class.delayTimeProperty : @(frameDuration)}; + CGImageDestinationAddImage(imageDestination, frameImageRef, (__bridge CFDictionaryRef)properties); + } + } + // Finalize the destination. + if (CGImageDestinationFinalize(imageDestination) == NO) { + // Handle failure. + imageData = nil; + } + + CFRelease(imageDestination); + + // In some beta version, ImageIO `CGImageDestinationFinalize` returns success, but the data buffer is 0 bytes length. + if (imageData.length == 0) { + return nil; + } + + return [imageData copy]; +} + +#pragma mark - SDAnimatedImageCoder +- (nullable instancetype)initWithAnimatedImageData:(nullable NSData *)data options:(nullable SDImageCoderOptions *)options { + if (!data) { + return nil; + } + self = [super init]; + if (self) { + CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL); + if (!imageSource) { + return nil; + } + BOOL framesValid = [self scanAndCheckFramesValidWithImageSource:imageSource]; + if (!framesValid) { + CFRelease(imageSource); + return nil; + } + CGFloat scale = 1; + NSNumber *scaleFactor = options[SDImageCoderDecodeScaleFactor]; + if (scaleFactor != nil) { + scale = MAX([scaleFactor doubleValue], 1); + } + _scale = scale; + CGSize thumbnailSize = CGSizeZero; + NSValue *thumbnailSizeValue = options[SDImageCoderDecodeThumbnailPixelSize]; + if (thumbnailSizeValue != nil) { + #if SD_MAC + thumbnailSize = thumbnailSizeValue.sizeValue; + #else + thumbnailSize = thumbnailSizeValue.CGSizeValue; + #endif + } + _thumbnailSize = thumbnailSize; + BOOL preserveAspectRatio = YES; + NSNumber *preserveAspectRatioValue = options[SDImageCoderDecodePreserveAspectRatio]; + if (preserveAspectRatioValue != nil) { + preserveAspectRatio = preserveAspectRatioValue.boolValue; + } + _preserveAspectRatio = preserveAspectRatio; + NSUInteger limitBytes = 0; + NSNumber *limitBytesValue = options[SDImageCoderDecodeScaleDownLimitBytes]; + if (limitBytesValue != nil) { + limitBytes = limitBytesValue.unsignedIntegerValue; + } + _limitBytes = limitBytes; + // Parse the image properties + NSDictionary *properties = (__bridge_transfer NSDictionary *)CGImageSourceCopyPropertiesAtIndex(imageSource, 0, NULL); + _width = [properties[(__bridge NSString *)kCGImagePropertyPixelWidth] doubleValue]; + _height = [properties[(__bridge NSString *)kCGImagePropertyPixelHeight] doubleValue]; + // Scale down to limit bytes if need + if (_limitBytes > 0) { + // Hack since ImageIO public API (not CGImageDecompressor/CMPhoto) always return back RGBA8888 CGImage + CGSize imageSize = CGSizeMake(_width, _height); + CGSize framePixelSize = [SDImageCoderHelper scaledSizeWithImageSize:imageSize limitBytes:_limitBytes bytesPerPixel:4 frameCount:_frameCount]; + // Override thumbnail size + _thumbnailSize = framePixelSize; + _preserveAspectRatio = YES; + } + BOOL lazyDecode = NO; // Defaults NO for animated image coder + NSNumber *lazyDecodeValue = options[SDImageCoderDecodeUseLazyDecoding]; + if (lazyDecodeValue != nil) { + lazyDecode = lazyDecodeValue.boolValue; + } + _lazyDecode = lazyDecode; + + _decodeToHDR = [options[SDImageCoderDecodeToHDR] boolValue]; + + _imageSource = imageSource; + _imageData = data; +#if SD_UIKIT + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveMemoryWarning:) name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; +#endif + } + return self; +} + +- (BOOL)scanAndCheckFramesValidWithImageSource:(CGImageSourceRef)imageSource { + if (!imageSource) { + return NO; + } + NSUInteger frameCount = CGImageSourceGetCount(imageSource); + NSUInteger loopCount = [self.class imageLoopCountWithSource:imageSource]; + _loopCount = loopCount; + + NSMutableArray *frames = [NSMutableArray arrayWithCapacity:frameCount]; + for (size_t i = 0; i < frameCount; i++) { + SDImageIOCoderFrame *frame = [[SDImageIOCoderFrame alloc] init]; + frame.index = i; + frame.duration = [self.class frameDurationAtIndex:i source:imageSource]; + [frames addObject:frame]; + } + if (frames.count != frameCount) { + // frames not match, do not override current value + return NO; + } + + _frameCount = frameCount; + _frames = [frames copy]; + + return YES; +} + +- (NSData *)animatedImageData { + return _imageData; +} + +- (NSUInteger)animatedImageLoopCount { + return _loopCount; +} + +- (NSUInteger)animatedImageFrameCount { + return _frameCount; +} + +- (NSTimeInterval)animatedImageDurationAtIndex:(NSUInteger)index { + NSTimeInterval duration; + // Incremental Animation decoding may update frames when new bytes available + // Which should use lock to ensure frame count and frames match, ensure atomic logic + if (_incremental) { + SD_LOCK(_lock); + if (index >= _frames.count) { + SD_UNLOCK(_lock); + return 0; + } + duration = _frames[index].duration; + SD_UNLOCK(_lock); + } else { + if (index >= _frames.count) { + return 0; + } + duration = _frames[index].duration; + } + return duration; +} + +- (UIImage *)animatedImageFrameAtIndex:(NSUInteger)index { + UIImage *image; + // Incremental Animation decoding may update frames when new bytes available + // Which should use lock to ensure frame count and frames match, ensure atomic logic + if (_incremental) { + SD_LOCK(_lock); + if (index >= _frames.count) { + SD_UNLOCK(_lock); + return nil; + } + image = [self safeAnimatedImageFrameAtIndex:index]; + SD_UNLOCK(_lock); + } else { + if (index >= _frames.count) { + return nil; + } + image = [self safeAnimatedImageFrameAtIndex:index]; + } + return image; +} + +- (UIImage *)safeAnimatedImageFrameAtIndex:(NSUInteger)index { + UIImage *image = [self.class createFrameAtIndex:index source:_imageSource scale:_scale preserveAspectRatio:_preserveAspectRatio thumbnailSize:_thumbnailSize lazyDecode:_lazyDecode animatedImage:YES decodeToHDR:!_incremental || _finished ? _decodeToHDR : NO]; + if (!image) { + return nil; + } + image.sd_imageFormat = self.class.imageFormat; + return image; +} + +@end + diff --git a/Pods/SDWebImage/SDWebImage/Core/SDImageIOCoder.h b/Pods/SDWebImage/SDWebImage/Core/SDImageIOCoder.h new file mode 100644 index 0000000..98682ed --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDImageIOCoder.h @@ -0,0 +1,30 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDImageCoder.h" + +/** + Built in coder that supports PNG, JPEG, TIFF, includes support for progressive decoding. + + GIF + Also supports static GIF (meaning will only handle the 1st frame). + For a full GIF support, we recommend `SDAnimatedImageView` to keep both CPU and memory balanced. + + HEIC + This coder also supports HEIC format because ImageIO supports it natively. But it depends on the system capabilities, so it won't work on all devices, see: https://devstreaming-cdn.apple.com/videos/wwdc/2017/511tj33587vdhds/511/511_working_with_heif_and_hevc.pdf + Decode(Software): !Simulator && (iOS 11 || tvOS 11 || macOS 10.13) + Decode(Hardware): !Simulator && ((iOS 11 && A9Chip) || (macOS 10.13 && 6thGenerationIntelCPU)) + Encode(Software): macOS 10.13 + Encode(Hardware): !Simulator && ((iOS 11 && A10FusionChip) || (macOS 10.13 && 6thGenerationIntelCPU)) + */ +@interface SDImageIOCoder : NSObject + +@property (nonatomic, class, readonly, nonnull) SDImageIOCoder *sharedCoder; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDImageIOCoder.m b/Pods/SDWebImage/SDWebImage/Core/SDImageIOCoder.m new file mode 100644 index 0000000..5606c46 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDImageIOCoder.m @@ -0,0 +1,458 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDImageIOCoder.h" +#import "SDImageCoderHelper.h" +#import "NSImage+Compatibility.h" +#import "UIImage+Metadata.h" +#import "SDImageGraphics.h" +#import "SDImageIOAnimatedCoderInternal.h" + +#import +#import + +// Specify File Size for lossy format encoding, like JPEG +static NSString * kSDCGImageDestinationRequestedFileSize = @"kCGImageDestinationRequestedFileSize"; +// Support Xcode 15 SDK, use raw value instead of symbol +static NSString * kSDCGImageDestinationEncodeRequest = @"kCGImageDestinationEncodeRequest"; +static NSString * kSDCGImageDestinationEncodeToSDR = @"kCGImageDestinationEncodeToSDR"; +static NSString * kSDCGImageDestinationEncodeToISOHDR = @"kCGImageDestinationEncodeToISOHDR"; +static NSString * kSDCGImageDestinationEncodeToISOGainmap = @"kCGImageDestinationEncodeToISOGainmap"; + + +@implementation SDImageIOCoder { + size_t _width, _height; + CGImagePropertyOrientation _orientation; + CGImageSourceRef _imageSource; + CGFloat _scale; + BOOL _finished; + BOOL _preserveAspectRatio; + CGSize _thumbnailSize; + BOOL _lazyDecode; + BOOL _decodeToHDR; +} + +#if SD_IMAGEIO_HDR_ENCODING ++ (void)initialize { + if (@available(macOS 15, iOS 18, tvOS 18, watchOS 11, *)) { + // Use SDK instead of raw value + kSDCGImageDestinationEncodeRequest = (__bridge NSString *)kCGImageDestinationEncodeRequest; + kSDCGImageDestinationEncodeToSDR = (__bridge NSString *)kCGImageDestinationEncodeToSDR; + kSDCGImageDestinationEncodeToISOHDR = (__bridge NSString *)kCGImageDestinationEncodeToISOHDR; + kSDCGImageDestinationEncodeToISOGainmap = (__bridge NSString *)kCGImageDestinationEncodeToISOGainmap; + } +} +#endif + +- (void)dealloc { + if (_imageSource) { + CFRelease(_imageSource); + _imageSource = NULL; + } +#if SD_UIKIT + [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; +#endif +} + +- (void)didReceiveMemoryWarning:(NSNotification *)notification +{ + if (_imageSource) { + CGImageSourceRemoveCacheAtIndex(_imageSource, 0); + } +} + ++ (instancetype)sharedCoder { + static SDImageIOCoder *coder; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + coder = [[SDImageIOCoder alloc] init]; + }); + return coder; +} + +#pragma mark - Bitmap PDF representation ++ (UIImage *)createBitmapPDFWithData:(nonnull NSData *)data pageNumber:(NSUInteger)pageNumber targetSize:(CGSize)targetSize preserveAspectRatio:(BOOL)preserveAspectRatio { + NSParameterAssert(data); + UIImage *image; + + CGDataProviderRef provider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data); + if (!provider) { + return nil; + } + CGPDFDocumentRef document = CGPDFDocumentCreateWithProvider(provider); + CGDataProviderRelease(provider); + if (!document) { + return nil; + } + + // `CGPDFDocumentGetPage` page number is 1-indexed. + CGPDFPageRef page = CGPDFDocumentGetPage(document, pageNumber + 1); + if (!page) { + CGPDFDocumentRelease(document); + return nil; + } + + CGPDFBox box = kCGPDFMediaBox; + CGRect rect = CGPDFPageGetBoxRect(page, box); + CGRect targetRect = rect; + if (!CGSizeEqualToSize(targetSize, CGSizeZero)) { + targetRect = CGRectMake(0, 0, targetSize.width, targetSize.height); + } + + CGFloat xRatio = targetRect.size.width / rect.size.width; + CGFloat yRatio = targetRect.size.height / rect.size.height; + CGFloat xScale = preserveAspectRatio ? MIN(xRatio, yRatio) : xRatio; + CGFloat yScale = preserveAspectRatio ? MIN(xRatio, yRatio) : yRatio; + + // `CGPDFPageGetDrawingTransform` will only scale down, but not scale up, so we need calculate the actual scale again + CGRect drawRect = CGRectMake( 0, 0, targetRect.size.width / xScale, targetRect.size.height / yScale); + CGAffineTransform scaleTransform = CGAffineTransformMakeScale(xScale, yScale); + CGAffineTransform transform = CGPDFPageGetDrawingTransform(page, box, drawRect, 0, preserveAspectRatio); + + SDGraphicsBeginImageContextWithOptions(targetRect.size, NO, 0); + CGContextRef context = SDGraphicsGetCurrentContext(); + +#if SD_UIKIT || SD_WATCH + // Core Graphics coordinate system use the bottom-left, UIKit use the flipped one + CGContextTranslateCTM(context, 0, targetRect.size.height); + CGContextScaleCTM(context, 1, -1); +#endif + + CGContextConcatCTM(context, scaleTransform); + CGContextConcatCTM(context, transform); + + CGContextDrawPDFPage(context, page); + + image = SDGraphicsGetImageFromCurrentImageContext(); + SDGraphicsEndImageContext(); + + CGPDFDocumentRelease(document); + + return image; +} + +#pragma mark - Decode +- (BOOL)canDecodeFromData:(nullable NSData *)data { + return YES; +} + +- (UIImage *)decodedImageWithData:(NSData *)data options:(nullable SDImageCoderOptions *)options { + if (!data) { + return nil; + } + CGFloat scale = 1; + NSNumber *scaleFactor = options[SDImageCoderDecodeScaleFactor]; + if (scaleFactor != nil) { + scale = MAX([scaleFactor doubleValue], 1) ; + } + + CGSize thumbnailSize = CGSizeZero; + NSValue *thumbnailSizeValue = options[SDImageCoderDecodeThumbnailPixelSize]; + if (thumbnailSizeValue != nil) { +#if SD_MAC + thumbnailSize = thumbnailSizeValue.sizeValue; +#else + thumbnailSize = thumbnailSizeValue.CGSizeValue; +#endif + } + + BOOL preserveAspectRatio = YES; + NSNumber *preserveAspectRatioValue = options[SDImageCoderDecodePreserveAspectRatio]; + if (preserveAspectRatioValue != nil) { + preserveAspectRatio = preserveAspectRatioValue.boolValue; + } + + // Check vector format + if ([NSData sd_imageFormatForImageData:data] == SDImageFormatPDF) { + // History before iOS 16, ImageIO can decode PDF with rasterization size, but can't ever :( + // So, use CoreGraphics to decode PDF (copy code from SDWebImagePDFCoder, may do refactor in the future) + UIImage *image; + NSUInteger pageNumber = 0; // Still use first page, may added options is user want +#if SD_MAC + // If don't use thumbnail, prefers the built-in generation of vector image + // macOS's `NSImage` supports PDF built-in rendering + if (thumbnailSize.width == 0 || thumbnailSize.height == 0) { + NSPDFImageRep *imageRep = [[NSPDFImageRep alloc] initWithData:data]; + if (imageRep) { + imageRep.currentPage = pageNumber; + image = [[NSImage alloc] initWithSize:imageRep.size]; + [image addRepresentation:imageRep]; + image.sd_imageFormat = SDImageFormatPDF; + return image; + } + } +#endif + image = [self.class createBitmapPDFWithData:data pageNumber:pageNumber targetSize:thumbnailSize preserveAspectRatio:preserveAspectRatio]; + image.sd_imageFormat = SDImageFormatPDF; + return image; + } + + BOOL lazyDecode = YES; // Defaults YES for static image coder + NSNumber *lazyDecodeValue = options[SDImageCoderDecodeUseLazyDecoding]; + if (lazyDecodeValue != nil) { + lazyDecode = lazyDecodeValue.boolValue; + } + + BOOL decodeToHDR = [options[SDImageCoderDecodeToHDR] boolValue]; + + NSString *typeIdentifierHint = options[SDImageCoderDecodeTypeIdentifierHint]; + if (!typeIdentifierHint) { + // Check file extension and convert to UTI, from: https://stackoverflow.com/questions/1506251/getting-an-uniform-type-identifier-for-a-given-extension + NSString *fileExtensionHint = options[SDImageCoderDecodeFileExtensionHint]; + if (fileExtensionHint) { + typeIdentifierHint = (__bridge_transfer NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)fileExtensionHint, kUTTypeImage); + // Ignore dynamic UTI + if (UTTypeIsDynamic((__bridge CFStringRef)typeIdentifierHint)) { + typeIdentifierHint = nil; + } + } + } else if ([typeIdentifierHint isEqual:NSNull.null]) { + // Hack if user don't want to imply file extension + typeIdentifierHint = nil; + } + + NSDictionary *creatingOptions = nil; + if (typeIdentifierHint) { + creatingOptions = @{(__bridge NSString *)kCGImageSourceTypeIdentifierHint : typeIdentifierHint}; + } + CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, (__bridge CFDictionaryRef)creatingOptions); + if (!source) { + // Try again without UTType hint, the call site from user may provide the wrong UTType + source = CGImageSourceCreateWithData((__bridge CFDataRef)data, nil); + } + if (!source) { + return nil; + } + + CFStringRef uttype = CGImageSourceGetType(source); + SDImageFormat imageFormat = [NSData sd_imageFormatFromUTType:uttype]; + + UIImage *image = [SDImageIOAnimatedCoder createFrameAtIndex:0 source:source scale:scale preserveAspectRatio:preserveAspectRatio thumbnailSize:thumbnailSize lazyDecode:lazyDecode animatedImage:NO decodeToHDR:decodeToHDR]; + CFRelease(source); + + image.sd_imageFormat = imageFormat; + return image; +} + +#pragma mark - Progressive Decode + +- (BOOL)canIncrementalDecodeFromData:(NSData *)data { + return [self canDecodeFromData:data]; +} + +- (instancetype)initIncrementalWithOptions:(nullable SDImageCoderOptions *)options { + self = [super init]; + if (self) { + _imageSource = CGImageSourceCreateIncremental(NULL); + CGFloat scale = 1; + NSNumber *scaleFactor = options[SDImageCoderDecodeScaleFactor]; + if (scaleFactor != nil) { + scale = MAX([scaleFactor doubleValue], 1); + } + _scale = scale; + CGSize thumbnailSize = CGSizeZero; + NSValue *thumbnailSizeValue = options[SDImageCoderDecodeThumbnailPixelSize]; + if (thumbnailSizeValue != nil) { + #if SD_MAC + thumbnailSize = thumbnailSizeValue.sizeValue; + #else + thumbnailSize = thumbnailSizeValue.CGSizeValue; + #endif + } + _thumbnailSize = thumbnailSize; + BOOL preserveAspectRatio = YES; + NSNumber *preserveAspectRatioValue = options[SDImageCoderDecodePreserveAspectRatio]; + if (preserveAspectRatioValue != nil) { + preserveAspectRatio = preserveAspectRatioValue.boolValue; + } + _preserveAspectRatio = preserveAspectRatio; + BOOL lazyDecode = YES; // Defaults YES for static image coder + NSNumber *lazyDecodeValue = options[SDImageCoderDecodeUseLazyDecoding]; + if (lazyDecodeValue != nil) { + lazyDecode = lazyDecodeValue.boolValue; + } + _lazyDecode = lazyDecode; + + _decodeToHDR = [options[SDImageCoderDecodeToHDR] boolValue]; + +#if SD_UIKIT + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveMemoryWarning:) name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; +#endif + } + return self; +} + +- (void)updateIncrementalData:(NSData *)data finished:(BOOL)finished { + if (_finished) { + return; + } + _finished = finished; + + // The following code is from http://www.cocoaintheshell.com/2011/05/progressive-images-download-imageio/ + // Thanks to the author @Nyx0uf + + // Update the data source, we must pass ALL the data, not just the new bytes + CGImageSourceUpdateData(_imageSource, (__bridge CFDataRef)data, finished); + + if (_width + _height == 0) { + CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(_imageSource, 0, NULL); + if (properties) { + NSInteger orientationValue = 1; + CFTypeRef val = CFDictionaryGetValue(properties, kCGImagePropertyPixelHeight); + if (val) CFNumberGetValue(val, kCFNumberLongType, &_height); + val = CFDictionaryGetValue(properties, kCGImagePropertyPixelWidth); + if (val) CFNumberGetValue(val, kCFNumberLongType, &_width); + val = CFDictionaryGetValue(properties, kCGImagePropertyOrientation); + if (val) CFNumberGetValue(val, kCFNumberNSIntegerType, &orientationValue); + CFRelease(properties); + + // When we draw to Core Graphics, we lose orientation information, + // which means the image below born of initWithCGIImage will be + // oriented incorrectly sometimes. (Unlike the image born of initWithData + // in didCompleteWithError.) So save it here and pass it on later. + _orientation = (CGImagePropertyOrientation)orientationValue; + } + } +} + +- (UIImage *)incrementalDecodedImageWithOptions:(SDImageCoderOptions *)options { + UIImage *image; + + if (_width + _height > 0) { + // Create the image + CGFloat scale = _scale; + NSNumber *scaleFactor = options[SDImageCoderDecodeScaleFactor]; + if (scaleFactor != nil) { + scale = MAX([scaleFactor doubleValue], 1); + } + image = [SDImageIOAnimatedCoder createFrameAtIndex:0 source:_imageSource scale:scale preserveAspectRatio:_preserveAspectRatio thumbnailSize:_thumbnailSize lazyDecode:_lazyDecode animatedImage:NO decodeToHDR:_finished ? _decodeToHDR : NO]; + if (image) { + CFStringRef uttype = CGImageSourceGetType(_imageSource); + image.sd_imageFormat = [NSData sd_imageFormatFromUTType:uttype]; + } + } + + return image; +} + +#pragma mark - Encode +- (BOOL)canEncodeToFormat:(SDImageFormat)format { + return YES; +} + +- (NSData *)encodedDataWithImage:(UIImage *)image format:(SDImageFormat)format options:(nullable SDImageCoderOptions *)options { + if (!image) { + return nil; + } + CGImageRef imageRef = image.CGImage; + if (!imageRef) { + // Earily return, supports CGImage only + return nil; + } + if (format == SDImageFormatUndefined) { + BOOL hasAlpha = [SDImageCoderHelper CGImageContainsAlpha:imageRef]; + if (hasAlpha) { + format = SDImageFormatPNG; + } else { + format = SDImageFormatJPEG; + } + } + + NSMutableData *imageData = [NSMutableData data]; + CFStringRef imageUTType = [NSData sd_UTTypeFromImageFormat:format]; + + // Create an image destination. + CGImageDestinationRef imageDestination = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)imageData, imageUTType, 1, NULL); + if (!imageDestination) { + // Handle failure. + return nil; + } + + NSMutableDictionary *properties = [NSMutableDictionary dictionary]; +#if SD_UIKIT || SD_WATCH + CGImagePropertyOrientation exifOrientation = [SDImageCoderHelper exifOrientationFromImageOrientation:image.imageOrientation]; +#else + CGImagePropertyOrientation exifOrientation = kCGImagePropertyOrientationUp; +#endif + properties[(__bridge NSString *)kCGImagePropertyOrientation] = @(exifOrientation); + // Encoding Options + double compressionQuality = 1; + if (options[SDImageCoderEncodeCompressionQuality]) { + compressionQuality = [options[SDImageCoderEncodeCompressionQuality] doubleValue]; + } + properties[(__bridge NSString *)kCGImageDestinationLossyCompressionQuality] = @(compressionQuality); + CGColorRef backgroundColor = [options[SDImageCoderEncodeBackgroundColor] CGColor]; + if (backgroundColor) { + properties[(__bridge NSString *)kCGImageDestinationBackgroundColor] = (__bridge id)(backgroundColor); + } + CGSize maxPixelSize = CGSizeZero; + NSValue *maxPixelSizeValue = options[SDImageCoderEncodeMaxPixelSize]; + if (maxPixelSizeValue != nil) { +#if SD_MAC + maxPixelSize = maxPixelSizeValue.sizeValue; +#else + maxPixelSize = maxPixelSizeValue.CGSizeValue; +#endif + } + // HDR Encoding + NSUInteger encodeToHDR = 0; + if (options[SDImageCoderEncodeToHDR]) { + encodeToHDR = [options[SDImageCoderEncodeToHDR] unsignedIntegerValue]; + } + if (@available(macOS 15, iOS 18, tvOS 18, watchOS 11, *)) { + if (encodeToHDR == SDImageHDRTypeISOHDR) { + properties[kSDCGImageDestinationEncodeRequest] = kSDCGImageDestinationEncodeToISOHDR; + } else if (encodeToHDR == SDImageHDRTypeISOGainMap) { + properties[kSDCGImageDestinationEncodeRequest] = kSDCGImageDestinationEncodeToISOGainmap; + } else { + properties[kSDCGImageDestinationEncodeRequest] = kSDCGImageDestinationEncodeToSDR; + } + } + + CGFloat pixelWidth = (CGFloat)CGImageGetWidth(imageRef); + CGFloat pixelHeight = (CGFloat)CGImageGetHeight(imageRef); + CGFloat finalPixelSize = 0; + BOOL encodeFullImage = maxPixelSize.width == 0 || maxPixelSize.height == 0 || pixelWidth == 0 || pixelHeight == 0 || (pixelWidth <= maxPixelSize.width && pixelHeight <= maxPixelSize.height); + if (!encodeFullImage) { + // Thumbnail Encoding + CGFloat pixelRatio = pixelWidth / pixelHeight; + CGFloat maxPixelSizeRatio = maxPixelSize.width / maxPixelSize.height; + if (pixelRatio > maxPixelSizeRatio) { + finalPixelSize = MAX(maxPixelSize.width, maxPixelSize.width / pixelRatio); + } else { + finalPixelSize = MAX(maxPixelSize.height, maxPixelSize.height * pixelRatio); + } + properties[(__bridge NSString *)kCGImageDestinationImageMaxPixelSize] = @(finalPixelSize); + } + NSUInteger maxFileSize = [options[SDImageCoderEncodeMaxFileSize] unsignedIntegerValue]; + if (maxFileSize > 0) { + properties[kSDCGImageDestinationRequestedFileSize] = @(maxFileSize); + // Remove the quality if we have file size limit + properties[(__bridge NSString *)kCGImageDestinationLossyCompressionQuality] = nil; + } + BOOL embedThumbnail = NO; + if (options[SDImageCoderEncodeEmbedThumbnail]) { + embedThumbnail = [options[SDImageCoderEncodeEmbedThumbnail] boolValue]; + } + properties[(__bridge NSString *)kCGImageDestinationEmbedThumbnail] = @(embedThumbnail); + + // Add your image to the destination. + CGImageDestinationAddImage(imageDestination, imageRef, (__bridge CFDictionaryRef)properties); + + // Finalize the destination. + if (CGImageDestinationFinalize(imageDestination) == NO) { + // Handle failure. + imageData = nil; + } + + CFRelease(imageDestination); + + return [imageData copy]; +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDImageLoader.h b/Pods/SDWebImage/SDWebImage/Core/SDImageLoader.h new file mode 100644 index 0000000..62ddc8e --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDImageLoader.h @@ -0,0 +1,146 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" +#import "SDWebImageDefine.h" +#import "SDWebImageOperation.h" +#import "SDImageCoder.h" + +typedef void(^SDImageLoaderProgressBlock)(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL); +typedef void(^SDImageLoaderCompletedBlock)(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished); + +#pragma mark - Context Options + +/** + A `UIImage` instance from `SDWebImageManager` when you specify `SDWebImageRefreshCached` and image cache hit. + This can be a hint for image loader to load the image from network and refresh the image from remote location if needed. If the image from remote location does not change, you should call the completion with `SDWebImageErrorCacheNotModified` error. (UIImage) + @note If you don't implement `SDWebImageRefreshCached` support, you do not need to care about this context option. + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextLoaderCachedImage; + +#pragma mark - Helper method + +/** + This is the built-in decoding process for image download from network or local file. + @note If you want to implement your custom loader with `requestImageWithURL:options:context:progress:completed:` API, but also want to keep compatible with SDWebImage's behavior, you'd better use this to produce image. + + @param imageData The image data from the network. Should not be nil + @param imageURL The image URL from the input. Should not be nil + @param options The options arg from the input + @param context The context arg from the input + @return The decoded image for current image data load from the network + */ +FOUNDATION_EXPORT UIImage * _Nullable SDImageLoaderDecodeImageData(NSData * _Nonnull imageData, NSURL * _Nonnull imageURL, SDWebImageOptions options, SDWebImageContext * _Nullable context); + +/** + This is the built-in decoding process for image progressive download from network. It's used when `SDWebImageProgressiveLoad` option is set. (It's not required when your loader does not support progressive image loading) + @note If you want to implement your custom loader with `requestImageWithURL:options:context:progress:completed:` API, but also want to keep compatible with SDWebImage's behavior, you'd better use this to produce image. + + @param imageData The image data from the network so far. Should not be nil + @param imageURL The image URL from the input. Should not be nil + @param finished Pass NO to specify the download process has not finished. Pass YES when all image data has finished. + @param operation The loader operation associated with current progressive download. Why to provide this is because progressive decoding need to store the partial decoded context for each operation to avoid conflict. You should provide the operation from `loadImageWithURL:` method return value. + @param options The options arg from the input + @param context The context arg from the input + @return The decoded progressive image for current image data load from the network + */ +FOUNDATION_EXPORT UIImage * _Nullable SDImageLoaderDecodeProgressiveImageData(NSData * _Nonnull imageData, NSURL * _Nonnull imageURL, BOOL finished, id _Nonnull operation, SDWebImageOptions options, SDWebImageContext * _Nullable context); + +/** + This function get the progressive decoder for current loading operation. If no progressive decoding is happended or decoder is not able to construct, return nil. + @return The progressive decoder associated with the loading operation. + */ +FOUNDATION_EXPORT id _Nullable SDImageLoaderGetProgressiveCoder(id _Nonnull operation); + +/** + This function set the progressive decoder for current loading operation. If no progressive decoding is happended, pass nil. + @param progressiveCoder The loading operation to associate the progerssive decoder. + */ +FOUNDATION_EXPORT void SDImageLoaderSetProgressiveCoder(id _Nonnull operation, id _Nullable progressiveCoder); + +#pragma mark - SDImageLoader + +/** + This is the protocol to specify custom image load process. You can create your own class to conform this protocol and use as a image loader to load image from network or any available remote resources defined by yourself. + If you want to implement custom loader for image download from network or local file, you just need to concentrate on image data download only. After the download finish, call `SDImageLoaderDecodeImageData` or `SDImageLoaderDecodeProgressiveImageData` to use the built-in decoding process and produce image (Remember to call in the global queue). And finally callback the completion block. + If you directly get the image instance using some third-party SDKs, such as image directly from Photos framework. You can process the image data and image instance by yourself without that built-in decoding process. And finally callback the completion block. + @note It's your responsibility to load the image in the desired global queue(to avoid block main queue). We do not dispatch these method call in a global queue but just from the call queue (For `SDWebImageManager`, it typically call from the main queue). +*/ +@protocol SDImageLoader + +@required +/** + Whether current image loader supports to load the provide image URL. + This will be checked every time a new image request come for loader. If this return NO, we will mark this image load as failed. If return YES, we will start to call `requestImageWithURL:options:context:progress:completed:`. + + @param url The image URL to be loaded. + @return YES to continue download, NO to stop download. + */ +- (BOOL)canRequestImageForURL:(nullable NSURL *)url API_DEPRECATED_WITH_REPLACEMENT("canRequestImageForURL:options:context:", macos(10.10, API_TO_BE_DEPRECATED), ios(8.0, API_TO_BE_DEPRECATED), tvos(9.0, API_TO_BE_DEPRECATED), watchos(2.0, API_TO_BE_DEPRECATED)); + +@optional +/** + Whether current image loader supports to load the provide image URL, with associated options and context. + This will be checked every time a new image request come for loader. If this return NO, we will mark this image load as failed. If return YES, we will start to call `requestImageWithURL:options:context:progress:completed:`. + + @param url The image URL to be loaded. + @param options A mask to specify options to use for this request + @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + @return YES to continue download, NO to stop download. + */ +- (BOOL)canRequestImageForURL:(nullable NSURL *)url + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context; + +@required +/** + Load the image and image data with the given URL and return the image data. You're responsible for producing the image instance. + + @param url The URL represent the image. Note this may not be a HTTP URL + @param options A mask to specify options to use for this request + @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + @param progressBlock A block called while image is downloading + * @note the progress block is executed on a background queue + @param completedBlock A block called when operation has been completed. + @return An operation which allow the user to cancel the current request. + */ +- (nullable id)requestImageWithURL:(nullable NSURL *)url + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDImageLoaderCompletedBlock)completedBlock; + + +/** + Whether the error from image loader should be marked indeed un-recoverable or not. + If this return YES, failed URL which does not using `SDWebImageRetryFailed` will be blocked into black list. Else not. + + @param url The URL represent the image. Note this may not be a HTTP URL + @param error The URL's loading error, from previous `requestImageWithURL:options:context:progress:completed:` completedBlock's error. + @return Whether to block this url or not. Return YES to mark this URL as failed. + */ +- (BOOL)shouldBlockFailedURLWithURL:(nonnull NSURL *)url + error:(nonnull NSError *)error API_DEPRECATED_WITH_REPLACEMENT("shouldBlockFailedURLWithURL:error:options:context:", macos(10.10, API_TO_BE_DEPRECATED), ios(8.0, API_TO_BE_DEPRECATED), tvos(9.0, API_TO_BE_DEPRECATED), watchos(2.0, API_TO_BE_DEPRECATED)); + +@optional +/** + Whether the error from image loader should be marked indeed un-recoverable or not, with associated options and context. + If this return YES, failed URL which does not using `SDWebImageRetryFailed` will be blocked into black list. Else not. + + @param url The URL represent the image. Note this may not be a HTTP URL + @param error The URL's loading error, from previous `requestImageWithURL:options:context:progress:completed:` completedBlock's error. + @param options A mask to specify options to use for this request + @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + @return Whether to block this url or not. Return YES to mark this URL as failed. + */ +- (BOOL)shouldBlockFailedURLWithURL:(nonnull NSURL *)url + error:(nonnull NSError *)error + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDImageLoader.m b/Pods/SDWebImage/SDWebImage/Core/SDImageLoader.m new file mode 100644 index 0000000..9c6c268 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDImageLoader.m @@ -0,0 +1,178 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDImageLoader.h" +#import "SDWebImageCacheKeyFilter.h" +#import "SDImageCodersManager.h" +#import "SDImageCoderHelper.h" +#import "SDAnimatedImage.h" +#import "UIImage+Metadata.h" +#import "SDInternalMacros.h" +#import "SDImageCacheDefine.h" +#import "objc/runtime.h" + +SDWebImageContextOption const SDWebImageContextLoaderCachedImage = @"loaderCachedImage"; + +static void * SDImageLoaderProgressiveCoderKey = &SDImageLoaderProgressiveCoderKey; + +id SDImageLoaderGetProgressiveCoder(id operation) { + NSCParameterAssert(operation); + return objc_getAssociatedObject(operation, SDImageLoaderProgressiveCoderKey); +} + +void SDImageLoaderSetProgressiveCoder(id operation, id progressiveCoder) { + NSCParameterAssert(operation); + objc_setAssociatedObject(operation, SDImageLoaderProgressiveCoderKey, progressiveCoder, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +UIImage * _Nullable SDImageLoaderDecodeImageData(NSData * _Nonnull imageData, NSURL * _Nonnull imageURL, SDWebImageOptions options, SDWebImageContext * _Nullable context) { + NSCParameterAssert(imageData); + NSCParameterAssert(imageURL); + + UIImage *image; + id cacheKeyFilter = context[SDWebImageContextCacheKeyFilter]; + NSString *cacheKey; + if (cacheKeyFilter) { + cacheKey = [cacheKeyFilter cacheKeyForURL:imageURL]; + } else { + cacheKey = imageURL.absoluteString; + } + SDImageCoderOptions *coderOptions = SDGetDecodeOptionsFromContext(context, options, cacheKey); + BOOL decodeFirstFrame = SD_OPTIONS_CONTAINS(options, SDWebImageDecodeFirstFrameOnly); + CGFloat scale = [coderOptions[SDImageCoderDecodeScaleFactor] doubleValue]; + + // Grab the image coder + id imageCoder = context[SDWebImageContextImageCoder]; + if (!imageCoder) { + imageCoder = [SDImageCodersManager sharedManager]; + } + + if (!decodeFirstFrame) { + // check whether we should use `SDAnimatedImage` + Class animatedImageClass = context[SDWebImageContextAnimatedImageClass]; + if ([animatedImageClass isSubclassOfClass:[UIImage class]] && [animatedImageClass conformsToProtocol:@protocol(SDAnimatedImage)]) { + image = [[animatedImageClass alloc] initWithData:imageData scale:scale options:coderOptions]; + if (image) { + // Preload frames if supported + if (options & SDWebImagePreloadAllFrames && [image respondsToSelector:@selector(preloadAllFrames)]) { + [((id)image) preloadAllFrames]; + } + } else { + // Check image class matching + if (options & SDWebImageMatchAnimatedImageClass) { + return nil; + } + } + } + } + if (!image) { + image = [imageCoder decodedImageWithData:imageData options:coderOptions]; + } + if (image) { + SDImageForceDecodePolicy policy = SDImageForceDecodePolicyAutomatic; + NSNumber *policyValue = context[SDWebImageContextImageForceDecodePolicy]; + if (policyValue != nil) { + policy = policyValue.unsignedIntegerValue; + } + // TODO: Deprecated, remove in SD 6.0... +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + if (SD_OPTIONS_CONTAINS(options, SDWebImageAvoidDecodeImage)) { + policy = SDImageForceDecodePolicyNever; + } +#pragma clang diagnostic pop + image = [SDImageCoderHelper decodedImageWithImage:image policy:policy]; + // assign the decode options, to let manager check whether to re-decode if needed + image.sd_decodeOptions = coderOptions; + } + + return image; +} + +UIImage * _Nullable SDImageLoaderDecodeProgressiveImageData(NSData * _Nonnull imageData, NSURL * _Nonnull imageURL, BOOL finished, id _Nonnull operation, SDWebImageOptions options, SDWebImageContext * _Nullable context) { + NSCParameterAssert(imageData); + NSCParameterAssert(imageURL); + NSCParameterAssert(operation); + + UIImage *image; + id cacheKeyFilter = context[SDWebImageContextCacheKeyFilter]; + NSString *cacheKey; + if (cacheKeyFilter) { + cacheKey = [cacheKeyFilter cacheKeyForURL:imageURL]; + } else { + cacheKey = imageURL.absoluteString; + } + SDImageCoderOptions *coderOptions = SDGetDecodeOptionsFromContext(context, options, cacheKey); + BOOL decodeFirstFrame = SD_OPTIONS_CONTAINS(options, SDWebImageDecodeFirstFrameOnly); + CGFloat scale = [coderOptions[SDImageCoderDecodeScaleFactor] doubleValue]; + + // Grab the progressive image coder + id progressiveCoder = SDImageLoaderGetProgressiveCoder(operation); + if (!progressiveCoder) { + id imageCoder = context[SDWebImageContextImageCoder]; + // Check the progressive coder if provided + if ([imageCoder respondsToSelector:@selector(initIncrementalWithOptions:)]) { + progressiveCoder = [[[imageCoder class] alloc] initIncrementalWithOptions:coderOptions]; + } else { + // We need to create a new instance for progressive decoding to avoid conflicts + for (id coder in [SDImageCodersManager sharedManager].coders.reverseObjectEnumerator) { + if ([coder conformsToProtocol:@protocol(SDProgressiveImageCoder)] && + [((id)coder) canIncrementalDecodeFromData:imageData]) { + progressiveCoder = [[[coder class] alloc] initIncrementalWithOptions:coderOptions]; + break; + } + } + } + SDImageLoaderSetProgressiveCoder(operation, progressiveCoder); + } + // If we can't find any progressive coder, disable progressive download + if (!progressiveCoder) { + return nil; + } + + [progressiveCoder updateIncrementalData:imageData finished:finished]; + if (!decodeFirstFrame) { + // check whether we should use `SDAnimatedImage` + Class animatedImageClass = context[SDWebImageContextAnimatedImageClass]; + if ([animatedImageClass isSubclassOfClass:[UIImage class]] && [animatedImageClass conformsToProtocol:@protocol(SDAnimatedImage)] && [progressiveCoder respondsToSelector:@selector(animatedImageFrameAtIndex:)]) { + image = [[animatedImageClass alloc] initWithAnimatedCoder:(id)progressiveCoder scale:scale]; + if (image) { + // Progressive decoding does not preload frames + } else { + // Check image class matching + if (options & SDWebImageMatchAnimatedImageClass) { + return nil; + } + } + } + } + if (!image) { + image = [progressiveCoder incrementalDecodedImageWithOptions:coderOptions]; + } + if (image) { + SDImageForceDecodePolicy policy = SDImageForceDecodePolicyAutomatic; + NSNumber *policyValue = context[SDWebImageContextImageForceDecodePolicy]; + if (policyValue != nil) { + policy = policyValue.unsignedIntegerValue; + } + // TODO: Deprecated, remove in SD 6.0... +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + if (SD_OPTIONS_CONTAINS(options, SDWebImageAvoidDecodeImage)) { + policy = SDImageForceDecodePolicyNever; + } +#pragma clang diagnostic pop + image = [SDImageCoderHelper decodedImageWithImage:image policy:policy]; + // assign the decode options, to let manager check whether to re-decode if needed + image.sd_decodeOptions = coderOptions; + // mark the image as progressive (completed one are not mark as progressive) + image.sd_isIncremental = !finished; + } + + return image; +} diff --git a/Pods/SDWebImage/SDWebImage/Core/SDImageLoadersManager.h b/Pods/SDWebImage/SDWebImage/Core/SDImageLoadersManager.h new file mode 100644 index 0000000..9886f45 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDImageLoadersManager.h @@ -0,0 +1,40 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDImageLoader.h" + +/** + A loaders manager to manage multiple loaders + */ +@interface SDImageLoadersManager : NSObject + +/** + Returns the global shared loaders manager instance. By default we will set [`SDWebImageDownloader.sharedDownloader`] into the loaders array. + */ +@property (nonatomic, class, readonly, nonnull) SDImageLoadersManager *sharedManager; + +/** + All image loaders in manager. The loaders array is a priority queue, which means the later added loader will have the highest priority + */ +@property (nonatomic, copy, nullable) NSArray>* loaders; + +/** + Add a new image loader to the end of loaders array. Which has the highest priority. + + @param loader loader + */ +- (void)addLoader:(nonnull id)loader; + +/** + Remove an image loader in the loaders array. + + @param loader loader + */ +- (void)removeLoader:(nonnull id)loader; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDImageLoadersManager.m b/Pods/SDWebImage/SDWebImage/Core/SDImageLoadersManager.m new file mode 100644 index 0000000..ac86c29 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDImageLoadersManager.m @@ -0,0 +1,123 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDImageLoadersManager.h" +#import "SDWebImageDownloader.h" +#import "SDInternalMacros.h" + +@interface SDImageLoadersManager () + +@property (nonatomic, strong, nonnull) NSMutableArray> *imageLoaders; + +@end + +@implementation SDImageLoadersManager { + SD_LOCK_DECLARE(_loadersLock); +} + ++ (SDImageLoadersManager *)sharedManager { + static dispatch_once_t onceToken; + static SDImageLoadersManager *manager; + dispatch_once(&onceToken, ^{ + manager = [[SDImageLoadersManager alloc] init]; + }); + return manager; +} + +- (instancetype)init { + self = [super init]; + if (self) { + // initialize with default image loaders + _imageLoaders = [NSMutableArray arrayWithObject:[SDWebImageDownloader sharedDownloader]]; + SD_LOCK_INIT(_loadersLock); + } + return self; +} + +- (NSArray> *)loaders { + SD_LOCK(_loadersLock); + NSArray>* loaders = [_imageLoaders copy]; + SD_UNLOCK(_loadersLock); + return loaders; +} + +- (void)setLoaders:(NSArray> *)loaders { + SD_LOCK(_loadersLock); + [_imageLoaders removeAllObjects]; + if (loaders.count) { + [_imageLoaders addObjectsFromArray:loaders]; + } + SD_UNLOCK(_loadersLock); +} + +#pragma mark - Loader Property + +- (void)addLoader:(id)loader { + if (![loader conformsToProtocol:@protocol(SDImageLoader)]) { + return; + } + SD_LOCK(_loadersLock); + [_imageLoaders addObject:loader]; + SD_UNLOCK(_loadersLock); +} + +- (void)removeLoader:(id)loader { + if (![loader conformsToProtocol:@protocol(SDImageLoader)]) { + return; + } + SD_LOCK(_loadersLock); + [_imageLoaders removeObject:loader]; + SD_UNLOCK(_loadersLock); +} + +#pragma mark - SDImageLoader + +- (BOOL)canRequestImageForURL:(nullable NSURL *)url { + return [self canRequestImageForURL:url options:0 context:nil]; +} + +- (BOOL)canRequestImageForURL:(NSURL *)url options:(SDWebImageOptions)options context:(SDWebImageContext *)context { + NSArray> *loaders = self.loaders; + for (id loader in loaders.reverseObjectEnumerator) { + if ([loader respondsToSelector:@selector(canRequestImageForURL:options:context:)]) { + if ([loader canRequestImageForURL:url options:options context:context]) { + return YES; + } + } else { + if ([loader canRequestImageForURL:url]) { + return YES; + } + } + } + return NO; +} + +- (id)requestImageWithURL:(NSURL *)url options:(SDWebImageOptions)options context:(SDWebImageContext *)context progress:(SDImageLoaderProgressBlock)progressBlock completed:(SDImageLoaderCompletedBlock)completedBlock { + if (!url) { + return nil; + } + NSArray> *loaders = self.loaders; + for (id loader in loaders.reverseObjectEnumerator) { + if ([loader canRequestImageForURL:url]) { + return [loader requestImageWithURL:url options:options context:context progress:progressBlock completed:completedBlock]; + } + } + return nil; +} + +- (BOOL)shouldBlockFailedURLWithURL:(NSURL *)url error:(NSError *)error { + NSArray> *loaders = self.loaders; + for (id loader in loaders.reverseObjectEnumerator) { + if ([loader canRequestImageForURL:url]) { + return [loader shouldBlockFailedURLWithURL:url error:error]; + } + } + return NO; +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDImageTransformer.h b/Pods/SDWebImage/SDWebImage/Core/SDImageTransformer.h new file mode 100644 index 0000000..640065c --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDImageTransformer.h @@ -0,0 +1,283 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" +#import "UIImage+Transform.h" + +/** + Return the transformed cache key which applied with specify transformerKey. + + @param key The original cache key + @param transformerKey The transformer key from the transformer + @return The transformed cache key + */ +FOUNDATION_EXPORT NSString * _Nullable SDTransformedKeyForKey(NSString * _Nullable key, NSString * _Nonnull transformerKey); + +/** + Return the thumbnailed cache key which applied with specify thumbnailSize and preserveAspectRatio control. + @param key The original cache key + @param thumbnailPixelSize The thumbnail pixel size + @param preserveAspectRatio The preserve aspect ratio option + @return The thumbnailed cache key + @note If you have both transformer and thumbnail applied for image, call `SDThumbnailedKeyForKey` firstly and then with `SDTransformedKeyForKey`.` + */ +FOUNDATION_EXPORT NSString * _Nullable SDThumbnailedKeyForKey(NSString * _Nullable key, CGSize thumbnailPixelSize, BOOL preserveAspectRatio); + +/** + A transformer protocol to transform the image load from cache or from download. + You can provide transformer to cache and manager (Through the `transformer` property or context option `SDWebImageContextImageTransformer`). + From v5.20, the transformer class also can be used on animated image frame post-transform logic, see `SDAnimatedImageView`. + + @note The transform process is called from a global queue in order to not to block the main queue. + */ +@protocol SDImageTransformer + +@optional + +/** + Defaults to YES if you don't implements this method. + We keep some metadata like Image Format (`sd_imageFormat`)/ Animated Loop Count (`sd_imageLoopCount`) via associated object on UIImage instance. + When transformer generate a new UIImage instance, in most cases you still want to keep these information. So this is what for during the image loading pipeline. + If the value is YES, we will keep and override the metadata **After you generate the UIImage** + If the value is NO, we will not touch the UIImage metadata and it's controlled by you during the generation. Read `UIImage+Medata.h` and pick the metadata you want for the new generated UIImage. + */ +@property (nonatomic, assign, readonly) BOOL preserveImageMetadata; + +@required +/** + For each transformer, it must contains its cache key to used to store the image cache or query from the cache. This key will be appened after the original cache key generated by URL or from user. + Which means, the cache should match what your transformer logic do. The same `input image` + `transformer key`, should always generate the same `output image`. + + @return The cache key to appended after the original cache key. Should not be nil. + */ +@property (nonatomic, copy, readonly, nonnull) NSString *transformerKey; + +/** + Transform the image to another image. + + @param image The image to be transformed + @param key The cache key associated to the image. This arg is a hint for image source, not always useful and should be nullable. In the future we will remove this arg. + @return The transformed image, or nil if transform failed + */ +- (nullable UIImage *)transformedImageWithImage:(nonnull UIImage *)image forKey:(nonnull NSString *)key API_DEPRECATED("The key arg will be removed in the future. Update your code and don't rely on that.", macos(10.10, API_TO_BE_DEPRECATED), ios(8.0, API_TO_BE_DEPRECATED), tvos(9.0, API_TO_BE_DEPRECATED), watchos(2.0, API_TO_BE_DEPRECATED)); + +@end + +#pragma mark - Pipeline + +/** + Pipeline transformer. Which you can bind multiple transformers together to let the image to be transformed one by one in order and generate the final image. + @note Because transformers are lightweight, if you want to append or arrange transformers, create another pipeline transformer instead. This class is considered as immutable. + */ +@interface SDImagePipelineTransformer : NSObject +/// For pipeline transformer, this property is readonly and always return NO. We handle each transformer's choice inside implementation +@property (nonatomic, assign, readonly) BOOL preserveImageMetadata; +/** + All transformers in pipeline + */ +@property (nonatomic, copy, readonly, nonnull) NSArray> *transformers; + +- (nonnull instancetype)init NS_UNAVAILABLE; ++ (nonnull instancetype)new NS_UNAVAILABLE; + ++ (nonnull instancetype)transformerWithTransformers:(nonnull NSArray> *)transformers; + +@end + +#pragma mark - Base +/// This is the base class for our built-in concrete transformers. You should not use this class directlly, use cconcrete subclass (like `SDImageRoundCornerTransformer`) instead. +@interface SDImageBaseTransformer : NSObject +/// For concrete transformer, this property is readwrite and defaults to YES. You can choose whether to preserve image metadata **After you generate the UIImage** +@property (nonatomic, assign, readwrite) BOOL preserveImageMetadata; +@end + +// There are some built-in transformers based on the `UIImage+Transformer` category to provide the common image geometry, image blending and image effect process. Those transform are useful for static image only but you can create your own to support animated image as well. +// Because transformers are lightweight, these class are considered as immutable. +#pragma mark - Image Geometry + +/** + Image round corner transformer + */ +@interface SDImageRoundCornerTransformer: SDImageBaseTransformer + +/** + The radius of each corner oval. Values larger than half the + rectangle's width or height are clamped appropriately to + half the width or height. + */ +@property (nonatomic, assign, readonly) CGFloat cornerRadius; + +/** + A bitmask value that identifies the corners that you want + rounded. You can use this parameter to round only a subset + of the corners of the rectangle. + */ +@property (nonatomic, assign, readonly) SDRectCorner corners; + +/** + The inset border line width. Values larger than half the rectangle's + width or height are clamped appropriately to half the width + or height. + */ +@property (nonatomic, assign, readonly) CGFloat borderWidth; + +/** + The border stroke color. nil means clear color. + */ +@property (nonatomic, strong, readonly, nullable) UIColor *borderColor; + +- (nonnull instancetype)init NS_UNAVAILABLE; ++ (nonnull instancetype)new NS_UNAVAILABLE; + ++ (nonnull instancetype)transformerWithRadius:(CGFloat)cornerRadius corners:(SDRectCorner)corners borderWidth:(CGFloat)borderWidth borderColor:(nullable UIColor *)borderColor; + +@end + +/** + Image resizing transformer + */ +@interface SDImageResizingTransformer : SDImageBaseTransformer + +/** + The new size to be resized, values should be positive. + */ +@property (nonatomic, assign, readonly) CGSize size; + +/** + The scale mode for image content. + */ +@property (nonatomic, assign, readonly) SDImageScaleMode scaleMode; + +- (nonnull instancetype)init NS_UNAVAILABLE; ++ (nonnull instancetype)new NS_UNAVAILABLE; + ++ (nonnull instancetype)transformerWithSize:(CGSize)size scaleMode:(SDImageScaleMode)scaleMode; + +@end + +/** + Image cropping transformer + */ +@interface SDImageCroppingTransformer : SDImageBaseTransformer + +/** + Image's inner rect. + */ +@property (nonatomic, assign, readonly) CGRect rect; + +- (nonnull instancetype)init NS_UNAVAILABLE; ++ (nonnull instancetype)new NS_UNAVAILABLE; + ++ (nonnull instancetype)transformerWithRect:(CGRect)rect; + +@end + +/** + Image flipping transformer + */ +@interface SDImageFlippingTransformer : SDImageBaseTransformer + +/** + YES to flip the image horizontally. ⇋ + */ +@property (nonatomic, assign, readonly) BOOL horizontal; + +/** + YES to flip the image vertically. ⥯ + */ +@property (nonatomic, assign, readonly) BOOL vertical; + +- (nonnull instancetype)init NS_UNAVAILABLE; ++ (nonnull instancetype)new NS_UNAVAILABLE; + ++ (nonnull instancetype)transformerWithHorizontal:(BOOL)horizontal vertical:(BOOL)vertical; + +@end + +/** + Image rotation transformer + */ +@interface SDImageRotationTransformer : SDImageBaseTransformer + +/** + Rotated radians in counterclockwise.⟲ + */ +@property (nonatomic, assign, readonly) CGFloat angle; + +/** + YES: new image's size is extend to fit all content. + NO: image's size will not change, content may be clipped. + */ +@property (nonatomic, assign, readonly) BOOL fitSize; + +- (nonnull instancetype)init NS_UNAVAILABLE; ++ (nonnull instancetype)new NS_UNAVAILABLE; + ++ (nonnull instancetype)transformerWithAngle:(CGFloat)angle fitSize:(BOOL)fitSize; + +@end + +#pragma mark - Image Blending + +/** + Image tint color transformer + */ +@interface SDImageTintTransformer : SDImageBaseTransformer + +/** + The tint color. + */ +@property (nonatomic, strong, readonly, nonnull) UIColor *tintColor; +/// The blend mode, defaults to `sourceIn` if you use the initializer without blend mode +@property (nonatomic, assign, readonly) CGBlendMode blendMode; + +- (nonnull instancetype)init NS_UNAVAILABLE; ++ (nonnull instancetype)new NS_UNAVAILABLE; + ++ (nonnull instancetype)transformerWithColor:(nonnull UIColor *)tintColor; ++ (nonnull instancetype)transformerWithColor:(nonnull UIColor *)tintColor blendMode:(CGBlendMode)blendMode; + +@end + +#pragma mark - Image Effect + +/** + Image blur effect transformer + */ +@interface SDImageBlurTransformer : SDImageBaseTransformer + +/** + The radius of the blur in points, 0 means no blur effect. + */ +@property (nonatomic, assign, readonly) CGFloat blurRadius; + +- (nonnull instancetype)init NS_UNAVAILABLE; ++ (nonnull instancetype)new NS_UNAVAILABLE; + ++ (nonnull instancetype)transformerWithRadius:(CGFloat)blurRadius; + +@end + +#if SD_UIKIT || SD_MAC +/** + Core Image filter transformer + */ +@interface SDImageFilterTransformer: SDImageBaseTransformer + +/** + The CIFilter to be applied to the image. + */ +@property (nonatomic, strong, readonly, nonnull) CIFilter *filter; + +- (nonnull instancetype)init NS_UNAVAILABLE; ++ (nonnull instancetype)new NS_UNAVAILABLE; + ++ (nonnull instancetype)transformerWithFilter:(nonnull CIFilter *)filter; + +@end +#endif diff --git a/Pods/SDWebImage/SDWebImage/Core/SDImageTransformer.m b/Pods/SDWebImage/SDWebImage/Core/SDImageTransformer.m new file mode 100644 index 0000000..883f634 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDImageTransformer.m @@ -0,0 +1,375 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDImageTransformer.h" +#import "UIColor+SDHexString.h" +#import "SDAssociatedObject.h" +#if SD_UIKIT || SD_MAC +#import +#endif + +// Separator for different transformerKey, for example, `image.png` |> flip(YES,NO) |> rotate(pi/4,YES) => 'image-SDImageFlippingTransformer(1,0)-SDImageRotationTransformer(0.78539816339,1).png' +static NSString * const SDImageTransformerKeySeparator = @"-"; + +NSString * _Nullable SDTransformedKeyForKey(NSString * _Nullable key, NSString * _Nonnull transformerKey) { + if (!key || !transformerKey) { + return nil; + } + // Find the file extension + NSURL *keyURL = [NSURL URLWithString:key]; + NSString *ext = keyURL ? keyURL.pathExtension : key.pathExtension; + if (ext.length > 0) { + // For non-file URL + if (keyURL && !keyURL.isFileURL) { + // keep anything except path (like URL query) + NSURLComponents *component = [NSURLComponents componentsWithURL:keyURL resolvingAgainstBaseURL:NO]; + component.path = [[[component.path.stringByDeletingPathExtension stringByAppendingString:SDImageTransformerKeySeparator] stringByAppendingString:transformerKey] stringByAppendingPathExtension:ext]; + return component.URL.absoluteString; + } else { + // file URL + return [[[key.stringByDeletingPathExtension stringByAppendingString:SDImageTransformerKeySeparator] stringByAppendingString:transformerKey] stringByAppendingPathExtension:ext]; + } + } else { + return [[key stringByAppendingString:SDImageTransformerKeySeparator] stringByAppendingString:transformerKey]; + } +} + +NSString * _Nullable SDThumbnailedKeyForKey(NSString * _Nullable key, CGSize thumbnailPixelSize, BOOL preserveAspectRatio) { + NSString *thumbnailKey = [NSString stringWithFormat:@"Thumbnail({%f,%f},%d)", thumbnailPixelSize.width, thumbnailPixelSize.height, preserveAspectRatio]; + return SDTransformedKeyForKey(key, thumbnailKey); +} + +@interface SDImagePipelineTransformer () + +@property (nonatomic, copy, readwrite, nonnull) NSArray> *transformers; +@property (nonatomic, copy, readwrite) NSString *transformerKey; + +@end + +@implementation SDImagePipelineTransformer + ++ (instancetype)transformerWithTransformers:(NSArray> *)transformers { + SDImagePipelineTransformer *transformer = [SDImagePipelineTransformer new]; + transformer.transformers = transformers; + transformer.transformerKey = [[self class] cacheKeyForTransformers:transformers]; + + return transformer; +} + ++ (NSString *)cacheKeyForTransformers:(NSArray> *)transformers { + if (transformers.count == 0) { + return @""; + } + NSMutableArray *cacheKeys = [NSMutableArray arrayWithCapacity:transformers.count]; + [transformers enumerateObjectsUsingBlock:^(id _Nonnull transformer, NSUInteger idx, BOOL * _Nonnull stop) { + NSString *cacheKey = transformer.transformerKey; + [cacheKeys addObject:cacheKey]; + }]; + + return [cacheKeys componentsJoinedByString:SDImageTransformerKeySeparator]; +} + +- (BOOL)preserveImageMetadata { + return NO; // We handle this logic inside `transformedImageWithImage` below +} + +- (UIImage *)transformedImageWithImage:(UIImage *)image forKey:(NSString *)key { + if (!image) { + return nil; + } + UIImage *transformedImage = image; + for (id transformer in self.transformers) { + UIImage *newImage = [transformer transformedImageWithImage:transformedImage forKey:key]; + // Handle each transformer's preserveImageMetadata choice + BOOL preserveImageMetadata = YES; + if ([transformer respondsToSelector:@selector(preserveImageMetadata)]) { + preserveImageMetadata = transformer.preserveImageMetadata; + } + if (preserveImageMetadata) { + SDImageCopyAssociatedObject(transformedImage, newImage); + } + transformedImage = newImage; + } + return transformedImage; +} + +@end + +@implementation SDImageBaseTransformer + +- (instancetype)init { + self = [super init]; + if (self) { + _preserveImageMetadata = YES; + } + return self; +} + +- (NSString *)transformerKey { + @throw [NSException exceptionWithName:NSInternalInconsistencyException + reason:[NSString stringWithFormat:@"For `SDImageBaseTransformer` subclass, you must override %@ method", NSStringFromSelector(_cmd)] + userInfo:nil]; +} + +- (nullable UIImage *)transformedImageWithImage:(nonnull UIImage *)image forKey:(nonnull NSString *)key { + @throw [NSException exceptionWithName:NSInternalInconsistencyException + reason:[NSString stringWithFormat:@"For `SDImageBaseTransformer` subclass, you must override %@ method", NSStringFromSelector(_cmd)] + userInfo:nil]; +} + +@end + +@interface SDImageRoundCornerTransformer () + +@property (nonatomic, assign) CGFloat cornerRadius; +@property (nonatomic, assign) SDRectCorner corners; +@property (nonatomic, assign) CGFloat borderWidth; +@property (nonatomic, strong, nullable) UIColor *borderColor; + +@end + +@implementation SDImageRoundCornerTransformer + ++ (instancetype)transformerWithRadius:(CGFloat)cornerRadius corners:(SDRectCorner)corners borderWidth:(CGFloat)borderWidth borderColor:(UIColor *)borderColor { + SDImageRoundCornerTransformer *transformer = [SDImageRoundCornerTransformer new]; + transformer.cornerRadius = cornerRadius; + transformer.corners = corners; + transformer.borderWidth = borderWidth; + transformer.borderColor = borderColor; + + return transformer; +} + +- (NSString *)transformerKey { + return [NSString stringWithFormat:@"SDImageRoundCornerTransformer(%f,%lu,%f,%@)", self.cornerRadius, (unsigned long)self.corners, self.borderWidth, self.borderColor.sd_hexString]; +} + +- (UIImage *)transformedImageWithImage:(UIImage *)image forKey:(NSString *)key { + if (!image) { + return nil; + } + return [image sd_roundedCornerImageWithRadius:self.cornerRadius corners:self.corners borderWidth:self.borderWidth borderColor:self.borderColor]; +} + +@end + +@interface SDImageResizingTransformer () + +@property (nonatomic, assign) CGSize size; +@property (nonatomic, assign) SDImageScaleMode scaleMode; + +@end + +@implementation SDImageResizingTransformer + ++ (instancetype)transformerWithSize:(CGSize)size scaleMode:(SDImageScaleMode)scaleMode { + SDImageResizingTransformer *transformer = [SDImageResizingTransformer new]; + transformer.size = size; + transformer.scaleMode = scaleMode; + + return transformer; +} + +- (NSString *)transformerKey { + CGSize size = self.size; + return [NSString stringWithFormat:@"SDImageResizingTransformer({%f,%f},%lu)", size.width, size.height, (unsigned long)self.scaleMode]; +} + +- (UIImage *)transformedImageWithImage:(UIImage *)image forKey:(NSString *)key { + if (!image) { + return nil; + } + return [image sd_resizedImageWithSize:self.size scaleMode:self.scaleMode]; +} + +@end + +@interface SDImageCroppingTransformer () + +@property (nonatomic, assign) CGRect rect; + +@end + +@implementation SDImageCroppingTransformer + ++ (instancetype)transformerWithRect:(CGRect)rect { + SDImageCroppingTransformer *transformer = [SDImageCroppingTransformer new]; + transformer.rect = rect; + + return transformer; +} + +- (NSString *)transformerKey { + CGRect rect = self.rect; + return [NSString stringWithFormat:@"SDImageCroppingTransformer({%f,%f,%f,%f})", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height]; +} + +- (UIImage *)transformedImageWithImage:(UIImage *)image forKey:(NSString *)key { + if (!image) { + return nil; + } + return [image sd_croppedImageWithRect:self.rect]; +} + +@end + +@interface SDImageFlippingTransformer () + +@property (nonatomic, assign) BOOL horizontal; +@property (nonatomic, assign) BOOL vertical; + +@end + +@implementation SDImageFlippingTransformer + ++ (instancetype)transformerWithHorizontal:(BOOL)horizontal vertical:(BOOL)vertical { + SDImageFlippingTransformer *transformer = [SDImageFlippingTransformer new]; + transformer.horizontal = horizontal; + transformer.vertical = vertical; + + return transformer; +} + +- (NSString *)transformerKey { + return [NSString stringWithFormat:@"SDImageFlippingTransformer(%d,%d)", self.horizontal, self.vertical]; +} + +- (UIImage *)transformedImageWithImage:(UIImage *)image forKey:(NSString *)key { + if (!image) { + return nil; + } + return [image sd_flippedImageWithHorizontal:self.horizontal vertical:self.vertical]; +} + +@end + +@interface SDImageRotationTransformer () + +@property (nonatomic, assign) CGFloat angle; +@property (nonatomic, assign) BOOL fitSize; + +@end + +@implementation SDImageRotationTransformer + ++ (instancetype)transformerWithAngle:(CGFloat)angle fitSize:(BOOL)fitSize { + SDImageRotationTransformer *transformer = [SDImageRotationTransformer new]; + transformer.angle = angle; + transformer.fitSize = fitSize; + + return transformer; +} + +- (NSString *)transformerKey { + return [NSString stringWithFormat:@"SDImageRotationTransformer(%f,%d)", self.angle, self.fitSize]; +} + +- (UIImage *)transformedImageWithImage:(UIImage *)image forKey:(NSString *)key { + if (!image) { + return nil; + } + return [image sd_rotatedImageWithAngle:self.angle fitSize:self.fitSize]; +} + +@end + +#pragma mark - Image Blending + +@interface SDImageTintTransformer () + +@property (nonatomic, strong, nonnull) UIColor *tintColor; +@property (nonatomic, assign) CGBlendMode blendMode; + +@end + +@implementation SDImageTintTransformer + ++ (instancetype)transformerWithColor:(UIColor *)tintColor { + return [self transformerWithColor:tintColor blendMode:kCGBlendModeSourceIn]; +} + ++ (instancetype)transformerWithColor:(UIColor *)tintColor blendMode:(CGBlendMode)blendMode { + SDImageTintTransformer *transformer = [SDImageTintTransformer new]; + transformer.tintColor = tintColor; + transformer.blendMode = blendMode; + + return transformer; +} + +- (NSString *)transformerKey { + return [NSString stringWithFormat:@"SDImageTintTransformer(%@,%d)", self.tintColor.sd_hexString, self.blendMode]; +} + +- (UIImage *)transformedImageWithImage:(UIImage *)image forKey:(NSString *)key { + if (!image) { + return nil; + } + return [image sd_tintedImageWithColor:self.tintColor]; +} + +@end + +#pragma mark - Image Effect + +@interface SDImageBlurTransformer () + +@property (nonatomic, assign) CGFloat blurRadius; + +@end + +@implementation SDImageBlurTransformer + ++ (instancetype)transformerWithRadius:(CGFloat)blurRadius { + SDImageBlurTransformer *transformer = [SDImageBlurTransformer new]; + transformer.blurRadius = blurRadius; + + return transformer; +} + +- (NSString *)transformerKey { + return [NSString stringWithFormat:@"SDImageBlurTransformer(%f)", self.blurRadius]; +} + +- (UIImage *)transformedImageWithImage:(UIImage *)image forKey:(NSString *)key { + if (!image) { + return nil; + } + return [image sd_blurredImageWithRadius:self.blurRadius]; +} + +@end + +#if SD_UIKIT || SD_MAC +@interface SDImageFilterTransformer () + +@property (nonatomic, strong, nonnull) CIFilter *filter; + +@end + +@implementation SDImageFilterTransformer + ++ (instancetype)transformerWithFilter:(CIFilter *)filter { + SDImageFilterTransformer *transformer = [SDImageFilterTransformer new]; + transformer.filter = filter; + + return transformer; +} + +- (NSString *)transformerKey { + return [NSString stringWithFormat:@"SDImageFilterTransformer(%@)", self.filter.name]; +} + +- (UIImage *)transformedImageWithImage:(UIImage *)image forKey:(NSString *)key { + if (!image) { + return nil; + } + return [image sd_filteredImageWithFilter:self.filter]; +} + +@end +#endif diff --git a/Pods/SDWebImage/SDWebImage/Core/SDMemoryCache.h b/Pods/SDWebImage/SDWebImage/Core/SDMemoryCache.h new file mode 100644 index 0000000..43c39e8 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDMemoryCache.h @@ -0,0 +1,78 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +@class SDImageCacheConfig; +/** + A protocol to allow custom memory cache used in SDImageCache. + */ +@protocol SDMemoryCache + +@required + +/** + Create a new memory cache instance with the specify cache config. You can check `maxMemoryCost` and `maxMemoryCount` used for memory cache. + + @param config The cache config to be used to create the cache. + @return The new memory cache instance. + */ +- (nonnull instancetype)initWithConfig:(nonnull SDImageCacheConfig *)config; + +/** + Returns the value associated with a given key. + + @param key An object identifying the value. If nil, just return nil. + @return The value associated with key, or nil if no value is associated with key. + */ +- (nullable id)objectForKey:(nonnull id)key; + +/** + Sets the value of the specified key in the cache (0 cost). + + @param object The object to be stored in the cache. If nil, it calls `removeObjectForKey:`. + @param key The key with which to associate the value. If nil, this method has no effect. + @discussion Unlike an NSMutableDictionary object, a cache does not copy the key + objects that are put into it. + */ +- (void)setObject:(nullable id)object forKey:(nonnull id)key; + +/** + Sets the value of the specified key in the cache, and associates the key-value + pair with the specified cost. + + @param object The object to store in the cache. If nil, it calls `removeObjectForKey`. + @param key The key with which to associate the value. If nil, this method has no effect. + @param cost The cost with which to associate the key-value pair. + @discussion Unlike an NSMutableDictionary object, a cache does not copy the key + objects that are put into it. + */ +- (void)setObject:(nullable id)object forKey:(nonnull id)key cost:(NSUInteger)cost; + +/** + Removes the value of the specified key in the cache. + + @param key The key identifying the value to be removed. If nil, this method has no effect. + */ +- (void)removeObjectForKey:(nonnull id)key; + +/** + Empties the cache immediately. + */ +- (void)removeAllObjects; + +@end + +/** + A memory cache which auto purge the cache on memory warning and support weak cache. + */ +@interface SDMemoryCache : NSCache + +@property (nonatomic, strong, nonnull, readonly) SDImageCacheConfig *config; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDMemoryCache.m b/Pods/SDWebImage/SDWebImage/Core/SDMemoryCache.m new file mode 100644 index 0000000..7bcc385 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDMemoryCache.m @@ -0,0 +1,158 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDMemoryCache.h" +#import "SDImageCacheConfig.h" +#import "UIImage+MemoryCacheCost.h" +#import "SDInternalMacros.h" + +static void * SDMemoryCacheContext = &SDMemoryCacheContext; + +@interface SDMemoryCache () { +#if SD_UIKIT + SD_LOCK_DECLARE(_weakCacheLock); // a lock to keep the access to `weakCache` thread-safe +#endif +} + +@property (nonatomic, strong, nullable) SDImageCacheConfig *config; +#if SD_UIKIT +@property (nonatomic, strong, nonnull) NSMapTable *weakCache; // strong-weak cache +#endif +@end + +@implementation SDMemoryCache + +- (void)dealloc { + [_config removeObserver:self forKeyPath:NSStringFromSelector(@selector(maxMemoryCost)) context:SDMemoryCacheContext]; + [_config removeObserver:self forKeyPath:NSStringFromSelector(@selector(maxMemoryCount)) context:SDMemoryCacheContext]; +#if SD_UIKIT + [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; +#endif + self.delegate = nil; +} + +- (instancetype)init { + self = [super init]; + if (self) { + _config = [[SDImageCacheConfig alloc] init]; + [self commonInit]; + } + return self; +} + +- (instancetype)initWithConfig:(SDImageCacheConfig *)config { + self = [super init]; + if (self) { + _config = config; + [self commonInit]; + } + return self; +} + +- (void)commonInit { + SDImageCacheConfig *config = self.config; + self.totalCostLimit = config.maxMemoryCost; + self.countLimit = config.maxMemoryCount; + + [config addObserver:self forKeyPath:NSStringFromSelector(@selector(maxMemoryCost)) options:0 context:SDMemoryCacheContext]; + [config addObserver:self forKeyPath:NSStringFromSelector(@selector(maxMemoryCount)) options:0 context:SDMemoryCacheContext]; + +#if SD_UIKIT + self.weakCache = [[NSMapTable alloc] initWithKeyOptions:NSPointerFunctionsStrongMemory valueOptions:NSPointerFunctionsWeakMemory capacity:0]; + SD_LOCK_INIT(_weakCacheLock); + + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(didReceiveMemoryWarning:) + name:UIApplicationDidReceiveMemoryWarningNotification + object:nil]; +#endif +} + +// Current this seems no use on macOS (macOS use virtual memory and do not clear cache when memory warning). So we only override on iOS/tvOS platform. +#if SD_UIKIT +- (void)didReceiveMemoryWarning:(NSNotification *)notification { + // Only remove cache, but keep weak cache + [super removeAllObjects]; +} + +// `setObject:forKey:` just call this with 0 cost. Override this is enough +- (void)setObject:(id)obj forKey:(id)key cost:(NSUInteger)g { + [super setObject:obj forKey:key cost:g]; + if (!self.config.shouldUseWeakMemoryCache) { + return; + } + if (key && obj) { + // Store weak cache + SD_LOCK(_weakCacheLock); + [self.weakCache setObject:obj forKey:key]; + SD_UNLOCK(_weakCacheLock); + } +} + +- (id)objectForKey:(id)key { + id obj = [super objectForKey:key]; + if (!self.config.shouldUseWeakMemoryCache) { + return obj; + } + if (key && !obj) { + // Check weak cache + SD_LOCK(_weakCacheLock); + obj = [self.weakCache objectForKey:key]; + SD_UNLOCK(_weakCacheLock); + if (obj) { + // Sync cache + NSUInteger cost = 0; + if ([obj isKindOfClass:[UIImage class]]) { + cost = [(UIImage *)obj sd_memoryCost]; + } + [super setObject:obj forKey:key cost:cost]; + } + } + return obj; +} + +- (void)removeObjectForKey:(id)key { + [super removeObjectForKey:key]; + if (!self.config.shouldUseWeakMemoryCache) { + return; + } + if (key) { + // Remove weak cache + SD_LOCK(_weakCacheLock); + [self.weakCache removeObjectForKey:key]; + SD_UNLOCK(_weakCacheLock); + } +} + +- (void)removeAllObjects { + [super removeAllObjects]; + if (!self.config.shouldUseWeakMemoryCache) { + return; + } + // Manually remove should also remove weak cache + SD_LOCK(_weakCacheLock); + [self.weakCache removeAllObjects]; + SD_UNLOCK(_weakCacheLock); +} +#endif + +#pragma mark - KVO + +- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { + if (context == SDMemoryCacheContext) { + if ([keyPath isEqualToString:NSStringFromSelector(@selector(maxMemoryCost))]) { + self.totalCostLimit = self.config.maxMemoryCost; + } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(maxMemoryCount))]) { + self.countLimit = self.config.maxMemoryCount; + } + } else { + [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; + } +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDWebImageCacheKeyFilter.h b/Pods/SDWebImage/SDWebImage/Core/SDWebImageCacheKeyFilter.h new file mode 100644 index 0000000..7c569f3 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDWebImageCacheKeyFilter.h @@ -0,0 +1,35 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" + +typedef NSString * _Nullable(^SDWebImageCacheKeyFilterBlock)(NSURL * _Nonnull url); + +/** + This is the protocol for cache key filter. + We can use a block to specify the cache key filter. But Using protocol can make this extensible, and allow Swift user to use it easily instead of using `@convention(block)` to store a block into context options. + */ +@protocol SDWebImageCacheKeyFilter + +- (nullable NSString *)cacheKeyForURL:(nonnull NSURL *)url; + +@end + +/** + A cache key filter class with block. + */ +@interface SDWebImageCacheKeyFilter : NSObject + +- (nonnull instancetype)init NS_UNAVAILABLE; ++ (nonnull instancetype)new NS_UNAVAILABLE; + +- (nonnull instancetype)initWithBlock:(nonnull SDWebImageCacheKeyFilterBlock)block; ++ (nonnull instancetype)cacheKeyFilterWithBlock:(nonnull SDWebImageCacheKeyFilterBlock)block; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDWebImageCacheKeyFilter.m b/Pods/SDWebImage/SDWebImage/Core/SDWebImageCacheKeyFilter.m new file mode 100644 index 0000000..b4ebb8b --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDWebImageCacheKeyFilter.m @@ -0,0 +1,39 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCacheKeyFilter.h" + +@interface SDWebImageCacheKeyFilter () + +@property (nonatomic, copy, nonnull) SDWebImageCacheKeyFilterBlock block; + +@end + +@implementation SDWebImageCacheKeyFilter + +- (instancetype)initWithBlock:(SDWebImageCacheKeyFilterBlock)block { + self = [super init]; + if (self) { + self.block = block; + } + return self; +} + ++ (instancetype)cacheKeyFilterWithBlock:(SDWebImageCacheKeyFilterBlock)block { + SDWebImageCacheKeyFilter *cacheKeyFilter = [[SDWebImageCacheKeyFilter alloc] initWithBlock:block]; + return cacheKeyFilter; +} + +- (NSString *)cacheKeyForURL:(NSURL *)url { + if (!self.block) { + return nil; + } + return self.block(url); +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDWebImageCacheSerializer.h b/Pods/SDWebImage/SDWebImage/Core/SDWebImageCacheSerializer.h new file mode 100644 index 0000000..071931a --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDWebImageCacheSerializer.h @@ -0,0 +1,39 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" + +typedef NSData * _Nullable(^SDWebImageCacheSerializerBlock)(UIImage * _Nonnull image, NSData * _Nullable data, NSURL * _Nullable imageURL); + +/** + This is the protocol for cache serializer. + We can use a block to specify the cache serializer. But Using protocol can make this extensible, and allow Swift user to use it easily instead of using `@convention(block)` to store a block into context options. + */ +@protocol SDWebImageCacheSerializer + +/// Provide the image data associated to the image and store to disk cache +/// @param image The loaded image +/// @param data The original loaded image data. May be nil when image is transformed (UIImage.sd_isTransformed = YES) +/// @param imageURL The image URL +- (nullable NSData *)cacheDataWithImage:(nonnull UIImage *)image originalData:(nullable NSData *)data imageURL:(nullable NSURL *)imageURL; + +@end + +/** + A cache serializer class with block. + */ +@interface SDWebImageCacheSerializer : NSObject + +- (nonnull instancetype)initWithBlock:(nonnull SDWebImageCacheSerializerBlock)block; ++ (nonnull instancetype)cacheSerializerWithBlock:(nonnull SDWebImageCacheSerializerBlock)block; + +- (nonnull instancetype)init NS_UNAVAILABLE; ++ (nonnull instancetype)new NS_UNAVAILABLE; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDWebImageCacheSerializer.m b/Pods/SDWebImage/SDWebImage/Core/SDWebImageCacheSerializer.m new file mode 100644 index 0000000..51528e6 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDWebImageCacheSerializer.m @@ -0,0 +1,39 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCacheSerializer.h" + +@interface SDWebImageCacheSerializer () + +@property (nonatomic, copy, nonnull) SDWebImageCacheSerializerBlock block; + +@end + +@implementation SDWebImageCacheSerializer + +- (instancetype)initWithBlock:(SDWebImageCacheSerializerBlock)block { + self = [super init]; + if (self) { + self.block = block; + } + return self; +} + ++ (instancetype)cacheSerializerWithBlock:(SDWebImageCacheSerializerBlock)block { + SDWebImageCacheSerializer *cacheSerializer = [[SDWebImageCacheSerializer alloc] initWithBlock:block]; + return cacheSerializer; +} + +- (NSData *)cacheDataWithImage:(UIImage *)image originalData:(NSData *)data imageURL:(nullable NSURL *)imageURL { + if (!self.block) { + return nil; + } + return self.block(image, data, imageURL); +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDWebImageCompat.h b/Pods/SDWebImage/SDWebImage/Core/SDWebImageCompat.h new file mode 100644 index 0000000..9efc7a0 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDWebImageCompat.h @@ -0,0 +1,102 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * (c) Jamie Pinkham + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import + +#ifdef __OBJC_GC__ + #error SDWebImage does not support Objective-C Garbage Collection +#endif + +// Seems like TARGET_OS_MAC is always defined (on all platforms). +// To determine if we are running on macOS, use TARGET_OS_OSX in Xcode 8 +#if TARGET_OS_OSX + #define SD_MAC 1 +#else + #define SD_MAC 0 +#endif + +#if TARGET_OS_IOS + #define SD_IOS 1 +#else + #define SD_IOS 0 +#endif + +#if TARGET_OS_TV + #define SD_TV 1 +#else + #define SD_TV 0 +#endif + +#if TARGET_OS_WATCH + #define SD_WATCH 1 +#else + #define SD_WATCH 0 +#endif + +// Supports Xcode 14 to suppress warning +#ifdef TARGET_OS_VISION +#if TARGET_OS_VISION + #define SD_VISION 1 +#endif +#endif + +// iOS/tvOS/visionOS are very similar, UIKit exists on both platforms +// Note: watchOS also has UIKit, but it's very limited +#if SD_IOS || SD_TV || SD_VISION + #define SD_UIKIT 1 +#else + #define SD_UIKIT 0 +#endif + +#if SD_MAC + #import + #ifndef UIImage + #define UIImage NSImage + #endif + #ifndef UIImageView + #define UIImageView NSImageView + #endif + #ifndef UIView + #define UIView NSView + #endif + #ifndef UIColor + #define UIColor NSColor + #endif +#else + #if SD_UIKIT + #import + #endif + #if SD_WATCH + #import + #ifndef UIView + #define UIView WKInterfaceObject + #endif + #ifndef UIImageView + #define UIImageView WKInterfaceImage + #endif + #endif +#endif + +#ifndef NS_ENUM +#define NS_ENUM(_type, _name) enum _name : _type _name; enum _name : _type +#endif + +#ifndef NS_OPTIONS +#define NS_OPTIONS(_type, _name) enum _name : _type _name; enum _name : _type +#endif + +#ifndef dispatch_main_async_safe +#define dispatch_main_async_safe(block)\ + if (dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL) == dispatch_queue_get_label(dispatch_get_main_queue())) {\ + block();\ + } else {\ + dispatch_async(dispatch_get_main_queue(), block);\ + } +#pragma clang deprecated(dispatch_main_async_safe, "Use SDCallbackQueue instead") +#endif diff --git a/Pods/SDWebImage/SDWebImage/Core/SDWebImageCompat.m b/Pods/SDWebImage/SDWebImage/Core/SDWebImageCompat.m new file mode 100644 index 0000000..1297401 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDWebImageCompat.m @@ -0,0 +1,17 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +#if !__has_feature(objc_arc) + #error SDWebImage is ARC only. Either turn on ARC for the project or use -fobjc-arc flag +#endif + +#if !OS_OBJECT_USE_OBJC + #error SDWebImage need ARC for dispatch object +#endif diff --git a/Pods/SDWebImage/SDWebImage/Core/SDWebImageDefine.h b/Pods/SDWebImage/SDWebImage/Core/SDWebImageDefine.h new file mode 100644 index 0000000..c1c69d7 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDWebImageDefine.h @@ -0,0 +1,420 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +typedef void(^SDWebImageNoParamsBlock)(void); +/// Image Loading context option +typedef NSString * SDWebImageContextOption NS_EXTENSIBLE_STRING_ENUM; +typedef NSDictionary SDWebImageContext; +typedef NSMutableDictionary SDWebImageMutableContext; + +#pragma mark - Image scale + +/** + Return the image scale factor for the specify key, supports file name and url key. + This is the built-in way to check the scale factor when we have no context about it. Because scale factor is not stored in image data (It's typically from filename). + However, you can also provide custom scale factor as well, see `SDWebImageContextImageScaleFactor`. + + @param key The image cache key + @return The scale factor for image + */ +FOUNDATION_EXPORT CGFloat SDImageScaleFactorForKey(NSString * _Nullable key); + +/** + Scale the image with the scale factor for the specify key. If no need to scale, return the original image. + This works for `UIImage`(UIKit) or `NSImage`(AppKit). And this function also preserve the associated value in `UIImage+Metadata.h`. + @note This is actually a convenience function, which firstly call `SDImageScaleFactorForKey` and then call `SDScaledImageForScaleFactor`, kept for backward compatibility. + + @param key The image cache key + @param image The image + @return The scaled image + */ +FOUNDATION_EXPORT UIImage * _Nullable SDScaledImageForKey(NSString * _Nullable key, UIImage * _Nullable image); + +/** + Scale the image with the scale factor. If no need to scale, return the original image. + This works for `UIImage`(UIKit) or `NSImage`(AppKit). And this function also preserve the associated value in `UIImage+Metadata.h`. + + @param scale The image scale factor + @param image The image + @return The scaled image + */ +FOUNDATION_EXPORT UIImage * _Nullable SDScaledImageForScaleFactor(CGFloat scale, UIImage * _Nullable image); + +#pragma mark - WebCache Options + +/// WebCache options +typedef NS_OPTIONS(NSUInteger, SDWebImageOptions) { + /** + * By default, when a URL fail to be downloaded, the URL is blacklisted so the library won't keep trying. + * This flag disable this blacklisting. + */ + SDWebImageRetryFailed = 1 << 0, + + /** + * By default, image downloads are started during UI interactions, this flags disable this feature, + * leading to delayed download on UIScrollView deceleration for instance. + */ + SDWebImageLowPriority = 1 << 1, + + /** + * This flag enables progressive download, the image is displayed progressively during download as a browser would do. + * By default, the image is only displayed once completely downloaded. + */ + SDWebImageProgressiveLoad = 1 << 2, + + /** + * Even if the image is cached, respect the HTTP response cache control, and refresh the image from remote location if needed. + * The disk caching will be handled by NSURLCache instead of SDWebImage leading to slight performance degradation. + * This option helps deal with images changing behind the same request URL, e.g. Facebook graph api profile pics. + * If a cached image is refreshed, the completion block is called once with the cached image and again with the final image. + * + * Use this flag only if you can't make your URLs static with embedded cache busting parameter. + */ + SDWebImageRefreshCached = 1 << 3, + + /** + * In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for + * extra time in background to let the request finish. If the background task expires the operation will be cancelled. + */ + SDWebImageContinueInBackground = 1 << 4, + + /** + * Handles cookies stored in NSHTTPCookieStore by setting + * NSMutableURLRequest.HTTPShouldHandleCookies = YES; + */ + SDWebImageHandleCookies = 1 << 5, + + /** + * Enable to allow untrusted SSL certificates. + * Useful for testing purposes. Use with caution in production. + */ + SDWebImageAllowInvalidSSLCertificates = 1 << 6, + + /** + * By default, images are loaded in the order in which they were queued. This flag moves them to + * the front of the queue. + */ + SDWebImageHighPriority = 1 << 7, + + /** + * By default, placeholder images are loaded while the image is loading. This flag will delay the loading + * of the placeholder image until after the image has finished loading. + * @note This is used to treate placeholder as an **Error Placeholder** but not **Loading Placeholder** by defaults. if the image loading is cancelled or error, the placeholder will be always set. + * @note Therefore, if you want both **Error Placeholder** and **Loading Placeholder** exist, use `SDWebImageAvoidAutoSetImage` to manually set the two placeholders and final loaded image by your hand depends on loading result. + * @note This options is UI level options, has no usage on ImageManager or other components. + */ + SDWebImageDelayPlaceholder = 1 << 8, + + /** + * We usually don't apply transform on animated images as most transformers could not manage animated images. + * Use this flag to transform them anyway. + */ + SDWebImageTransformAnimatedImage = 1 << 9, + + /** + * By default, image is added to the imageView after download. But in some cases, we want to + * have the hand before setting the image (apply a filter or add it with cross-fade animation for instance) + * Use this flag if you want to manually set the image in the completion when success + * @note This options is UI level options, has no usage on ImageManager or other components. + */ + SDWebImageAvoidAutoSetImage = 1 << 10, + + /** + * By default, images are decoded respecting their original size. + * This flag will scale down the images to a size compatible with the constrained memory of devices. + * To control the limit memory bytes, check `SDImageCoderHelper.defaultScaleDownLimitBytes` (Defaults to 60MB on iOS) + * (from 5.16.0) This will actually translate to use context option `SDWebImageContextImageScaleDownLimitBytes`, which check and calculate the thumbnail pixel size occupied small than limit bytes (including animated image) + * (from 5.5.0) This flags effect the progressive and animated images as well + * @note If you need detail controls, it's better to use context option `imageScaleDownBytes` instead. + * @warning This does not effect the cache key. So which means, this will effect the global cache even next time you query without this option. Pay attention when you use this on global options (It's always recommended to use request-level option for different pipeline) + */ + SDWebImageScaleDownLargeImages = 1 << 11, + + /** + * By default, we do not query image data when the image is already cached in memory. This mask can force to query image data at the same time. However, this query is asynchronously unless you specify `SDWebImageQueryMemoryDataSync` + */ + SDWebImageQueryMemoryData = 1 << 12, + + /** + * By default, when you only specify `SDWebImageQueryMemoryData`, we query the memory image data asynchronously. Combined this mask as well to query the memory image data synchronously. + * @note Query data synchronously is not recommend, unless you want to ensure the image is loaded in the same runloop to avoid flashing during cell reusing. + */ + SDWebImageQueryMemoryDataSync = 1 << 13, + + /** + * By default, when the memory cache miss, we query the disk cache asynchronously. This mask can force to query disk cache (when memory cache miss) synchronously. + * @note These 3 query options can be combined together. For the full list about these masks combination, see wiki page. + * @note Query data synchronously is not recommend, unless you want to ensure the image is loaded in the same runloop to avoid flashing during cell reusing. + */ + SDWebImageQueryDiskDataSync = 1 << 14, + + /** + * By default, when the cache missed, the image is load from the loader. This flag can prevent this to load from cache only. + */ + SDWebImageFromCacheOnly = 1 << 15, + + /** + * By default, we query the cache before the image is load from the loader. This flag can prevent this to load from loader only. + */ + SDWebImageFromLoaderOnly = 1 << 16, + + /** + * By default, when you use `SDWebImageTransition` to do some view transition after the image load finished, this transition is only applied for image when the callback from manager is asynchronous (from network, or disk cache query) + * This mask can force to apply view transition for any cases, like memory cache query, or sync disk cache query. + * @note This options is UI level options, has no usage on ImageManager or other components. + */ + SDWebImageForceTransition = 1 << 17, + + /** + * By default, we will decode the image in the background during cache query and download from the network. This can help to improve performance because when rendering image on the screen, it need to be firstly decoded. But this happen on the main queue by Core Animation. + * However, this process may increase the memory usage as well. If you are experiencing an issue due to excessive memory consumption, This flag can prevent decode the image. + * @note 5.14.0 introduce `SDImageCoderDecodeUseLazyDecoding`, use that for better control from codec, instead of post-processing. Which acts the similar like this option but works for SDAnimatedImage as well (this one does not) + * @deprecated Deprecated in v5.17.0, if you don't want force-decode, pass [.imageForceDecodePolicy] = SDImageForceDecodePolicy.never.rawValue in context option + */ + SDWebImageAvoidDecodeImage API_DEPRECATED("Use SDWebImageContextImageForceDecodePolicy instead", macos(10.10, 10.10), ios(8.0, 8.0), tvos(9.0, 9.0), watchos(2.0, 2.0)) = 1 << 18, + + /** + * By default, we decode the animated image. This flag can force decode the first frame only and produce the static image. + */ + SDWebImageDecodeFirstFrameOnly = 1 << 19, + + /** + * By default, for `SDAnimatedImage`, we decode the animated image frame during rendering to reduce memory usage. However, you can specify to preload all frames into memory to reduce CPU usage when the animated image is shared by lots of imageViews. + * This will actually trigger `preloadAllAnimatedImageFrames` in the background queue(Disk Cache & Download only). + */ + SDWebImagePreloadAllFrames = 1 << 20, + + /** + * By default, when you use `SDWebImageContextAnimatedImageClass` context option (like using `SDAnimatedImageView` which designed to use `SDAnimatedImage`), we may still use `UIImage` when the memory cache hit, or image decoder is not available to produce one exactlly matching your custom class as a fallback solution. + * Using this option, can ensure we always callback image with your provided class. If failed to produce one, a error with code `SDWebImageErrorBadImageData` will been used. + * Note this options is not compatible with `SDWebImageDecodeFirstFrameOnly`, which always produce a UIImage/NSImage. + */ + SDWebImageMatchAnimatedImageClass = 1 << 21, + + /** + * By default, when we load the image from network, the image will be written to the cache (memory and disk, controlled by your `storeCacheType` context option) + * This maybe an asynchronously operation and the final `SDInternalCompletionBlock` callback does not guarantee the disk cache written is finished and may cause logic error. (For example, you modify the disk data just in completion block, however, the disk cache is not ready) + * If you need to process with the disk cache in the completion block, you should use this option to ensure the disk cache already been written when callback. + * Note if you use this when using the custom cache serializer, or using the transformer, we will also wait until the output image data written is finished. + */ + SDWebImageWaitStoreCache = 1 << 22, + + /** + * We usually don't apply transform on vector images, because vector images supports dynamically changing to any size, rasterize to a fixed size will loss details. To modify vector images, you can process the vector data at runtime (such as modifying PDF tag / SVG element). + * Use this flag to transform them anyway. + */ + SDWebImageTransformVectorImage = 1 << 23, + + /** + * By defaults, when you use UI-level category like `sd_setImageWithURL:` on UIImageView, it will cancel the loading image requests. + * However, some users may choose to not cancel the loading image requests and always start new pipeline. + * Use this flag to disable automatic cancel behavior. + * @note This options is UI level options, has no usage on ImageManager or other components. + */ + SDWebImageAvoidAutoCancelImage = 1 << 24, + + /** + * By defaults, for `SDWebImageTransition`, we just submit to UI transition and inmeediatelly callback the final `completedBlock` (`SDExternalCompletionBlock/SDInternalCompletionBlock`). + * This may cause un-wanted behavior if you do another transition inside `completedBlock`, because the previous transition is still runnning and un-cancellable, which mass-up the UI status. + * For this case, you can pass this option, we will delay the final callback, until your transition end. So when you inside `completedBlock`, no any transition is running on image view and safe to submit new transition. + * @note Currently we do not support `pausable/cancellable` transition. But possible in the future by using the https://developer.apple.com/documentation/uikit/uiviewpropertyanimator. + * @note If you have complicated transition animation, just use `SDWebImageManager` and do UI state management by yourself, do not use the top-level API (`sd_setImageWithURL:`) + */ + SDWebImageWaitTransition = 1 << 25, +}; + + +#pragma mark - Manager Context Options + +/** + A String to be used as the operation key for view category to store the image load operation. This is used for view instance which supports different image loading process. If nil, will use the class name as operation key. (NSString *) + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextSetImageOperationKey; + +/** + A SDWebImageManager instance to control the image download and cache process using in UIImageView+WebCache category and likes. If not provided, use the shared manager (SDWebImageManager *) + @deprecated Deprecated in the future. This context options can be replaced by other context option control like `.imageCache`, `.imageLoader`, `.imageTransformer` (See below), which already matches all the properties in SDWebImageManager. + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextCustomManager API_DEPRECATED("Use individual context option like .imageCache, .imageLoader and .imageTransformer instead", macos(10.10, API_TO_BE_DEPRECATED), ios(8.0, API_TO_BE_DEPRECATED), tvos(9.0, API_TO_BE_DEPRECATED), watchos(2.0, API_TO_BE_DEPRECATED)); + +/** + A `SDCallbackQueue` instance which controls the `Cache`/`Manager`/`Loader`'s callback queue for their completionBlock. + This is useful for user who call these 3 components in non-main queue and want to avoid callback in main queue. + @note For UI callback (`sd_setImageWithURL`), we will still use main queue to dispatch, means if you specify a global queue, it will enqueue from the global queue to main queue. + @note This does not effect the components' working queue (for example, `Cache` still query disk on internal ioQueue, `Loader` still do network on URLSessionConfiguration.delegateQueue), change those config if you need. + Defaults to nil. Which means main queue. + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextCallbackQueue; + +/** + A id instance which conforms to `SDImageCache` protocol. It's used to override the image manager's cache during the image loading pipeline. + In other word, if you just want to specify a custom cache during image loading, you don't need to re-create a dummy SDWebImageManager instance with the cache. If not provided, use the image manager's cache (id) + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextImageCache; + +/** + A id instance which conforms to `SDImageLoader` protocol. It's used to override the image manager's loader during the image loading pipeline. + In other word, if you just want to specify a custom loader during image loading, you don't need to re-create a dummy SDWebImageManager instance with the loader. If not provided, use the image manager's cache (id) +*/ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextImageLoader; + +/** + A id instance which conforms to `SDImageCoder` protocol. It's used to override the default image coder for image decoding(including progressive) and encoding during the image loading process. + If you use this context option, we will not always use `SDImageCodersManager.shared` to loop through all registered coders and find the suitable one. Instead, we will arbitrarily use the exact provided coder without extra checking (We may not call `canDecodeFromData:`). + @note This is only useful for cases which you can ensure the loading url matches your coder, or you find it's too hard to write a common coder which can used for generic usage. This will bind the loading url with the coder logic, which is not always a good design, but possible. (id) +*/ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextImageCoder; + +/** + A id instance which conforms `SDImageTransformer` protocol. It's used for image transform after the image load finished and store the transformed image to cache. If you provide one, it will ignore the `transformer` in manager and use provided one instead. If you pass NSNull, the transformer feature will be disabled. (id) + @note When this value is used, we will trigger image transform after downloaded, and the callback's data **will be nil** (because this time the data saved to disk does not match the image return to you. If you need full size data, query the cache with full size url key) + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextImageTransformer; + +#pragma mark - Force Decode Options + +/** + A NSNumber instance which store the`SDImageForceDecodePolicy` enum. This is used to control how current image loading should force-decode the decoded image (CGImage, typically). See more what's force-decode means in `SDImageForceDecodePolicy` comment. + Defaults to `SDImageForceDecodePolicyAutomatic`, which will detect the input CGImage's metadata, and only force-decode if the input CGImage can not directly render on screen (need extra CoreAnimation Copied Image and increase RAM usage). + @note If you want to always the force-decode for this image request, pass `SDImageForceDecodePolicyAlways`, for example, some WebP images which does not created by ImageIO. + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextImageForceDecodePolicy; + +#pragma mark - Image Decoder Context Options + +/** + A Dictionary (SDImageCoderOptions) value, which pass the extra decoding options to the SDImageCoder. Introduced in SDWebImage 5.14.0 + You can pass additional decoding related options to the decoder, extensible and control by you. And pay attention this dictionary may be retained by decoded image via `UIImage.sd_decodeOptions` + This context option replace the deprecated `SDImageCoderWebImageContext`, which may cause retain cycle (cache -> image -> options -> context -> cache) + @note There are already individual options below like `.imageScaleFactor`, `.imagePreserveAspectRatio`, each of individual options will override the same filed for this dictionary. + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextImageDecodeOptions; + +/** + A CGFloat raw value which specify the image scale factor. The number should be greater than or equal to 1.0. If not provide or the number is invalid, we will use the cache key to specify the scale factor. (NSNumber) + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextImageScaleFactor; + +/** + A Boolean value indicating whether to keep the original aspect ratio when generating thumbnail images (or bitmap images from vector format). + Defaults to YES. (NSNumber) + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextImagePreserveAspectRatio; + +/** + A CGSize raw value indicating whether or not to generate the thumbnail images (or bitmap images from vector format). When this value is provided, the decoder will generate a thumbnail image which pixel size is smaller than or equal to (depends the `.imagePreserveAspectRatio`) the value size. + @note When you pass `.preserveAspectRatio == NO`, the thumbnail image is stretched to match each dimension. When `.preserveAspectRatio == YES`, the thumbnail image's width is limited to pixel size's width, the thumbnail image's height is limited to pixel size's height. For common cases, you can just pass a square size to limit both. + Defaults to CGSizeZero, which means no thumbnail generation at all. (NSValue) + @note When this value is used, we will trigger thumbnail decoding for url, and the callback's data **will be nil** (because this time the data saved to disk does not match the image return to you. If you need full size data, query the cache with full size url key) + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextImageThumbnailPixelSize; + +/** + A NSString value (UTI) indicating the source image's file extension. Example: "public.jpeg-2000", "com.nikon.raw-image", "public.tiff" + Some image file format share the same data structure but has different tag explanation, like TIFF and NEF/SRW, see https://en.wikipedia.org/wiki/TIFF + Changing the file extension cause the different image result. The coder (like ImageIO) may use file extension to choose the correct parser + @note If you don't provide this option, we will use the `URL.path` as file extension to calculate the UTI hint + @note If you really don't want any hint which effect the image result, pass `NSNull.null` instead + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextImageTypeIdentifierHint; + +/** + A NSUInteger value to provide the limit bytes during decoding. This can help to avoid OOM on large frame count animated image or large pixel static image when you don't know how much RAM it occupied before decoding + The decoder will do these logic based on limit bytes: + 1. Get the total frame count (static image means 1) + 2. Calculate the `framePixelSize` width/height to `sqrt(limitBytes / frameCount / bytesPerPixel)`, keeping aspect ratio (at least 1x1) + 3. If the `framePixelSize < originalImagePixelSize`, then do thumbnail decoding (see `SDImageCoderDecodeThumbnailPixelSize`) use the `framePixelSize` and `preseveAspectRatio = YES` + 4. Else, use the full pixel decoding (small than limit bytes) + 5. Whatever result, this does not effect the animated/static behavior of image. So even if you set `limitBytes = 1 && frameCount = 100`, we will stll create animated image with each frame `1x1` pixel size. + @note This option has higher priority than `.imageThumbnailPixelSize` + @warning This does not effect the cache key. So which means, this will effect the global cache even next time you query without this option. Pay attention when you use this on global options (It's always recommended to use request-level option for different pipeline) + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextImageScaleDownLimitBytes; + +/** + A Boolean value (NSNumber) to provide converting to HDR during decoding. Currently if number is 0, use SDR, else use HDR. But we may extend this option to use `NSUInteger` in the future (means, think this options as int number, but not actual boolean) + @note Supported by iOS 17 and above when using ImageIO coder (third-party coder can support lower firmware) + Defaults to @(NO), decoder will automatically convert SDR. + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextImageDecodeToHDR; + +#pragma mark - Cache Context Options + +/** + A Dictionary (SDImageCoderOptions) value, which pass the extra encode options to the SDImageCoder. Introduced in SDWebImage 5.15.0 + You can pass encode options like `compressionQuality`, `maxFileSize`, `maxPixelSize` to control the encoding related thing, this is used inside `SDImageCache` during store logic. + @note For developer who use custom cache protocol (not SDImageCache instance), they need to upgrade and use these options for encoding. + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextImageEncodeOptions; + +/** + A SDImageCacheType raw value which specify the source of cache to query. Specify `SDImageCacheTypeDisk` to query from disk cache only; `SDImageCacheTypeMemory` to query from memory only. And `SDImageCacheTypeAll` to query from both memory cache and disk cache. Specify `SDImageCacheTypeNone` is invalid and totally ignore the cache query. + If not provide or the value is invalid, we will use `SDImageCacheTypeAll`. (NSNumber) + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextQueryCacheType; + +/** + A SDImageCacheType raw value which specify the store cache type when the image has just been downloaded and will be stored to the cache. Specify `SDImageCacheTypeNone` to disable cache storage; `SDImageCacheTypeDisk` to store in disk cache only; `SDImageCacheTypeMemory` to store in memory only. And `SDImageCacheTypeAll` to store in both memory cache and disk cache. + If you use image transformer feature, this actually apply for the transformed image, but not the original image itself. Use `SDWebImageContextOriginalStoreCacheType` if you want to control the original image's store cache type at the same time. + If not provide or the value is invalid, we will use `SDImageCacheTypeAll`. (NSNumber) + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextStoreCacheType; + +/** + The same behavior like `SDWebImageContextQueryCacheType`, but control the query cache type for the original image when you use image transformer feature. This allows the detail control of cache query for these two images. For example, if you want to query the transformed image from both memory/disk cache, query the original image from disk cache only, use `[.queryCacheType : .all, .originalQueryCacheType : .disk]` + If not provide or the value is invalid, we will use `SDImageCacheTypeDisk`, which query the original full image data from disk cache after transformed image cache miss. This is suitable for most common cases to avoid re-downloading the full data for different transform variants. (NSNumber) + @note Which means, if you set this value to not be `.none`, we will query the original image from cache, then do transform with transformer, instead of actual downloading, which can save bandwidth usage. + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextOriginalQueryCacheType; + +/** + The same behavior like `SDWebImageContextStoreCacheType`, but control the store cache type for the original image when you use image transformer feature. This allows the detail control of cache storage for these two images. For example, if you want to store the transformed image into both memory/disk cache, store the original image into disk cache only, use `[.storeCacheType : .all, .originalStoreCacheType : .disk]` + If not provide or the value is invalid, we will use `SDImageCacheTypeDisk`, which store the original full image data into disk cache after storing the transformed image. This is suitable for most common cases to avoid re-downloading the full data for different transform variants. (NSNumber) + @note This only store the original image, if you want to use the original image without downloading in next query, specify `SDWebImageContextOriginalQueryCacheType` as well. + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextOriginalStoreCacheType; + +/** + A id instance which conforms to `SDImageCache` protocol. It's used to control the cache for original image when using the transformer. If you provide one, the original image (full size image) will query and write from that cache instance instead, the transformed image will query and write from the default `SDWebImageContextImageCache` instead. (id) + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextOriginalImageCache; + +/** + A Class object which the instance is a `UIImage/NSImage` subclass and adopt `SDAnimatedImage` protocol. We will call `initWithData:scale:options:` to create the instance (or `initWithAnimatedCoder:scale:` when using progressive download) . If the instance create failed, fallback to normal `UIImage/NSImage`. + This can be used to improve animated images rendering performance (especially memory usage on big animated images) with `SDAnimatedImageView` (Class). + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextAnimatedImageClass; + +#pragma mark - Download Context Options + +/** + A id instance to modify the image download request. It's used for downloader to modify the original request from URL and options. If you provide one, it will ignore the `requestModifier` in downloader and use provided one instead. (id) + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextDownloadRequestModifier; + +/** + A id instance to modify the image download response. It's used for downloader to modify the original response from URL and options. If you provide one, it will ignore the `responseModifier` in downloader and use provided one instead. (id) + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextDownloadResponseModifier; + +/** + A id instance to decrypt the image download data. This can be used for image data decryption, such as Base64 encoded image. If you provide one, it will ignore the `decryptor` in downloader and use provided one instead. (id) + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextDownloadDecryptor; + +/** + A id instance to convert an URL into a cache key. It's used when manager need cache key to use image cache. If you provide one, it will ignore the `cacheKeyFilter` in manager and use provided one instead. (id) + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextCacheKeyFilter; + +/** + A id instance to convert the decoded image, the source downloaded data, to the actual data. It's used for manager to store image to the disk cache. If you provide one, it will ignore the `cacheSerializer` in manager and use provided one instead. (id) + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextCacheSerializer; diff --git a/Pods/SDWebImage/SDWebImage/Core/SDWebImageDefine.m b/Pods/SDWebImage/SDWebImage/Core/SDWebImageDefine.m new file mode 100644 index 0000000..b6b5034 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDWebImageDefine.m @@ -0,0 +1,163 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageDefine.h" +#import "UIImage+Metadata.h" +#import "NSImage+Compatibility.h" +#import "SDAnimatedImage.h" +#import "SDAssociatedObject.h" + +#pragma mark - Image scale + +static inline NSArray * _Nonnull SDImageScaleFactors(void) { + return @[@2, @3]; +} + +inline CGFloat SDImageScaleFactorForKey(NSString * _Nullable key) { + CGFloat scale = 1; + if (!key) { + return scale; + } + // Now all OS supports retina display scale system + { + // a@2x.png -> 8 + if (key.length >= 8) { + // Fast check + BOOL isURL = [key hasPrefix:@"http://"] || [key hasPrefix:@"https://"]; + for (NSNumber *scaleFactor in SDImageScaleFactors()) { + // @2x. for file name and normal url + NSString *fileScale = [NSString stringWithFormat:@"@%@x.", scaleFactor]; + if ([key containsString:fileScale]) { + scale = scaleFactor.doubleValue; + return scale; + } + if (isURL) { + // %402x. for url encode + NSString *urlScale = [NSString stringWithFormat:@"%%40%@x.", scaleFactor]; + if ([key containsString:urlScale]) { + scale = scaleFactor.doubleValue; + return scale; + } + } + } + } + } + return scale; +} + +inline UIImage * _Nullable SDScaledImageForKey(NSString * _Nullable key, UIImage * _Nullable image) { + if (!image) { + return nil; + } + CGFloat scale = SDImageScaleFactorForKey(key); + return SDScaledImageForScaleFactor(scale, image); +} + +inline UIImage * _Nullable SDScaledImageForScaleFactor(CGFloat scale, UIImage * _Nullable image) { + if (!image) { + return nil; + } + if (scale <= 1) { + return image; + } + if (scale == image.scale) { + return image; + } + UIImage *scaledImage; + // Check SDAnimatedImage support for shortcut + if ([image.class conformsToProtocol:@protocol(SDAnimatedImage)]) { + if ([image respondsToSelector:@selector(animatedCoder)]) { + id coder = [(id)image animatedCoder]; + if (coder) { + scaledImage = [[image.class alloc] initWithAnimatedCoder:coder scale:scale]; + } + } else { + // Some class impl does not support `animatedCoder`, keep for compatibility + NSData *data = [(id)image animatedImageData]; + if (data) { + scaledImage = [[image.class alloc] initWithData:data scale:scale]; + } + } + } + if (scaledImage) { + SDImageCopyAssociatedObject(image, scaledImage); + return scaledImage; + } + if (image.sd_isAnimated) { + UIImage *animatedImage; +#if SD_UIKIT || SD_WATCH + // `UIAnimatedImage` images share the same size and scale. + NSArray *images = image.images; + NSMutableArray *scaledImages = [NSMutableArray arrayWithCapacity:images.count]; + + for (UIImage *tempImage in images) { + UIImage *tempScaledImage = [[UIImage alloc] initWithCGImage:tempImage.CGImage scale:scale orientation:tempImage.imageOrientation]; + [scaledImages addObject:tempScaledImage]; + } + + animatedImage = [UIImage animatedImageWithImages:scaledImages duration:image.duration]; +#else + // Animated GIF for `NSImage` need to grab `NSBitmapImageRep`; + NSRect imageRect = NSMakeRect(0, 0, image.size.width, image.size.height); + NSImageRep *imageRep = [image bestRepresentationForRect:imageRect context:nil hints:nil]; + NSBitmapImageRep *bitmapImageRep; + if ([imageRep isKindOfClass:[NSBitmapImageRep class]]) { + bitmapImageRep = (NSBitmapImageRep *)imageRep; + } + if (bitmapImageRep) { + NSSize size = NSMakeSize(image.size.width / scale, image.size.height / scale); + animatedImage = [[NSImage alloc] initWithSize:size]; + bitmapImageRep.size = size; + [animatedImage addRepresentation:bitmapImageRep]; + } +#endif + scaledImage = animatedImage; + } else { +#if SD_UIKIT || SD_WATCH + scaledImage = [[UIImage alloc] initWithCGImage:image.CGImage scale:scale orientation:image.imageOrientation]; +#else + scaledImage = [[UIImage alloc] initWithCGImage:image.CGImage scale:scale orientation:kCGImagePropertyOrientationUp]; +#endif + } + if (scaledImage) { + SDImageCopyAssociatedObject(image, scaledImage); + return scaledImage; + } + + return nil; +} + +#pragma mark - Context option + +SDWebImageContextOption const SDWebImageContextSetImageOperationKey = @"setImageOperationKey"; +SDWebImageContextOption const SDWebImageContextCustomManager = @"customManager"; +SDWebImageContextOption const SDWebImageContextCallbackQueue = @"callbackQueue"; +SDWebImageContextOption const SDWebImageContextImageCache = @"imageCache"; +SDWebImageContextOption const SDWebImageContextImageLoader = @"imageLoader"; +SDWebImageContextOption const SDWebImageContextImageCoder = @"imageCoder"; +SDWebImageContextOption const SDWebImageContextImageTransformer = @"imageTransformer"; +SDWebImageContextOption const SDWebImageContextImageForceDecodePolicy = @"imageForceDecodePolicy"; +SDWebImageContextOption const SDWebImageContextImageDecodeOptions = @"imageDecodeOptions"; +SDWebImageContextOption const SDWebImageContextImageScaleFactor = @"imageScaleFactor"; +SDWebImageContextOption const SDWebImageContextImagePreserveAspectRatio = @"imagePreserveAspectRatio"; +SDWebImageContextOption const SDWebImageContextImageThumbnailPixelSize = @"imageThumbnailPixelSize"; +SDWebImageContextOption const SDWebImageContextImageTypeIdentifierHint = @"imageTypeIdentifierHint"; +SDWebImageContextOption const SDWebImageContextImageScaleDownLimitBytes = @"imageScaleDownLimitBytes"; +SDWebImageContextOption const SDWebImageContextImageDecodeToHDR = @"imageDecodeToHDR"; +SDWebImageContextOption const SDWebImageContextImageEncodeOptions = @"imageEncodeOptions"; +SDWebImageContextOption const SDWebImageContextQueryCacheType = @"queryCacheType"; +SDWebImageContextOption const SDWebImageContextStoreCacheType = @"storeCacheType"; +SDWebImageContextOption const SDWebImageContextOriginalQueryCacheType = @"originalQueryCacheType"; +SDWebImageContextOption const SDWebImageContextOriginalStoreCacheType = @"originalStoreCacheType"; +SDWebImageContextOption const SDWebImageContextOriginalImageCache = @"originalImageCache"; +SDWebImageContextOption const SDWebImageContextAnimatedImageClass = @"animatedImageClass"; +SDWebImageContextOption const SDWebImageContextDownloadRequestModifier = @"downloadRequestModifier"; +SDWebImageContextOption const SDWebImageContextDownloadResponseModifier = @"downloadResponseModifier"; +SDWebImageContextOption const SDWebImageContextDownloadDecryptor = @"downloadDecryptor"; +SDWebImageContextOption const SDWebImageContextCacheKeyFilter = @"cacheKeyFilter"; +SDWebImageContextOption const SDWebImageContextCacheSerializer = @"cacheSerializer"; diff --git a/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloader.h b/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloader.h new file mode 100644 index 0000000..eec3fc1 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloader.h @@ -0,0 +1,320 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" +#import "SDWebImageDefine.h" +#import "SDWebImageOperation.h" +#import "SDWebImageDownloaderConfig.h" +#import "SDWebImageDownloaderRequestModifier.h" +#import "SDWebImageDownloaderResponseModifier.h" +#import "SDWebImageDownloaderDecryptor.h" +#import "SDImageLoader.h" + +/// Downloader options +typedef NS_OPTIONS(NSUInteger, SDWebImageDownloaderOptions) { + /** + * Put the download in the low queue priority and task priority. + */ + SDWebImageDownloaderLowPriority = 1 << 0, + + /** + * This flag enables progressive download, the image is displayed progressively during download as a browser would do. + */ + SDWebImageDownloaderProgressiveLoad = 1 << 1, + + /** + * By default, request prevent the use of NSURLCache. With this flag, NSURLCache + * is used with default policies. + */ + SDWebImageDownloaderUseNSURLCache = 1 << 2, + + /** + * Call completion block with nil image/imageData if the image was read from NSURLCache + * And the error code is `SDWebImageErrorCacheNotModified` + * This flag should be combined with `SDWebImageDownloaderUseNSURLCache`. + */ + SDWebImageDownloaderIgnoreCachedResponse = 1 << 3, + + /** + * In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for + * extra time in background to let the request finish. If the background task expires the operation will be cancelled. + */ + SDWebImageDownloaderContinueInBackground = 1 << 4, + + /** + * Handles cookies stored in NSHTTPCookieStore by setting + * NSMutableURLRequest.HTTPShouldHandleCookies = YES; + */ + SDWebImageDownloaderHandleCookies = 1 << 5, + + /** + * Enable to allow untrusted SSL certificates. + * Useful for testing purposes. Use with caution in production. + */ + SDWebImageDownloaderAllowInvalidSSLCertificates = 1 << 6, + + /** + * Put the download in the high queue priority and task priority. + */ + SDWebImageDownloaderHighPriority = 1 << 7, + + /** + * By default, images are decoded respecting their original size. On iOS, this flag will scale down the + * images to a size compatible with the constrained memory of devices. + * This flag take no effect if `SDWebImageDownloaderAvoidDecodeImage` is set. And it will be ignored if `SDWebImageDownloaderProgressiveLoad` is set. + */ + SDWebImageDownloaderScaleDownLargeImages = 1 << 8, + + /** + * By default, we will decode the image in the background during cache query and download from the network. This can help to improve performance because when rendering image on the screen, it need to be firstly decoded. But this happen on the main queue by Core Animation. + * However, this process may increase the memory usage as well. If you are experiencing a issue due to excessive memory consumption, This flag can prevent decode the image. + * @note 5.14.0 introduce `SDImageCoderDecodeUseLazyDecoding`, use that for better control from codec, instead of post-processing. Which acts the similar like this option but works for SDAnimatedImage as well (this one does not) + * @deprecated Deprecated in v5.17.0, if you don't want force-decode, pass [.imageForceDecodePolicy] = SDImageForceDecodePolicy.never.rawValue in context option + */ + SDWebImageDownloaderAvoidDecodeImage API_DEPRECATED("Use SDWebImageContextImageForceDecodePolicy instead", macos(10.10, 10.10), ios(8.0, 8.0), tvos(9.0, 9.0), watchos(2.0, 2.0)) = 1 << 9, + + /** + * By default, we decode the animated image. This flag can force decode the first frame only and produce the static image. + */ + SDWebImageDownloaderDecodeFirstFrameOnly = 1 << 10, + + /** + * By default, for `SDAnimatedImage`, we decode the animated image frame during rendering to reduce memory usage. This flag actually trigger `preloadAllAnimatedImageFrames = YES` after image load from network + */ + SDWebImageDownloaderPreloadAllFrames = 1 << 11, + + /** + * By default, when you use `SDWebImageContextAnimatedImageClass` context option (like using `SDAnimatedImageView` which designed to use `SDAnimatedImage`), we may still use `UIImage` when the memory cache hit, or image decoder is not available, to behave as a fallback solution. + * Using this option, can ensure we always produce image with your provided class. If failed, a error with code `SDWebImageErrorBadImageData` will been used. + * Note this options is not compatible with `SDWebImageDownloaderDecodeFirstFrameOnly`, which always produce a UIImage/NSImage. + */ + SDWebImageDownloaderMatchAnimatedImageClass = 1 << 12, +}; + +/// Posed when URLSessionTask started (`resume` called)) +FOUNDATION_EXPORT NSNotificationName _Nonnull const SDWebImageDownloadStartNotification; +/// Posed when URLSessionTask get HTTP response (`didReceiveResponse:completionHandler:` called) +FOUNDATION_EXPORT NSNotificationName _Nonnull const SDWebImageDownloadReceiveResponseNotification; +/// Posed when URLSessionTask stoped (`didCompleteWithError:` with error or `cancel` called) +FOUNDATION_EXPORT NSNotificationName _Nonnull const SDWebImageDownloadStopNotification; +/// Posed when URLSessionTask finished with success (`didCompleteWithError:` without error) +FOUNDATION_EXPORT NSNotificationName _Nonnull const SDWebImageDownloadFinishNotification; + +typedef SDImageLoaderProgressBlock SDWebImageDownloaderProgressBlock; +typedef SDImageLoaderCompletedBlock SDWebImageDownloaderCompletedBlock; + +/** + * A token associated with each download. Can be used to cancel a download + */ +@interface SDWebImageDownloadToken : NSObject + +/** + Cancel the current download. + */ +- (void)cancel; + +/** + The download's URL. + */ +@property (nonatomic, strong, nullable, readonly) NSURL *url; + +/** + The download's request. + */ +@property (nonatomic, strong, nullable, readonly) NSURLRequest *request; + +/** + The download's response. + */ +@property (nonatomic, strong, nullable, readonly) NSURLResponse *response; + +/** + The download's metrics. This will be nil if download operation does not support metrics. + */ +@property (nonatomic, strong, nullable, readonly) NSURLSessionTaskMetrics *metrics API_AVAILABLE(macos(10.12), ios(10.0), watchos(3.0), tvos(10.0)); + +@end + + +/** + * Asynchronous downloader dedicated and optimized for image loading. + */ +@interface SDWebImageDownloader : NSObject + +/** + * Downloader Config object - storing all kind of settings. + * Most config properties support dynamic changes during download, except something like `sessionConfiguration`, see `SDWebImageDownloaderConfig` for more detail. + */ +@property (nonatomic, copy, readonly, nonnull) SDWebImageDownloaderConfig *config; + +/** + * Set the request modifier to modify the original download request before image load. + * This request modifier method will be called for each downloading image request. Return the original request means no modification. Return nil will cancel the download request. + * Defaults to nil, means does not modify the original download request. + * @note If you want to modify single request, consider using `SDWebImageContextDownloadRequestModifier` context option. + */ +@property (nonatomic, strong, nullable) id requestModifier; + +/** + * Set the response modifier to modify the original download response during image load. + * This response modifier method will be called for each downloading image response. Return the original response means no modification. Return nil will mark current download as cancelled. + * Defaults to nil, means does not modify the original download response. + * @note If you want to modify single response, consider using `SDWebImageContextDownloadResponseModifier` context option. + */ +@property (nonatomic, strong, nullable) id responseModifier; + +/** + * Set the decryptor to decrypt the original download data before image decoding. This can be used for encrypted image data, like Base64. + * This decryptor method will be called for each downloading image data. Return the original data means no modification. Return nil will mark this download failed. + * Defaults to nil, means does not modify the original download data. + * @note When using decryptor, progressive decoding will be disabled, to avoid data corrupt issue. + * @note If you want to decrypt single download data, consider using `SDWebImageContextDownloadDecryptor` context option. + */ +@property (nonatomic, strong, nullable) id decryptor; + +/** + * The configuration in use by the internal NSURLSession. If you want to provide a custom sessionConfiguration, use `SDWebImageDownloaderConfig.sessionConfiguration` and create a new downloader instance. + @note This is immutable according to NSURLSession's documentation. Mutating this object directly has no effect. + */ +@property (nonatomic, readonly, nonnull) NSURLSessionConfiguration *sessionConfiguration; + +/** + * Gets/Sets the download queue suspension state. + */ +@property (nonatomic, assign, getter=isSuspended) BOOL suspended; + +/** + * Shows the current amount of downloads that still need to be downloaded + */ +@property (nonatomic, assign, readonly) NSUInteger currentDownloadCount; + +/** + * Returns the global shared downloader instance. Which use the `SDWebImageDownloaderConfig.defaultDownloaderConfig` config. + */ +@property (nonatomic, class, readonly, nonnull) SDWebImageDownloader *sharedDownloader; + +/** + Creates an instance of a downloader with specified downloader config. + You can specify session configuration, timeout or operation class through downloader config. + + @param config The downloader config. If you specify nil, the `defaultDownloaderConfig` will be used. + @return new instance of downloader class + */ +- (nonnull instancetype)initWithConfig:(nullable SDWebImageDownloaderConfig *)config NS_DESIGNATED_INITIALIZER; + +/** + * Set a value for a HTTP header to be appended to each download HTTP request. + * + * @param value The value for the header field. Use `nil` value to remove the header field. + * @param field The name of the header field to set. + */ +- (void)setValue:(nullable NSString *)value forHTTPHeaderField:(nullable NSString *)field; + +/** + * Returns the value of the specified HTTP header field. + * + * @return The value associated with the header field field, or `nil` if there is no corresponding header field. + */ +- (nullable NSString *)valueForHTTPHeaderField:(nullable NSString *)field; + +/** + * Creates a SDWebImageDownloader async downloader instance with a given URL + * + * The delegate will be informed when the image is finish downloaded or an error has happen. + * + * @see SDWebImageDownloaderDelegate + * + * @param url The URL to the image to download + * @param completedBlock A block called once the download is completed. + * If the download succeeded, the image parameter is set, in case of error, + * error parameter is set with the error. The last parameter is always YES + * if SDWebImageDownloaderProgressiveDownload isn't use. With the + * SDWebImageDownloaderProgressiveDownload option, this block is called + * repeatedly with the partial image object and the finished argument set to NO + * before to be called a last time with the full image and finished argument + * set to YES. In case of error, the finished argument is always YES. + * + * @return A token (SDWebImageDownloadToken) that can be used to cancel this operation + */ +- (nullable SDWebImageDownloadToken *)downloadImageWithURL:(nullable NSURL *)url + completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock; + +/** + * Creates a SDWebImageDownloader async downloader instance with a given URL + * + * The delegate will be informed when the image is finish downloaded or an error has happen. + * + * @see SDWebImageDownloaderDelegate + * + * @param url The URL to the image to download + * @param options The options to be used for this download + * @param progressBlock A block called repeatedly while the image is downloading + * @note the progress block is executed on a background queue + * @param completedBlock A block called once the download is completed. + * If the download succeeded, the image parameter is set, in case of error, + * error parameter is set with the error. The last parameter is always YES + * if SDWebImageDownloaderProgressiveLoad isn't use. With the + * SDWebImageDownloaderProgressiveLoad option, this block is called + * repeatedly with the partial image object and the finished argument set to NO + * before to be called a last time with the full image and finished argument + * set to YES. In case of error, the finished argument is always YES. + * + * @return A token (SDWebImageDownloadToken) that can be used to cancel this operation + */ +- (nullable SDWebImageDownloadToken *)downloadImageWithURL:(nullable NSURL *)url + options:(SDWebImageDownloaderOptions)options + progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock + completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock; + +/** + * Creates a SDWebImageDownloader async downloader instance with a given URL + * + * The delegate will be informed when the image is finish downloaded or an error has happen. + * + * @see SDWebImageDownloaderDelegate + * + * @param url The URL to the image to download + * @param options The options to be used for this download + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + * @param progressBlock A block called repeatedly while the image is downloading + * @note the progress block is executed on a background queue + * @param completedBlock A block called once the download is completed. + * + * @return A token (SDWebImageDownloadToken) that can be used to cancel this operation + */ +- (nullable SDWebImageDownloadToken *)downloadImageWithURL:(nullable NSURL *)url + options:(SDWebImageDownloaderOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock + completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock; + +/** + * Cancels all download operations in the queue + */ +- (void)cancelAllDownloads; + +/** + * Invalidates the managed session, optionally canceling pending operations. + * @note If you use custom downloader instead of the shared downloader, you need call this method when you do not use it to avoid memory leak + * @param cancelPendingOperations Whether or not to cancel pending operations. + * @note Calling this method on the shared downloader has no effect. + */ +- (void)invalidateSessionAndCancel:(BOOL)cancelPendingOperations; + +@end + + +/** + SDWebImageDownloader is the built-in image loader conform to `SDImageLoader`. Which provide the HTTP/HTTPS/FTP download, or local file URL using NSURLSession. + However, this downloader class itself also support customization for advanced users. You can specify `operationClass` in download config to custom download operation, See `SDWebImageDownloaderOperation`. + If you want to provide some image loader which beyond network or local file, consider to create your own custom class conform to `SDImageLoader`. + */ +@interface SDWebImageDownloader (SDImageLoader) + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloader.m b/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloader.m new file mode 100644 index 0000000..6628afd --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloader.m @@ -0,0 +1,665 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageDownloader.h" +#import "SDWebImageDownloaderConfig.h" +#import "SDWebImageDownloaderOperation.h" +#import "SDWebImageError.h" +#import "SDWebImageCacheKeyFilter.h" +#import "SDImageCacheDefine.h" +#import "SDInternalMacros.h" +#import "objc/runtime.h" + +NSNotificationName const SDWebImageDownloadStartNotification = @"SDWebImageDownloadStartNotification"; +NSNotificationName const SDWebImageDownloadReceiveResponseNotification = @"SDWebImageDownloadReceiveResponseNotification"; +NSNotificationName const SDWebImageDownloadStopNotification = @"SDWebImageDownloadStopNotification"; +NSNotificationName const SDWebImageDownloadFinishNotification = @"SDWebImageDownloadFinishNotification"; + +static void * SDWebImageDownloaderContext = &SDWebImageDownloaderContext; + +@interface SDWebImageDownloadToken () + +@property (nonatomic, strong, nullable, readwrite) NSURL *url; +@property (nonatomic, strong, nullable, readwrite) NSURLRequest *request; +@property (nonatomic, strong, nullable, readwrite) NSURLResponse *response; +@property (nonatomic, strong, nullable, readwrite) NSURLSessionTaskMetrics *metrics API_AVAILABLE(macos(10.12), ios(10.0), watchos(3.0), tvos(10.0)); +@property (nonatomic, weak, nullable, readwrite) id downloadOperationCancelToken; +@property (nonatomic, weak, nullable) NSOperation *downloadOperation; +@property (nonatomic, assign, getter=isCancelled) BOOL cancelled; + +- (nonnull instancetype)init NS_UNAVAILABLE; ++ (nonnull instancetype)new NS_UNAVAILABLE; +- (nonnull instancetype)initWithDownloadOperation:(nullable NSOperation *)downloadOperation; + +@end + +@interface SDWebImageDownloader () + +@property (strong, nonatomic, nonnull) NSOperationQueue *downloadQueue; +@property (strong, nonatomic, nonnull) NSMutableDictionary *> *URLOperations; +@property (strong, nonatomic, nullable) NSMutableDictionary *HTTPHeaders; + +// The session in which data tasks will run +@property (strong, nonatomic) NSURLSession *session; + +@end + +@implementation SDWebImageDownloader { + SD_LOCK_DECLARE(_HTTPHeadersLock); // A lock to keep the access to `HTTPHeaders` thread-safe + SD_LOCK_DECLARE(_operationsLock); // A lock to keep the access to `URLOperations` thread-safe +} + ++ (void)initialize { + // Bind SDNetworkActivityIndicator if available (download it here: http://github.com/rs/SDNetworkActivityIndicator ) + // To use it, just add #import "SDNetworkActivityIndicator.h" in addition to the SDWebImage import + if (NSClassFromString(@"SDNetworkActivityIndicator")) { + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-performSelector-leaks" + id activityIndicator = [NSClassFromString(@"SDNetworkActivityIndicator") performSelector:NSSelectorFromString(@"sharedActivityIndicator")]; +#pragma clang diagnostic pop + + // Remove observer in case it was previously added. + [[NSNotificationCenter defaultCenter] removeObserver:activityIndicator name:SDWebImageDownloadStartNotification object:nil]; + [[NSNotificationCenter defaultCenter] removeObserver:activityIndicator name:SDWebImageDownloadStopNotification object:nil]; + + [[NSNotificationCenter defaultCenter] addObserver:activityIndicator + selector:NSSelectorFromString(@"startActivity") + name:SDWebImageDownloadStartNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:activityIndicator + selector:NSSelectorFromString(@"stopActivity") + name:SDWebImageDownloadStopNotification object:nil]; + } +} + ++ (nonnull instancetype)sharedDownloader { + static dispatch_once_t once; + static id instance; + dispatch_once(&once, ^{ + instance = [self new]; + }); + return instance; +} + +- (nonnull instancetype)init { + return [self initWithConfig:SDWebImageDownloaderConfig.defaultDownloaderConfig]; +} + +- (instancetype)initWithConfig:(SDWebImageDownloaderConfig *)config { + self = [super init]; + if (self) { + if (!config) { + config = SDWebImageDownloaderConfig.defaultDownloaderConfig; + } + _config = [config copy]; + [_config addObserver:self forKeyPath:NSStringFromSelector(@selector(maxConcurrentDownloads)) options:0 context:SDWebImageDownloaderContext]; + _downloadQueue = [NSOperationQueue new]; + _downloadQueue.maxConcurrentOperationCount = _config.maxConcurrentDownloads; + _downloadQueue.name = @"com.hackemist.SDWebImageDownloader.downloadQueue"; + _URLOperations = [NSMutableDictionary new]; + NSMutableDictionary *headerDictionary = [NSMutableDictionary dictionary]; + NSString *userAgent = nil; + // User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43 +#if SD_VISION + userAgent = [NSString stringWithFormat:@"%@/%@ (%@; visionOS %@; 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], UITraitCollection.currentTraitCollection.displayScale]; +#elif SD_UIKIT + 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 SD_WATCH + 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 SD_MAC + 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 + 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; + } + } + headerDictionary[@"User-Agent"] = userAgent; + } + headerDictionary[@"Accept"] = @"image/*,*/*;q=0.8"; + _HTTPHeaders = headerDictionary; + SD_LOCK_INIT(_HTTPHeadersLock); + SD_LOCK_INIT(_operationsLock); + NSURLSessionConfiguration *sessionConfiguration = _config.sessionConfiguration; + if (!sessionConfiguration) { + sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration]; + } + /** + * Create the session for this task + * We send nil as delegate queue so that the session creates a serial operation queue for performing all delegate + * method calls and completion handler calls. + */ + _session = [NSURLSession sessionWithConfiguration:sessionConfiguration + delegate:self + delegateQueue:nil]; + } + return self; +} + +- (void)dealloc { + [self.downloadQueue cancelAllOperations]; + [self.config removeObserver:self forKeyPath:NSStringFromSelector(@selector(maxConcurrentDownloads)) context:SDWebImageDownloaderContext]; + + // Invalide the URLSession after all operations been cancelled + [self.session invalidateAndCancel]; + self.session = nil; +} + +- (void)invalidateSessionAndCancel:(BOOL)cancelPendingOperations { + if (self == [SDWebImageDownloader sharedDownloader]) { + return; + } + if (cancelPendingOperations) { + [self.session invalidateAndCancel]; + } else { + [self.session finishTasksAndInvalidate]; + } +} + +- (void)setValue:(nullable NSString *)value forHTTPHeaderField:(nullable NSString *)field { + if (!field) { + return; + } + SD_LOCK(_HTTPHeadersLock); + [self.HTTPHeaders setValue:value forKey:field]; + SD_UNLOCK(_HTTPHeadersLock); +} + +- (nullable NSString *)valueForHTTPHeaderField:(nullable NSString *)field { + if (!field) { + return nil; + } + SD_LOCK(_HTTPHeadersLock); + NSString *value = [self.HTTPHeaders objectForKey:field]; + SD_UNLOCK(_HTTPHeadersLock); + return value; +} + +- (nullable SDWebImageDownloadToken *)downloadImageWithURL:(NSURL *)url + completed:(SDWebImageDownloaderCompletedBlock)completedBlock { + return [self downloadImageWithURL:url options:0 progress:nil completed:completedBlock]; +} + +- (nullable SDWebImageDownloadToken *)downloadImageWithURL:(NSURL *)url + options:(SDWebImageDownloaderOptions)options + progress:(SDWebImageDownloaderProgressBlock)progressBlock + completed:(SDWebImageDownloaderCompletedBlock)completedBlock { + return [self downloadImageWithURL:url options:options context:nil progress:progressBlock completed:completedBlock]; +} + +- (nullable SDWebImageDownloadToken *)downloadImageWithURL:(nullable NSURL *)url + options:(SDWebImageDownloaderOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock + completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock { + // The URL will be used as the key to the callbacks dictionary so it cannot be nil. If it is nil immediately call the completed block with no image or data. + if (url == nil) { + if (completedBlock) { + NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorInvalidURL userInfo:@{NSLocalizedDescriptionKey : @"Image url is nil"}]; + completedBlock(nil, nil, error, YES); + } + return nil; + } + + id downloadOperationCancelToken; + // When different thumbnail size download with same url, we need to make sure each callback called with desired size + id cacheKeyFilter = context[SDWebImageContextCacheKeyFilter]; + NSString *cacheKey; + if (cacheKeyFilter) { + cacheKey = [cacheKeyFilter cacheKeyForURL:url]; + } else { + cacheKey = url.absoluteString; + } + SDImageCoderOptions *decodeOptions = SDGetDecodeOptionsFromContext(context, [self.class imageOptionsFromDownloaderOptions:options], cacheKey); + SD_LOCK(_operationsLock); + NSOperation *operation = [self.URLOperations objectForKey:url]; + // There is a case that the operation may be marked as finished or cancelled, but not been removed from `self.URLOperations`. + BOOL shouldNotReuseOperation; + if (operation) { + @synchronized (operation) { + shouldNotReuseOperation = operation.isFinished || operation.isCancelled; + } + } else { + shouldNotReuseOperation = YES; + } + if (shouldNotReuseOperation) { + operation = [self createDownloaderOperationWithUrl:url options:options context:context]; + if (!operation) { + SD_UNLOCK(_operationsLock); + if (completedBlock) { + NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorInvalidDownloadOperation userInfo:@{NSLocalizedDescriptionKey : @"Downloader operation is nil"}]; + completedBlock(nil, nil, error, YES); + } + return nil; + } + @weakify(self); + operation.completionBlock = ^{ + @strongify(self); + if (!self) { + return; + } + SD_LOCK(self->_operationsLock); + [self.URLOperations removeObjectForKey:url]; + SD_UNLOCK(self->_operationsLock); + }; + [self.URLOperations setObject:operation forKey:url]; + // Add the handlers before submitting to operation queue, avoid the race condition that operation finished before setting handlers. + downloadOperationCancelToken = [operation addHandlersForProgress:progressBlock completed:completedBlock decodeOptions:decodeOptions]; + // Add operation to operation queue only after all configuration done according to Apple's doc. + // `addOperation:` does not synchronously execute the `operation.completionBlock` so this will not cause deadlock. + [self.downloadQueue addOperation:operation]; + } else { + // When we reuse the download operation to attach more callbacks, there may be thread safe issue because the getter of callbacks may in another queue (decoding queue or delegate queue) + // So we lock the operation here, and in `SDWebImageDownloaderOperation`, we use `@synchonzied (self)`, to ensure the thread safe between these two classes. + @synchronized (operation) { + downloadOperationCancelToken = [operation addHandlersForProgress:progressBlock completed:completedBlock decodeOptions:decodeOptions]; + } + } + SD_UNLOCK(_operationsLock); + + SDWebImageDownloadToken *token = [[SDWebImageDownloadToken alloc] initWithDownloadOperation:operation]; + token.url = url; + token.request = operation.request; + token.downloadOperationCancelToken = downloadOperationCancelToken; + + return token; +} + +#pragma mark Helper methods +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" ++ (SDWebImageOptions)imageOptionsFromDownloaderOptions:(SDWebImageDownloaderOptions)downloadOptions { + SDWebImageOptions options = 0; + if (downloadOptions & SDWebImageDownloaderScaleDownLargeImages) options |= SDWebImageScaleDownLargeImages; + if (downloadOptions & SDWebImageDownloaderDecodeFirstFrameOnly) options |= SDWebImageDecodeFirstFrameOnly; + if (downloadOptions & SDWebImageDownloaderPreloadAllFrames) options |= SDWebImagePreloadAllFrames; + if (downloadOptions & SDWebImageDownloaderAvoidDecodeImage) options |= SDWebImageAvoidDecodeImage; + if (downloadOptions & SDWebImageDownloaderMatchAnimatedImageClass) options |= SDWebImageMatchAnimatedImageClass; + + return options; +} +#pragma clang diagnostic pop + +- (nullable NSOperation *)createDownloaderOperationWithUrl:(nonnull NSURL *)url + options:(SDWebImageDownloaderOptions)options + context:(nullable SDWebImageContext *)context { + NSTimeInterval timeoutInterval = self.config.downloadTimeout; + if (timeoutInterval == 0.0) { + timeoutInterval = 15.0; + } + + // In order to prevent from potential duplicate caching (NSURLCache + SDImageCache) we disable the cache for image requests if told otherwise + NSURLRequestCachePolicy cachePolicy = options & SDWebImageDownloaderUseNSURLCache ? NSURLRequestUseProtocolCachePolicy : NSURLRequestReloadIgnoringLocalCacheData; + NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:cachePolicy timeoutInterval:timeoutInterval]; + mutableRequest.HTTPShouldHandleCookies = SD_OPTIONS_CONTAINS(options, SDWebImageDownloaderHandleCookies); + mutableRequest.HTTPShouldUsePipelining = YES; + SD_LOCK(_HTTPHeadersLock); + mutableRequest.allHTTPHeaderFields = self.HTTPHeaders; + SD_UNLOCK(_HTTPHeadersLock); + + // Context Option + SDWebImageMutableContext *mutableContext; + if (context) { + mutableContext = [context mutableCopy]; + } else { + mutableContext = [NSMutableDictionary dictionary]; + } + + // Request Modifier + id requestModifier; + if ([context valueForKey:SDWebImageContextDownloadRequestModifier]) { + requestModifier = [context valueForKey:SDWebImageContextDownloadRequestModifier]; + } else { + requestModifier = self.requestModifier; + } + + NSURLRequest *request; + if (requestModifier) { + NSURLRequest *modifiedRequest = [requestModifier modifiedRequestWithRequest:[mutableRequest copy]]; + // If modified request is nil, early return + if (!modifiedRequest) { + return nil; + } else { + request = [modifiedRequest copy]; + } + } else { + request = [mutableRequest copy]; + } + // Response Modifier + id responseModifier; + if ([context valueForKey:SDWebImageContextDownloadResponseModifier]) { + responseModifier = [context valueForKey:SDWebImageContextDownloadResponseModifier]; + } else { + responseModifier = self.responseModifier; + } + if (responseModifier) { + mutableContext[SDWebImageContextDownloadResponseModifier] = responseModifier; + } + // Decryptor + id decryptor; + if ([context valueForKey:SDWebImageContextDownloadDecryptor]) { + decryptor = [context valueForKey:SDWebImageContextDownloadDecryptor]; + } else { + decryptor = self.decryptor; + } + if (decryptor) { + mutableContext[SDWebImageContextDownloadDecryptor] = decryptor; + } + + context = [mutableContext copy]; + + // Operation Class + Class operationClass = self.config.operationClass; + if (!operationClass) { + operationClass = [SDWebImageDownloaderOperation class]; + } + NSOperation *operation = [[operationClass alloc] initWithRequest:request inSession:self.session options:options context:context]; + + if ([operation respondsToSelector:@selector(setCredential:)]) { + if (self.config.urlCredential) { + operation.credential = self.config.urlCredential; + } else if (self.config.username && self.config.password) { + operation.credential = [NSURLCredential credentialWithUser:self.config.username password:self.config.password persistence:NSURLCredentialPersistenceForSession]; + } + } + + if ([operation respondsToSelector:@selector(setMinimumProgressInterval:)]) { + operation.minimumProgressInterval = MIN(MAX(self.config.minimumProgressInterval, 0), 1); + } + + if ([operation respondsToSelector:@selector(setAcceptableStatusCodes:)]) { + operation.acceptableStatusCodes = self.config.acceptableStatusCodes; + } + + if ([operation respondsToSelector:@selector(setAcceptableContentTypes:)]) { + operation.acceptableContentTypes = self.config.acceptableContentTypes; + } + + if (options & SDWebImageDownloaderHighPriority) { + operation.queuePriority = NSOperationQueuePriorityHigh; + } else if (options & SDWebImageDownloaderLowPriority) { + operation.queuePriority = NSOperationQueuePriorityLow; + } + + if (self.config.executionOrder == SDWebImageDownloaderLIFOExecutionOrder) { + // Emulate LIFO execution order by systematically, each previous adding operation can dependency the new operation + // This can gurantee the new operation to be execulated firstly, even if when some operations finished, meanwhile you appending new operations + // Just make last added operation dependents new operation can not solve this problem. See test case #test15DownloaderLIFOExecutionOrder + for (NSOperation *pendingOperation in self.downloadQueue.operations) { + [pendingOperation addDependency:operation]; + } + } + + return operation; +} + +- (void)cancelAllDownloads { + [self.downloadQueue cancelAllOperations]; +} + +#pragma mark - Properties + +- (BOOL)isSuspended { + return self.downloadQueue.isSuspended; +} + +- (void)setSuspended:(BOOL)suspended { + self.downloadQueue.suspended = suspended; +} + +- (NSUInteger)currentDownloadCount { + return self.downloadQueue.operationCount; +} + +- (NSURLSessionConfiguration *)sessionConfiguration { + return self.session.configuration; +} + +#pragma mark - KVO + +- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { + if (context == SDWebImageDownloaderContext) { + if ([keyPath isEqualToString:NSStringFromSelector(@selector(maxConcurrentDownloads))]) { + self.downloadQueue.maxConcurrentOperationCount = self.config.maxConcurrentDownloads; + } + } else { + [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; + } +} + +#pragma mark Helper methods + +- (NSOperation *)operationWithTask:(NSURLSessionTask *)task { + NSOperation *returnOperation = nil; + for (NSOperation *operation in self.downloadQueue.operations) { + if ([operation respondsToSelector:@selector(dataTask)]) { + // So we lock the operation here, and in `SDWebImageDownloaderOperation`, we use `@synchonzied (self)`, to ensure the thread safe between these two classes. + NSURLSessionTask *operationTask; + @synchronized (operation) { + operationTask = operation.dataTask; + } + if (operationTask.taskIdentifier == task.taskIdentifier) { + returnOperation = operation; + break; + } + } + } + return returnOperation; +} + +#pragma mark NSURLSessionDataDelegate + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask +didReceiveResponse:(NSURLResponse *)response + completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler { + + // Identify the operation that runs this task and pass it the delegate method + NSOperation *dataOperation = [self operationWithTask:dataTask]; + if ([dataOperation respondsToSelector:@selector(URLSession:dataTask:didReceiveResponse:completionHandler:)]) { + [dataOperation URLSession:session dataTask:dataTask didReceiveResponse:response completionHandler:completionHandler]; + } else { + if (completionHandler) { + completionHandler(NSURLSessionResponseAllow); + } + } +} + +- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { + + // Identify the operation that runs this task and pass it the delegate method + NSOperation *dataOperation = [self operationWithTask:dataTask]; + if ([dataOperation respondsToSelector:@selector(URLSession:dataTask:didReceiveData:)]) { + [dataOperation URLSession:session dataTask:dataTask didReceiveData:data]; + } +} + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask + willCacheResponse:(NSCachedURLResponse *)proposedResponse + completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler { + + // Identify the operation that runs this task and pass it the delegate method + NSOperation *dataOperation = [self operationWithTask:dataTask]; + if ([dataOperation respondsToSelector:@selector(URLSession:dataTask:willCacheResponse:completionHandler:)]) { + [dataOperation URLSession:session dataTask:dataTask willCacheResponse:proposedResponse completionHandler:completionHandler]; + } else { + if (completionHandler) { + completionHandler(proposedResponse); + } + } +} + +#pragma mark NSURLSessionTaskDelegate + +- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { + + // Identify the operation that runs this task and pass it the delegate method + NSOperation *dataOperation = [self operationWithTask:task]; + if ([dataOperation respondsToSelector:@selector(URLSession:task:didCompleteWithError:)]) { + [dataOperation URLSession:session task:task didCompleteWithError:error]; + } +} + +- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest * _Nullable))completionHandler { + + // Identify the operation that runs this task and pass it the delegate method + NSOperation *dataOperation = [self operationWithTask:task]; + if ([dataOperation respondsToSelector:@selector(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:)]) { + [dataOperation URLSession:session task:task willPerformHTTPRedirection:response newRequest:request completionHandler:completionHandler]; + } else { + if (completionHandler) { + completionHandler(request); + } + } +} + +- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler { + + // Identify the operation that runs this task and pass it the delegate method + NSOperation *dataOperation = [self operationWithTask:task]; + if ([dataOperation respondsToSelector:@selector(URLSession:task:didReceiveChallenge:completionHandler:)]) { + [dataOperation URLSession:session task:task didReceiveChallenge:challenge completionHandler:completionHandler]; + } else { + if (completionHandler) { + completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil); + } + } +} + +- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didFinishCollectingMetrics:(NSURLSessionTaskMetrics *)metrics API_AVAILABLE(macos(10.12), ios(10.0), watchos(3.0), tvos(10.0)) { + + // Identify the operation that runs this task and pass it the delegate method + NSOperation *dataOperation = [self operationWithTask:task]; + if ([dataOperation respondsToSelector:@selector(URLSession:task:didFinishCollectingMetrics:)]) { + [dataOperation URLSession:session task:task didFinishCollectingMetrics:metrics]; + } +} + +@end + +@implementation SDWebImageDownloadToken + +- (void)dealloc { + [[NSNotificationCenter defaultCenter] removeObserver:self name:SDWebImageDownloadReceiveResponseNotification object:nil]; + [[NSNotificationCenter defaultCenter] removeObserver:self name:SDWebImageDownloadStopNotification object:nil]; +} + +- (instancetype)initWithDownloadOperation:(NSOperation *)downloadOperation { + self = [super init]; + if (self) { + _downloadOperation = downloadOperation; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(downloadDidReceiveResponse:) name:SDWebImageDownloadReceiveResponseNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(downloadDidStop:) name:SDWebImageDownloadStopNotification object:nil]; + } + return self; +} + +- (void)downloadDidReceiveResponse:(NSNotification *)notification { + NSOperation *downloadOperation = notification.object; + if (downloadOperation && downloadOperation == self.downloadOperation) { + self.response = downloadOperation.response; + } +} + +- (void)downloadDidStop:(NSNotification *)notification { + NSOperation *downloadOperation = notification.object; + if (downloadOperation && downloadOperation == self.downloadOperation) { + if ([downloadOperation respondsToSelector:@selector(metrics)]) { + if (@available(iOS 10.0, tvOS 10.0, macOS 10.12, watchOS 3.0, *)) { + self.metrics = downloadOperation.metrics; + } + } + } +} + +- (void)cancel { + @synchronized (self) { + if (self.isCancelled) { + return; + } + self.cancelled = YES; + [self.downloadOperation cancel:self.downloadOperationCancelToken]; + self.downloadOperationCancelToken = nil; + } +} + +@end + +@implementation SDWebImageDownloader (SDImageLoader) + +- (BOOL)canRequestImageForURL:(NSURL *)url { + return [self canRequestImageForURL:url options:0 context:nil]; +} + +- (BOOL)canRequestImageForURL:(NSURL *)url options:(SDWebImageOptions)options context:(SDWebImageContext *)context { + if (!url) { + return NO; + } + // Always pass YES to let URLSession or custom download operation to determine + return YES; +} + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +- (id)requestImageWithURL:(NSURL *)url options:(SDWebImageOptions)options context:(SDWebImageContext *)context progress:(SDImageLoaderProgressBlock)progressBlock completed:(SDImageLoaderCompletedBlock)completedBlock { + UIImage *cachedImage = context[SDWebImageContextLoaderCachedImage]; + + SDWebImageDownloaderOptions downloaderOptions = 0; + if (options & SDWebImageLowPriority) downloaderOptions |= SDWebImageDownloaderLowPriority; + if (options & SDWebImageProgressiveLoad) downloaderOptions |= SDWebImageDownloaderProgressiveLoad; + if (options & SDWebImageRefreshCached) downloaderOptions |= SDWebImageDownloaderUseNSURLCache; + if (options & SDWebImageContinueInBackground) downloaderOptions |= SDWebImageDownloaderContinueInBackground; + if (options & SDWebImageHandleCookies) downloaderOptions |= SDWebImageDownloaderHandleCookies; + if (options & SDWebImageAllowInvalidSSLCertificates) downloaderOptions |= SDWebImageDownloaderAllowInvalidSSLCertificates; + if (options & SDWebImageHighPriority) downloaderOptions |= SDWebImageDownloaderHighPriority; + if (options & SDWebImageScaleDownLargeImages) downloaderOptions |= SDWebImageDownloaderScaleDownLargeImages; + if (options & SDWebImageAvoidDecodeImage) downloaderOptions |= SDWebImageDownloaderAvoidDecodeImage; + if (options & SDWebImageDecodeFirstFrameOnly) downloaderOptions |= SDWebImageDownloaderDecodeFirstFrameOnly; + if (options & SDWebImagePreloadAllFrames) downloaderOptions |= SDWebImageDownloaderPreloadAllFrames; + if (options & SDWebImageMatchAnimatedImageClass) downloaderOptions |= SDWebImageDownloaderMatchAnimatedImageClass; + + if (cachedImage && options & SDWebImageRefreshCached) { + // force progressive off if image already cached but forced refreshing + downloaderOptions &= ~SDWebImageDownloaderProgressiveLoad; + // ignore image read from NSURLCache if image if cached but force refreshing + downloaderOptions |= SDWebImageDownloaderIgnoreCachedResponse; + } + + return [self downloadImageWithURL:url options:downloaderOptions context:context progress:progressBlock completed:completedBlock]; +} +#pragma clang diagnostic pop + +- (BOOL)shouldBlockFailedURLWithURL:(NSURL *)url error:(NSError *)error { + return [self shouldBlockFailedURLWithURL:url error:error options:0 context:nil]; +} + +- (BOOL)shouldBlockFailedURLWithURL:(NSURL *)url error:(NSError *)error options:(SDWebImageOptions)options context:(SDWebImageContext *)context { + BOOL shouldBlockFailedURL; + // Filter the error domain and check error codes + if ([error.domain isEqualToString:SDWebImageErrorDomain]) { + shouldBlockFailedURL = ( error.code == SDWebImageErrorInvalidURL + || error.code == SDWebImageErrorBadImageData); + } else if ([error.domain isEqualToString:NSURLErrorDomain]) { + shouldBlockFailedURL = ( error.code != NSURLErrorNotConnectedToInternet + && error.code != NSURLErrorCancelled + && error.code != NSURLErrorTimedOut + && error.code != NSURLErrorInternationalRoamingOff + && error.code != NSURLErrorDataNotAllowed + && error.code != NSURLErrorCannotFindHost + && error.code != NSURLErrorCannotConnectToHost + && error.code != NSURLErrorNetworkConnectionLost); + } else { + shouldBlockFailedURL = NO; + } + return shouldBlockFailedURL; +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderConfig.h b/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderConfig.h new file mode 100644 index 0000000..9d5e67b --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderConfig.h @@ -0,0 +1,113 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" + +/// Operation execution order +typedef NS_ENUM(NSInteger, SDWebImageDownloaderExecutionOrder) { + /** + * Default value. All download operations will execute in queue style (first-in-first-out). + */ + SDWebImageDownloaderFIFOExecutionOrder, + + /** + * All download operations will execute in stack style (last-in-first-out). + */ + SDWebImageDownloaderLIFOExecutionOrder +}; + +/** + The class contains all the config for image downloader + @note This class conform to NSCopying, make sure to add the property in `copyWithZone:` as well. + */ +@interface SDWebImageDownloaderConfig : NSObject + +/** + Gets the default downloader config used for shared instance or initialization when it does not provide any downloader config. Such as `SDWebImageDownloader.sharedDownloader`. + @note You can modify the property on default downloader config, which can be used for later created downloader instance. The already created downloader instance does not get affected. + */ +@property (nonatomic, class, readonly, nonnull) SDWebImageDownloaderConfig *defaultDownloaderConfig; + +/** + * The maximum number of concurrent downloads. + * Defaults to 6. + */ +@property (nonatomic, assign) NSInteger maxConcurrentDownloads; + +/** + * The timeout value (in seconds) for each download operation. + * Defaults to 15.0. + */ +@property (nonatomic, assign) NSTimeInterval downloadTimeout; + +/** + * The minimum interval about progress percent during network downloading. Which means the next progress callback and current progress callback's progress percent difference should be larger or equal to this value. However, the final finish download progress callback does not get effected. + * The value should be 0.0-1.0. + * @note If you're using progressive decoding feature, this will also effect the image refresh rate. + * @note This value may enhance the performance if you don't want progress callback too frequently. + * Defaults to 0, which means each time we receive the new data from URLSession, we callback the progressBlock immediately. + */ +@property (nonatomic, assign) double minimumProgressInterval; + +/** + * The custom session configuration in use by NSURLSession. If you don't provide one, we will use `defaultSessionConfiguration` instead. + * Defatuls to nil. + * @note This property does not support dynamic changes, means it's immutable after the downloader instance initialized. + */ +@property (nonatomic, strong, nullable) NSURLSessionConfiguration *sessionConfiguration; + +/** + * Gets/Sets a subclass of `SDWebImageDownloaderOperation` as the default + * `NSOperation` to be used each time SDWebImage constructs a request + * operation to download an image. + * Defaults to nil. + * @note Passing `NSOperation` to set as default. Passing `nil` will revert to `SDWebImageDownloaderOperation`. + */ +@property (nonatomic, assign, nullable) Class operationClass; + +/** + * Changes download operations execution order. + * Defaults to `SDWebImageDownloaderFIFOExecutionOrder`. + */ +@property (nonatomic, assign) SDWebImageDownloaderExecutionOrder executionOrder; + +/** + * Set the default URL credential to be set for request operations. + * Defaults to nil. + */ +@property (nonatomic, copy, nullable) NSURLCredential *urlCredential; + +/** + * Set username using for HTTP Basic authentication. + * Defaults to nil. + */ +@property (nonatomic, copy, nullable) NSString *username; + +/** + * Set password using for HTTP Basic authentication. + * Defaults to nil. + */ +@property (nonatomic, copy, nullable) NSString *password; + +/** + * Set the acceptable HTTP Response status code. The status code which beyond the range will mark the download operation failed. + * For example, if we config [200, 400) but server response is 503, the download will fail with error code `SDWebImageErrorInvalidDownloadStatusCode`. + * Defaults to [200,400). Nil means no validation at all. + */ +@property (nonatomic, copy, nullable) NSIndexSet *acceptableStatusCodes; + +/** + * Set the acceptable HTTP Response content type. The content type beyond the set will mark the download operation failed. + * For example, if we config ["image/png"] but server response is "application/json", the download will fail with error code `SDWebImageErrorInvalidDownloadContentType`. + * Normally you don't need this for image format detection because we use image's data file signature magic bytes: https://en.wikipedia.org/wiki/List_of_file_signatures + * Defaults to nil. Nil means no validation at all. + */ +@property (nonatomic, copy, nullable) NSSet *acceptableContentTypes; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderConfig.m b/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderConfig.m new file mode 100644 index 0000000..6738b34 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderConfig.m @@ -0,0 +1,60 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageDownloaderConfig.h" +#import "SDWebImageDownloaderOperation.h" + +static SDWebImageDownloaderConfig * _defaultDownloaderConfig; + +@implementation SDWebImageDownloaderConfig + ++ (SDWebImageDownloaderConfig *)defaultDownloaderConfig { + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + _defaultDownloaderConfig = [SDWebImageDownloaderConfig new]; + }); + return _defaultDownloaderConfig; +} + +- (instancetype)init { + self = [super init]; + if (self) { + _maxConcurrentDownloads = 6; + _downloadTimeout = 15.0; + _executionOrder = SDWebImageDownloaderFIFOExecutionOrder; + _acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)]; + } + return self; +} + +- (id)copyWithZone:(NSZone *)zone { + SDWebImageDownloaderConfig *config = [[[self class] allocWithZone:zone] init]; + config.maxConcurrentDownloads = self.maxConcurrentDownloads; + config.downloadTimeout = self.downloadTimeout; + config.minimumProgressInterval = self.minimumProgressInterval; + config.sessionConfiguration = [self.sessionConfiguration copyWithZone:zone]; + config.operationClass = self.operationClass; + config.executionOrder = self.executionOrder; + config.urlCredential = self.urlCredential; + config.username = self.username; + config.password = self.password; + config.acceptableStatusCodes = self.acceptableStatusCodes; + config.acceptableContentTypes = self.acceptableContentTypes; + + return config; +} + +- (void)setOperationClass:(Class)operationClass { + if (operationClass) { + NSAssert([operationClass isSubclassOfClass:[NSOperation class]] && [operationClass conformsToProtocol:@protocol(SDWebImageDownloaderOperation)], @"Custom downloader operation class must subclass NSOperation and conform to `SDWebImageDownloaderOperation` protocol"); + } + _operationClass = operationClass; +} + + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderDecryptor.h b/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderDecryptor.h new file mode 100644 index 0000000..69eee7a --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderDecryptor.h @@ -0,0 +1,52 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import +#import "SDWebImageCompat.h" + +typedef NSData * _Nullable (^SDWebImageDownloaderDecryptorBlock)(NSData * _Nonnull data, NSURLResponse * _Nullable response); + +/** +This is the protocol for downloader decryptor. Which decrypt the original encrypted data before decoding. Note progressive decoding is not compatible for decryptor. +We can use a block to specify the downloader decryptor. But Using protocol can make this extensible, and allow Swift user to use it easily instead of using `@convention(block)` to store a block into context options. +*/ +@protocol SDWebImageDownloaderDecryptor + +/// Decrypt the original download data and return a new data. You can use this to decrypt the data using your preferred algorithm. +/// @param data The original download data +/// @param response The URL response for data. If you modify the original URL response via response modifier, the modified version will be here. This arg is nullable. +/// @note If nil is returned, the image download will be marked as failed with error `SDWebImageErrorBadImageData` +- (nullable NSData *)decryptedDataWithData:(nonnull NSData *)data response:(nullable NSURLResponse *)response; + +@end + +/** +A downloader response modifier class with block. +*/ +@interface SDWebImageDownloaderDecryptor : NSObject + +/// Create the data decryptor with block +/// @param block A block to control decrypt logic +- (nonnull instancetype)initWithBlock:(nonnull SDWebImageDownloaderDecryptorBlock)block; + +/// Create the data decryptor with block +/// @param block A block to control decrypt logic ++ (nonnull instancetype)decryptorWithBlock:(nonnull SDWebImageDownloaderDecryptorBlock)block; + +- (nonnull instancetype)init NS_UNAVAILABLE; ++ (nonnull instancetype)new NS_UNAVAILABLE; + +@end + +/// Convenience way to create decryptor for common data encryption. +@interface SDWebImageDownloaderDecryptor (Conveniences) + +/// Base64 Encoded image data decryptor +@property (class, readonly, nonnull) SDWebImageDownloaderDecryptor *base64Decryptor; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderDecryptor.m b/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderDecryptor.m new file mode 100644 index 0000000..a3b75b2 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderDecryptor.m @@ -0,0 +1,55 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import "SDWebImageDownloaderDecryptor.h" + +@interface SDWebImageDownloaderDecryptor () + +@property (nonatomic, copy, nonnull) SDWebImageDownloaderDecryptorBlock block; + +@end + +@implementation SDWebImageDownloaderDecryptor + +- (instancetype)initWithBlock:(SDWebImageDownloaderDecryptorBlock)block { + self = [super init]; + if (self) { + self.block = block; + } + return self; +} + ++ (instancetype)decryptorWithBlock:(SDWebImageDownloaderDecryptorBlock)block { + SDWebImageDownloaderDecryptor *decryptor = [[SDWebImageDownloaderDecryptor alloc] initWithBlock:block]; + return decryptor; +} + +- (nullable NSData *)decryptedDataWithData:(nonnull NSData *)data response:(nullable NSURLResponse *)response { + if (!self.block) { + return nil; + } + return self.block(data, response); +} + +@end + +@implementation SDWebImageDownloaderDecryptor (Conveniences) + ++ (SDWebImageDownloaderDecryptor *)base64Decryptor { + static SDWebImageDownloaderDecryptor *decryptor; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + decryptor = [SDWebImageDownloaderDecryptor decryptorWithBlock:^NSData * _Nullable(NSData * _Nonnull data, NSURLResponse * _Nullable response) { + NSData *modifiedData = [[NSData alloc] initWithBase64EncodedData:data options:NSDataBase64DecodingIgnoreUnknownCharacters]; + return modifiedData; + }]; + }); + return decryptor; +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderOperation.h b/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderOperation.h new file mode 100644 index 0000000..aec9c93 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderOperation.h @@ -0,0 +1,191 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageDownloader.h" +#import "SDWebImageOperation.h" + +/** + Describes a downloader operation. If one wants to use a custom downloader op, it needs to inherit from `NSOperation` and conform to this protocol + For the description about these methods, see `SDWebImageDownloaderOperation` + @note If your custom operation class does not use `NSURLSession` at all, do not implement the optional methods and session delegate methods. + */ +@protocol SDWebImageDownloaderOperation +@required +- (nonnull instancetype)initWithRequest:(nullable NSURLRequest *)request + inSession:(nullable NSURLSession *)session + options:(SDWebImageDownloaderOptions)options; + +- (nonnull instancetype)initWithRequest:(nullable NSURLRequest *)request + inSession:(nullable NSURLSession *)session + options:(SDWebImageDownloaderOptions)options + context:(nullable SDWebImageContext *)context; + +- (nullable id)addHandlersForProgress:(nullable SDWebImageDownloaderProgressBlock)progressBlock + completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock; + +- (nullable id)addHandlersForProgress:(nullable SDWebImageDownloaderProgressBlock)progressBlock + completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock + decodeOptions:(nullable SDImageCoderOptions *)decodeOptions; + +- (BOOL)cancel:(nullable id)token; + +@property (strong, nonatomic, readonly, nullable) NSURLRequest *request; +@property (strong, nonatomic, readonly, nullable) NSURLResponse *response; + +@optional +@property (strong, nonatomic, readonly, nullable) NSURLSessionTask *dataTask; +@property (strong, nonatomic, readonly, nullable) NSURLSessionTaskMetrics *metrics API_AVAILABLE(macos(10.12), ios(10.0), watchos(3.0), tvos(10.0)); + +// These operation-level config was inherited from downloader. See `SDWebImageDownloaderConfig` for documentation. +@property (strong, nonatomic, nullable) NSURLCredential *credential; +@property (assign, nonatomic) double minimumProgressInterval; +@property (copy, nonatomic, nullable) NSIndexSet *acceptableStatusCodes; +@property (copy, nonatomic, nullable) NSSet *acceptableContentTypes; + +@end + + +/** + The download operation class for SDWebImageDownloader. + */ +@interface SDWebImageDownloaderOperation : NSOperation + +/** + * The request used by the operation's task. + */ +@property (strong, nonatomic, readonly, nullable) NSURLRequest *request; + +/** + * The response returned by the operation's task. + */ +@property (strong, nonatomic, readonly, nullable) NSURLResponse *response; + +/** + * The operation's task + */ +@property (strong, nonatomic, readonly, nullable) NSURLSessionTask *dataTask; + +/** + * The collected metrics from `-URLSession:task:didFinishCollectingMetrics:`. + * This can be used to collect the network metrics like download duration, DNS lookup duration, SSL handshake duration, etc. See Apple's documentation: https://developer.apple.com/documentation/foundation/urlsessiontaskmetrics + */ +@property (strong, nonatomic, readonly, nullable) NSURLSessionTaskMetrics *metrics API_AVAILABLE(macos(10.12), ios(10.0), watchos(3.0), tvos(10.0)); + +/** + * The credential used for authentication challenges in `-URLSession:task:didReceiveChallenge:completionHandler:`. + * + * This will be overridden by any shared credentials that exist for the username or password of the request URL, if present. + */ +@property (strong, nonatomic, nullable) NSURLCredential *credential; + +/** + * The minimum interval about progress percent during network downloading. Which means the next progress callback and current progress callback's progress percent difference should be larger or equal to this value. However, the final finish download progress callback does not get effected. + * The value should be 0.0-1.0. + * @note If you're using progressive decoding feature, this will also effect the image refresh rate. + * @note This value may enhance the performance if you don't want progress callback too frequently. + * Defaults to 0, which means each time we receive the new data from URLSession, we callback the progressBlock immediately. + */ +@property (assign, nonatomic) double minimumProgressInterval; + +/** + * Set the acceptable HTTP Response status code. The status code which beyond the range will mark the download operation failed. + * For example, if we config [200, 400) but server response is 503, the download will fail with error code `SDWebImageErrorInvalidDownloadStatusCode`. + * Defaults to [200,400). Nil means no validation at all. + */ +@property (copy, nonatomic, nullable) NSIndexSet *acceptableStatusCodes; + +/** + * Set the acceptable HTTP Response content type. The content type beyond the set will mark the download operation failed. + * For example, if we config ["image/png"] but server response is "application/json", the download will fail with error code `SDWebImageErrorInvalidDownloadContentType`. + * Normally you don't need this for image format detection because we use image's data file signature magic bytes: https://en.wikipedia.org/wiki/List_of_file_signatures + * Defaults to nil. Nil means no validation at all. + */ +@property (copy, nonatomic, nullable) NSSet *acceptableContentTypes; + +/** + * The options for the receiver. + */ +@property (assign, nonatomic, readonly) SDWebImageDownloaderOptions options; + +/** + * The context for the receiver. + */ +@property (copy, nonatomic, readonly, nullable) SDWebImageContext *context; + +/** + * Initializes a `SDWebImageDownloaderOperation` object + * + * @see SDWebImageDownloaderOperation + * + * @param request the URL request + * @param session the URL session in which this operation will run + * @param options downloader options + * + * @return the initialized instance + */ +- (nonnull instancetype)initWithRequest:(nullable NSURLRequest *)request + inSession:(nullable NSURLSession *)session + options:(SDWebImageDownloaderOptions)options; + +/** + * Initializes a `SDWebImageDownloaderOperation` object + * + * @see SDWebImageDownloaderOperation + * + * @param request the URL request + * @param session the URL session in which this operation will run + * @param options downloader options + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + * + * @return the initialized instance + */ +- (nonnull instancetype)initWithRequest:(nullable NSURLRequest *)request + inSession:(nullable NSURLSession *)session + options:(SDWebImageDownloaderOptions)options + context:(nullable SDWebImageContext *)context NS_DESIGNATED_INITIALIZER; + +/** + * Adds handlers for progress and completion. Returns a token that can be passed to -cancel: to cancel this set of + * callbacks. + * + * @param progressBlock the block executed when a new chunk of data arrives. + * @note the progress block is executed on a background queue + * @param completedBlock the block executed when the download is done. + * @note the completed block is executed on the main queue for success. If errors are found, there is a chance the block will be executed on a background queue + * + * @return the token to use to cancel this set of handlers + */ +- (nullable id)addHandlersForProgress:(nullable SDWebImageDownloaderProgressBlock)progressBlock + completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock; + +/** + * Adds handlers for progress and completion, and optional decode options (which need another image other than the initial one). Returns a token that can be passed to -cancel: to cancel this set of + * callbacks. + * + * @param progressBlock the block executed when a new chunk of data arrives. + * @note the progress block is executed on a background queue + * @param completedBlock the block executed when the download is done. + * @note the completed block is executed on the main queue for success. If errors are found, there is a chance the block will be executed on a background queue + * @param decodeOptions The optional decode options, used when in thumbnail decoding for current completion block callback. For example, request and then , we may callback these two completion block with different size. + * @return the token to use to cancel this set of handlers + */ +- (nullable id)addHandlersForProgress:(nullable SDWebImageDownloaderProgressBlock)progressBlock + completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock + decodeOptions:(nullable SDImageCoderOptions *)decodeOptions; + +/** + * Cancels a set of callbacks. Once all callbacks are canceled, the operation is cancelled. + * + * @param token the token representing a set of callbacks to cancel + * + * @return YES if the operation was stopped because this was the last token to be canceled. NO otherwise. + */ +- (BOOL)cancel:(nullable id)token; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderOperation.m b/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderOperation.m new file mode 100644 index 0000000..5b40004 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderOperation.m @@ -0,0 +1,760 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageDownloaderOperation.h" +#import "SDWebImageError.h" +#import "SDInternalMacros.h" +#import "SDWebImageDownloaderResponseModifier.h" +#import "SDWebImageDownloaderDecryptor.h" +#import "SDImageCacheDefine.h" +#import "SDCallbackQueue.h" + +// A handler to represent individual request +@interface SDWebImageDownloaderOperationToken : NSObject + +@property (nonatomic, copy, nullable) SDWebImageDownloaderCompletedBlock completedBlock; +@property (nonatomic, copy, nullable) SDWebImageDownloaderProgressBlock progressBlock; +@property (nonatomic, copy, nullable) SDImageCoderOptions *decodeOptions; + +@end + +@implementation SDWebImageDownloaderOperationToken + +- (BOOL)isEqual:(id)other { + if (nil == other) { + return NO; + } + if (self == other) { + return YES; + } + if (![other isKindOfClass:[self class]]) { + return NO; + } + SDWebImageDownloaderOperationToken *object = (SDWebImageDownloaderOperationToken *)other; + // warn: only compare decodeOptions, ignore pointer, use `removeObjectIdenticalTo` + BOOL result = [self.decodeOptions isEqualToDictionary:object.decodeOptions]; + return result; +} + +@end + +@interface SDWebImageDownloaderOperation () + +@property (strong, nonatomic, nonnull) NSMutableArray *callbackTokens; + +@property (assign, nonatomic, readwrite) SDWebImageDownloaderOptions options; +@property (copy, nonatomic, readwrite, nullable) SDWebImageContext *context; + +@property (assign, nonatomic, getter = isExecuting) BOOL executing; +@property (assign, nonatomic, getter = isFinished) BOOL finished; +@property (strong, nonatomic, nullable) NSMutableData *imageData; +@property (copy, nonatomic, nullable) NSData *cachedData; // for `SDWebImageDownloaderIgnoreCachedResponse` +@property (assign, nonatomic) NSUInteger expectedSize; // may be 0 +@property (assign, nonatomic) NSUInteger receivedSize; +@property (strong, nonatomic, nullable, readwrite) NSURLResponse *response; +@property (strong, nonatomic, nullable) NSError *responseError; +@property (assign, nonatomic) double previousProgress; // previous progress percent + +@property (assign, nonatomic, getter = isDownloadCompleted) BOOL downloadCompleted; + +@property (strong, nonatomic, nullable) id responseModifier; // modify original URLResponse +@property (strong, nonatomic, nullable) id decryptor; // decrypt image data + +// This is weak because it is injected by whoever manages this session. If this gets nil-ed out, we won't be able to run +// the task associated with this operation +@property (weak, nonatomic, nullable) NSURLSession *unownedSession; +// This is set if we're using not using an injected NSURLSession. We're responsible of invalidating this one +@property (strong, nonatomic, nullable) NSURLSession *ownedSession; + +@property (strong, nonatomic, readwrite, nullable) NSURLSessionTask *dataTask; + +@property (strong, nonatomic, readwrite, nullable) NSURLSessionTaskMetrics *metrics API_AVAILABLE(macos(10.12), ios(10.0), watchos(3.0), tvos(10.0)); + +@property (strong, nonatomic, nonnull) NSOperationQueue *coderQueue; // the serial operation queue to do image decoding + +@property (strong, nonatomic, nonnull) NSMapTable *imageMap; // each variant of image is weak-referenced to avoid too many re-decode during downloading +#if SD_UIKIT +@property (assign, nonatomic) UIBackgroundTaskIdentifier backgroundTaskId; +#endif + +@end + +@implementation SDWebImageDownloaderOperation + +@synthesize executing = _executing; +@synthesize finished = _finished; + +- (nonnull instancetype)init { + return [self initWithRequest:nil inSession:nil options:0]; +} + +- (instancetype)initWithRequest:(NSURLRequest *)request inSession:(NSURLSession *)session options:(SDWebImageDownloaderOptions)options { + return [self initWithRequest:request inSession:session options:options context:nil]; +} + +- (nonnull instancetype)initWithRequest:(nullable NSURLRequest *)request + inSession:(nullable NSURLSession *)session + options:(SDWebImageDownloaderOptions)options + context:(nullable SDWebImageContext *)context { + if ((self = [super init])) { + _request = [request copy]; + _options = options; + _context = [context copy]; + _callbackTokens = [NSMutableArray new]; + _responseModifier = context[SDWebImageContextDownloadResponseModifier]; + _decryptor = context[SDWebImageContextDownloadDecryptor]; + _executing = NO; + _finished = NO; + _expectedSize = 0; + _unownedSession = session; + _downloadCompleted = NO; + _coderQueue = [[NSOperationQueue alloc] init]; + _coderQueue.maxConcurrentOperationCount = 1; + _coderQueue.name = @"com.hackemist.SDWebImageDownloaderOperation.coderQueue"; + _imageMap = [[NSMapTable alloc] initWithKeyOptions:NSPointerFunctionsStrongMemory valueOptions:NSPointerFunctionsWeakMemory capacity:1]; +#if SD_UIKIT + _backgroundTaskId = UIBackgroundTaskInvalid; +#endif + } + return self; +} + +- (nullable id)addHandlersForProgress:(nullable SDWebImageDownloaderProgressBlock)progressBlock + completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock { + return [self addHandlersForProgress:progressBlock completed:completedBlock decodeOptions:nil]; +} + +- (nullable id)addHandlersForProgress:(nullable SDWebImageDownloaderProgressBlock)progressBlock + completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock + decodeOptions:(nullable SDImageCoderOptions *)decodeOptions { + if (!completedBlock && !progressBlock && !decodeOptions) return nil; + SDWebImageDownloaderOperationToken *token = [SDWebImageDownloaderOperationToken new]; + token.completedBlock = completedBlock; + token.progressBlock = progressBlock; + token.decodeOptions = decodeOptions; + @synchronized (self) { + [self.callbackTokens addObject:token]; + } + + return token; +} + +- (BOOL)cancel:(nullable id)token { + if (![token isKindOfClass:SDWebImageDownloaderOperationToken.class]) return NO; + + BOOL shouldCancel = NO; + @synchronized (self) { + NSArray *tokens = self.callbackTokens; + if (tokens.count == 1 && [tokens indexOfObjectIdenticalTo:token] != NSNotFound) { + shouldCancel = YES; + } + } + if (shouldCancel) { + // Cancel operation running and callback last token's completion block + [self cancel]; + } else { + // Only callback this token's completion block + @synchronized (self) { + [self.callbackTokens removeObjectIdenticalTo:token]; + } + [self callCompletionBlockWithToken:token image:nil imageData:nil error:[NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorCancelled userInfo:@{NSLocalizedDescriptionKey : @"Operation cancelled by user during sending the request"}] finished:YES]; + } + return shouldCancel; +} + +- (void)start { + @synchronized (self) { + if (self.isCancelled) { + if (!self.isFinished) self.finished = YES; + // Operation cancelled by user before sending the request + [self callCompletionBlocksWithError:[NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorCancelled userInfo:@{NSLocalizedDescriptionKey : @"Operation cancelled by user before sending the request"}]]; + [self reset]; + return; + } + +#if SD_UIKIT + Class UIApplicationClass = NSClassFromString(@"UIApplication"); + BOOL hasApplication = UIApplicationClass && [UIApplicationClass respondsToSelector:@selector(sharedApplication)]; + if (hasApplication && [self shouldContinueWhenAppEntersBackground]) { + __weak typeof(self) wself = self; + UIApplication * app = [UIApplicationClass performSelector:@selector(sharedApplication)]; + self.backgroundTaskId = [app beginBackgroundTaskWithExpirationHandler:^{ + [wself cancel]; + }]; + } +#endif + NSURLSession *session = self.unownedSession; + if (!session) { + NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration]; + sessionConfig.timeoutIntervalForRequest = 15; + + /** + * Create the session for this task + * We send nil as delegate queue so that the session creates a serial operation queue for performing all delegate + * method calls and completion handler calls. + */ + session = [NSURLSession sessionWithConfiguration:sessionConfig + delegate:self + delegateQueue:nil]; + self.ownedSession = session; + } + + if (self.options & SDWebImageDownloaderIgnoreCachedResponse) { + // Grab the cached data for later check + NSURLCache *URLCache = session.configuration.URLCache; + if (!URLCache) { + URLCache = [NSURLCache sharedURLCache]; + } + NSCachedURLResponse *cachedResponse; + // NSURLCache's `cachedResponseForRequest:` is not thread-safe, see https://developer.apple.com/documentation/foundation/nsurlcache#2317483 + @synchronized (URLCache) { + cachedResponse = [URLCache cachedResponseForRequest:self.request]; + } + if (cachedResponse) { + self.cachedData = cachedResponse.data; + self.response = cachedResponse.response; + } + } + + if (!session.delegate) { + // Session been invalid and has no delegate at all + [self callCompletionBlocksWithError:[NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorInvalidDownloadOperation userInfo:@{NSLocalizedDescriptionKey : @"Session delegate is nil and invalid"}]]; + [self reset]; + return; + } + + self.dataTask = [session dataTaskWithRequest:self.request]; + self.executing = YES; + } + + if (self.dataTask) { + if (self.options & SDWebImageDownloaderHighPriority) { + self.dataTask.priority = NSURLSessionTaskPriorityHigh; + } else if (self.options & SDWebImageDownloaderLowPriority) { + self.dataTask.priority = NSURLSessionTaskPriorityLow; + } else { + self.dataTask.priority = NSURLSessionTaskPriorityDefault; + } + [self.dataTask resume]; + NSArray *tokens; + @synchronized (self) { + tokens = [self.callbackTokens copy]; + } + for (SDWebImageDownloaderOperationToken *token in tokens) { + if (token.progressBlock) { + token.progressBlock(0, NSURLResponseUnknownLength, self.request.URL); + } + } + __block typeof(self) strongSelf = self; + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStartNotification object:strongSelf]; + }); + } else { + if (!self.isFinished) self.finished = YES; + [self callCompletionBlocksWithError:[NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorInvalidDownloadOperation userInfo:@{NSLocalizedDescriptionKey : @"Task can't be initialized"}]]; + [self reset]; + } +} + +- (void)cancel { + @synchronized (self) { + [self cancelInternal]; + } +} + +- (void)cancelInternal { + if (self.isFinished) return; + [super cancel]; + + __block typeof(self) strongSelf = self; + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:strongSelf]; + }); + + if (self.dataTask) { + // Cancel the URLSession, `URLSession:task:didCompleteWithError:` delegate callback will be ignored + [self.dataTask cancel]; + self.dataTask = nil; + } + + // NSOperation disallow setFinished=YES **before** operation's start method been called + // We check for the initialized status, which is isExecuting == NO && isFinished = NO + // Ony update for non-intialized status, which is !(isExecuting == NO && isFinished = NO), or if (self.isExecuting || self.isFinished) {...} + if (self.isExecuting || self.isFinished) { + if (self.isExecuting) self.executing = NO; + if (!self.isFinished) self.finished = YES; + } + + // Operation cancelled by user during sending the request + [self callCompletionBlocksWithError:[NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorCancelled userInfo:@{NSLocalizedDescriptionKey : @"Operation cancelled by user during sending the request"}]]; + + [self reset]; +} + +- (void)done { + self.finished = YES; + self.executing = NO; + [self reset]; +} + +- (void)reset { + @synchronized (self) { + [self.callbackTokens removeAllObjects]; + self.dataTask = nil; + + if (self.ownedSession) { + [self.ownedSession invalidateAndCancel]; + self.ownedSession = nil; + } + +#if SD_UIKIT + if (self.backgroundTaskId != UIBackgroundTaskInvalid) { + // If backgroundTaskId != UIBackgroundTaskInvalid, sharedApplication is always exist + UIApplication * app = [UIApplication performSelector:@selector(sharedApplication)]; + [app endBackgroundTask:self.backgroundTaskId]; + self.backgroundTaskId = UIBackgroundTaskInvalid; + } +#endif + } +} + +- (void)setFinished:(BOOL)finished { + [self willChangeValueForKey:@"isFinished"]; + _finished = finished; + [self didChangeValueForKey:@"isFinished"]; +} + +- (void)setExecuting:(BOOL)executing { + [self willChangeValueForKey:@"isExecuting"]; + _executing = executing; + [self didChangeValueForKey:@"isExecuting"]; +} + +- (BOOL)isAsynchronous { + return YES; +} + +// Check for unprocessed tokens. +// if all tokens have been processed call [self done]. +- (void)checkDoneWithImageData:(NSData *)imageData + finishedTokens:(NSArray *)finishedTokens { + @synchronized (self) { + NSMutableArray *tokens = [self.callbackTokens mutableCopy]; + [finishedTokens enumerateObjectsUsingBlock:^(SDWebImageDownloaderOperationToken * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { + [tokens removeObjectIdenticalTo:obj]; + }]; + if (tokens.count == 0) { + [self done]; + } else { + // If there are new tokens added during the decoding operation, the decoding operation is supplemented with these new tokens. + [self startCoderOperationWithImageData:imageData pendingTokens:tokens finishedTokens:finishedTokens]; + } + } +} + +- (void)startCoderOperationWithImageData:(NSData *)imageData + pendingTokens:(NSArray *)pendingTokens + finishedTokens:(NSArray *)finishedTokens { + @weakify(self); + for (SDWebImageDownloaderOperationToken *token in pendingTokens) { + [self.coderQueue addOperationWithBlock:^{ + @strongify(self); + if (!self) { + return; + } + UIImage *image; + // check if we already decode this variant of image for current callback + if (token.decodeOptions) { + image = [self.imageMap objectForKey:token.decodeOptions]; + } + if (!image) { + // check if we already use progressive decoding, use that to produce faster decoding + id progressiveCoder = SDImageLoaderGetProgressiveCoder(self); + SDWebImageOptions options = [[self class] imageOptionsFromDownloaderOptions:self.options]; + SDWebImageContext *context; + if (token.decodeOptions) { + SDWebImageMutableContext *mutableContext = [NSMutableDictionary dictionaryWithDictionary:self.context]; + SDSetDecodeOptionsToContext(mutableContext, &options, token.decodeOptions); + context = [mutableContext copy]; + } else { + context = self.context; + } + if (progressiveCoder) { + image = SDImageLoaderDecodeProgressiveImageData(imageData, self.request.URL, YES, self, options, context); + } else { + image = SDImageLoaderDecodeImageData(imageData, self.request.URL, options, context); + } + if (image && token.decodeOptions) { + [self.imageMap setObject:image forKey:token.decodeOptions]; + } + } + CGSize imageSize = image.size; + if (imageSize.width == 0 || imageSize.height == 0) { + NSString *description = image == nil ? @"Downloaded image decode failed" : @"Downloaded image has 0 pixels"; + NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorBadImageData userInfo:@{NSLocalizedDescriptionKey : description}]; + [self callCompletionBlockWithToken:token image:nil imageData:nil error:error finished:YES]; + } else { + [self callCompletionBlockWithToken:token image:image imageData:imageData error:nil finished:YES]; + } + }]; + } + // call [self done] after all completed block was dispatched + dispatch_block_t doneBlock = ^{ + @strongify(self); + if (!self) { + return; + } + // Check for new tokens added during the decode operation. + [self checkDoneWithImageData:imageData + finishedTokens:[finishedTokens arrayByAddingObjectsFromArray:pendingTokens]]; + }; + if (@available(iOS 13, tvOS 13, macOS 10.15, watchOS 6, *)) { + // seems faster than `addOperationWithBlock` + [self.coderQueue addBarrierBlock:doneBlock]; + } else { + // serial queue, this does the same effect in semantics + [self.coderQueue addOperationWithBlock:doneBlock]; + } + +} + +#pragma mark NSURLSessionDataDelegate + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask +didReceiveResponse:(NSURLResponse *)response + completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler { + NSURLSessionResponseDisposition disposition = NSURLSessionResponseAllow; + + // Check response modifier, if return nil, will marked as cancelled. + BOOL valid = YES; + if (self.responseModifier && response) { + response = [self.responseModifier modifiedResponseWithResponse:response]; + if (!response) { + valid = NO; + self.responseError = [NSError errorWithDomain:SDWebImageErrorDomain + code:SDWebImageErrorInvalidDownloadResponse + userInfo:@{NSLocalizedDescriptionKey : @"Download marked as failed because response is nil"}]; + } + } + + NSInteger expected = (NSInteger)response.expectedContentLength; + expected = expected > 0 ? expected : 0; + self.expectedSize = expected; + self.response = response; + + // Check status code valid (defaults [200,400)) + NSInteger statusCode = [response isKindOfClass:NSHTTPURLResponse.class] ? ((NSHTTPURLResponse *)response).statusCode : 0; + BOOL statusCodeValid = YES; + if (valid && statusCode > 0 && self.acceptableStatusCodes) { + statusCodeValid = [self.acceptableStatusCodes containsIndex:statusCode]; + } + if (!statusCodeValid) { + valid = NO; + self.responseError = [NSError errorWithDomain:SDWebImageErrorDomain + code:SDWebImageErrorInvalidDownloadStatusCode + userInfo:@{NSLocalizedDescriptionKey : [NSString stringWithFormat:@"Download marked as failed because of invalid response status code %ld", (long)statusCode], + SDWebImageErrorDownloadStatusCodeKey : @(statusCode), + SDWebImageErrorDownloadResponseKey : response}]; + } + // Check content type valid (defaults nil) + NSString *contentType = [response isKindOfClass:NSHTTPURLResponse.class] ? ((NSHTTPURLResponse *)response).MIMEType : nil; + BOOL contentTypeValid = YES; + if (valid && contentType.length > 0 && self.acceptableContentTypes) { + contentTypeValid = [self.acceptableContentTypes containsObject:contentType]; + } + if (!contentTypeValid) { + valid = NO; + self.responseError = [NSError errorWithDomain:SDWebImageErrorDomain + code:SDWebImageErrorInvalidDownloadContentType + userInfo:@{NSLocalizedDescriptionKey : [NSString stringWithFormat:@"Download marked as failed because of invalid response content type %@", contentType], + SDWebImageErrorDownloadContentTypeKey : contentType, + SDWebImageErrorDownloadResponseKey : response}]; + } + //'304 Not Modified' is an exceptional one + //URLSession current behavior will return 200 status code when the server respond 304 and URLCache hit. But this is not a standard behavior and we just add a check + if (valid && statusCode == 304 && !self.cachedData) { + valid = NO; + self.responseError = [NSError errorWithDomain:SDWebImageErrorDomain + code:SDWebImageErrorCacheNotModified + userInfo:@{NSLocalizedDescriptionKey: @"Download response status code is 304 not modified and ignored", + SDWebImageErrorDownloadResponseKey : response}]; + } + + if (valid) { + NSArray *tokens; + @synchronized (self) { + tokens = [self.callbackTokens copy]; + } + for (SDWebImageDownloaderOperationToken *token in tokens) { + if (token.progressBlock) { + token.progressBlock(0, expected, self.request.URL); + } + } + } else { + // Status code invalid and marked as cancelled. Do not call `[self.dataTask cancel]` which may mass up URLSession life cycle + disposition = NSURLSessionResponseCancel; + } + __block typeof(self) strongSelf = self; + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadReceiveResponseNotification object:strongSelf]; + }); + + if (completionHandler) { + completionHandler(disposition); + } +} + +- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { + if (!self.imageData) { + self.imageData = [[NSMutableData alloc] initWithCapacity:self.expectedSize]; + } + [self.imageData appendData:data]; + + self.receivedSize = self.imageData.length; + NSArray *tokens; + @synchronized (self) { + tokens = [self.callbackTokens copy]; + } + if (self.expectedSize == 0) { + // Unknown expectedSize, immediately call progressBlock and return + for (SDWebImageDownloaderOperationToken *token in tokens) { + if (token.progressBlock) { + token.progressBlock(self.receivedSize, self.expectedSize, self.request.URL); + } + } + return; + } + + // Get the finish status + BOOL finished = (self.receivedSize >= self.expectedSize); + // Get the current progress + double currentProgress = (double)self.receivedSize / (double)self.expectedSize; + double previousProgress = self.previousProgress; + double progressInterval = currentProgress - previousProgress; + // Check if we need callback progress + if (!finished && (progressInterval < self.minimumProgressInterval)) { + return; + } + self.previousProgress = currentProgress; + + // Using data decryptor will disable the progressive decoding, since there are no support for progressive decrypt + BOOL supportProgressive = (self.options & SDWebImageDownloaderProgressiveLoad) && !self.decryptor; + // When multiple thumbnail decoding use different size, this progressive decoding will cause issue because each callback assume called with different size's image, can not share the same decoding part + // We currently only pick the first thumbnail size, see #3423 talks + // Progressive decoding Only decode partial image, full image in `URLSession:task:didCompleteWithError:` + if (supportProgressive && !finished) { + // Get the image data + NSData *imageData = self.imageData; + + // keep maximum one progressive decode process during download + if (imageData && self.coderQueue.operationCount == 0) { + // NSOperation have autoreleasepool, don't need to create extra one + @weakify(self); + [self.coderQueue addOperationWithBlock:^{ + @strongify(self); + if (!self) { + return; + } + // When cancelled or transfer finished (`didCompleteWithError`), cancel the progress callback, only completed block is called and enough + @synchronized (self) { + if (self.isCancelled || self.isDownloadCompleted) { + return; + } + } + UIImage *image = SDImageLoaderDecodeProgressiveImageData(imageData, self.request.URL, NO, self, [[self class] imageOptionsFromDownloaderOptions:self.options], self.context); + if (image) { + // We do not keep the progressive decoding image even when `finished`=YES. Because they are for view rendering but not take full function from downloader options. And some coders implementation may not keep consistent between progressive decoding and normal decoding. + + [self callCompletionBlocksWithImage:image imageData:nil error:nil finished:NO]; + } + }]; + } + } + + for (SDWebImageDownloaderOperationToken *token in tokens) { + if (token.progressBlock) { + token.progressBlock(self.receivedSize, self.expectedSize, self.request.URL); + } + } +} + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask + willCacheResponse:(NSCachedURLResponse *)proposedResponse + completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler { + + NSCachedURLResponse *cachedResponse = proposedResponse; + + if (!(self.options & SDWebImageDownloaderUseNSURLCache)) { + // Prevents caching of responses + cachedResponse = nil; + } + if (completionHandler) { + completionHandler(cachedResponse); + } +} + +#pragma mark NSURLSessionTaskDelegate + +- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { + // If we already cancel the operation or anything mark the operation finished, don't callback twice + if (self.isFinished) return; + + self.downloadCompleted = YES; + + NSArray *tokens; + @synchronized (self) { + tokens = [self.callbackTokens copy]; + self.dataTask = nil; + __block typeof(self) strongSelf = self; + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:strongSelf]; + if (!error) { + [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadFinishNotification object:strongSelf]; + } + }); + } + + // make sure to call `[self done]` to mark operation as finished + if (error) { + // custom error instead of URLSession error + if (self.responseError) { + error = self.responseError; + } + [self callCompletionBlocksWithError:error]; + [self done]; + } else { + if (tokens.count > 0) { + NSData *imageData = self.imageData; + // data decryptor + if (imageData && self.decryptor) { + imageData = [self.decryptor decryptedDataWithData:imageData response:self.response]; + } + if (imageData) { + /** if you specified to only use cached data via `SDWebImageDownloaderIgnoreCachedResponse`, + * then we should check if the cached data is equal to image data + */ + if (self.options & SDWebImageDownloaderIgnoreCachedResponse && [self.cachedData isEqualToData:imageData]) { + self.responseError = [NSError errorWithDomain:SDWebImageErrorDomain + code:SDWebImageErrorCacheNotModified + userInfo:@{NSLocalizedDescriptionKey : @"Downloaded image is not modified and ignored", + SDWebImageErrorDownloadResponseKey : self.response}]; + // call completion block with not modified error + [self callCompletionBlocksWithError:self.responseError]; + [self done]; + } else { + // decode the image in coder queue, cancel all previous decoding process + [self.coderQueue cancelAllOperations]; + [self startCoderOperationWithImageData:imageData + pendingTokens:tokens + finishedTokens:@[]]; + } + } else { + [self callCompletionBlocksWithError:[NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorBadImageData userInfo:@{NSLocalizedDescriptionKey : @"Image data is nil"}]]; + [self done]; + } + } else { + [self done]; + } + } +} + +- (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 ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { + if (!(self.options & SDWebImageDownloaderAllowInvalidSSLCertificates)) { + disposition = NSURLSessionAuthChallengePerformDefaultHandling; + } else { + credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; + disposition = NSURLSessionAuthChallengeUseCredential; + } + } else { + if (challenge.previousFailureCount == 0) { + if (self.credential) { + credential = self.credential; + disposition = NSURLSessionAuthChallengeUseCredential; + } else { + // Web Server like Nginx can set `ssl_verify_client` to optional but not always on + // We'd better use default handling here + disposition = NSURLSessionAuthChallengePerformDefaultHandling; + } + } else { + disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge; + } + } + + if (completionHandler) { + completionHandler(disposition, credential); + } +} + +- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didFinishCollectingMetrics:(NSURLSessionTaskMetrics *)metrics API_AVAILABLE(macos(10.12), ios(10.0), watchos(3.0), tvos(10.0)) { + self.metrics = metrics; +} + +#pragma mark Helper methods +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" ++ (SDWebImageOptions)imageOptionsFromDownloaderOptions:(SDWebImageDownloaderOptions)downloadOptions { + SDWebImageOptions options = 0; + if (downloadOptions & SDWebImageDownloaderScaleDownLargeImages) options |= SDWebImageScaleDownLargeImages; + if (downloadOptions & SDWebImageDownloaderDecodeFirstFrameOnly) options |= SDWebImageDecodeFirstFrameOnly; + if (downloadOptions & SDWebImageDownloaderPreloadAllFrames) options |= SDWebImagePreloadAllFrames; + if (downloadOptions & SDWebImageDownloaderAvoidDecodeImage) options |= SDWebImageAvoidDecodeImage; + if (downloadOptions & SDWebImageDownloaderMatchAnimatedImageClass) options |= SDWebImageMatchAnimatedImageClass; + + return options; +} +#pragma clang diagnostic pop + +- (BOOL)shouldContinueWhenAppEntersBackground { + return SD_OPTIONS_CONTAINS(self.options, SDWebImageDownloaderContinueInBackground); +} + +- (void)callCompletionBlocksWithError:(nullable NSError *)error { + [self callCompletionBlocksWithImage:nil imageData:nil error:error finished:YES]; +} + +- (void)callCompletionBlocksWithImage:(nullable UIImage *)image + imageData:(nullable NSData *)imageData + error:(nullable NSError *)error + finished:(BOOL)finished { + NSArray *tokens; + @synchronized (self) { + tokens = [self.callbackTokens copy]; + } + for (SDWebImageDownloaderOperationToken *token in tokens) { + SDWebImageDownloaderCompletedBlock completedBlock = token.completedBlock; + if (completedBlock) { + SDCallbackQueue *queue = self.context[SDWebImageContextCallbackQueue]; + [(queue ?: SDCallbackQueue.mainQueue) async:^{ + completedBlock(image, imageData, error, finished); + }]; + } + } +} + +- (void)callCompletionBlockWithToken:(nonnull SDWebImageDownloaderOperationToken *)token + image:(nullable UIImage *)image + imageData:(nullable NSData *)imageData + error:(nullable NSError *)error + finished:(BOOL)finished { + SDWebImageDownloaderCompletedBlock completedBlock = token.completedBlock; + if (completedBlock) { + SDCallbackQueue *queue = self.context[SDWebImageContextCallbackQueue]; + [(queue ?: SDCallbackQueue.mainQueue) async:^{ + completedBlock(image, imageData, error, finished); + }]; + } +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderRequestModifier.h b/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderRequestModifier.h new file mode 100644 index 0000000..9400997 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderRequestModifier.h @@ -0,0 +1,72 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" + +typedef NSURLRequest * _Nullable (^SDWebImageDownloaderRequestModifierBlock)(NSURLRequest * _Nonnull request); + +/** + This is the protocol for downloader request modifier. + We can use a block to specify the downloader request modifier. But Using protocol can make this extensible, and allow Swift user to use it easily instead of using `@convention(block)` to store a block into context options. + */ +@protocol SDWebImageDownloaderRequestModifier + +/// Modify the original URL request and return a new one instead. You can modify the HTTP header, cachePolicy, etc for this URL. +/// @param request The original URL request for image loading +/// @note If return nil, the URL request will be cancelled. +- (nullable NSURLRequest *)modifiedRequestWithRequest:(nonnull NSURLRequest *)request; + +@end + +/** + A downloader request modifier class with block. + */ +@interface SDWebImageDownloaderRequestModifier : NSObject + +/// Create the request modifier with block +/// @param block A block to control modifier logic +- (nonnull instancetype)initWithBlock:(nonnull SDWebImageDownloaderRequestModifierBlock)block; + +/// Create the request modifier with block +/// @param block A block to control modifier logic ++ (nonnull instancetype)requestModifierWithBlock:(nonnull SDWebImageDownloaderRequestModifierBlock)block; + +- (nonnull instancetype)init NS_UNAVAILABLE; ++ (nonnull instancetype)new NS_UNAVAILABLE; + +@end + +/** +A convenient request modifier to provide the HTTP request including HTTP Method, Headers and Body. +*/ +@interface SDWebImageDownloaderRequestModifier (Conveniences) + +/// Create the request modifier with HTTP Method. +/// @param method HTTP Method, nil means to GET. +/// @note This is for convenience, if you need code to control the logic, use block API instead. +- (nonnull instancetype)initWithMethod:(nullable NSString *)method; + +/// Create the request modifier with HTTP Headers. +/// @param headers HTTP Headers. Case insensitive according to HTTP/1.1(HTTP/2) standard. The headers will override the same fields from original request. +/// @note This is for convenience, if you need code to control the logic, use block API instead. +- (nonnull instancetype)initWithHeaders:(nullable NSDictionary *)headers; + +/// Create the request modifier with HTTP Body. +/// @param body HTTP Body. +/// @note This is for convenience, if you need code to control the logic, use block API instead. +- (nonnull instancetype)initWithBody:(nullable NSData *)body; + +/// Create the request modifier with HTTP Method, Headers and Body. +/// @param method HTTP Method, nil means to GET. +/// @param headers HTTP Headers. Case insensitive according to HTTP/1.1(HTTP/2) standard. The headers will override the same fields from original request. +/// @param body HTTP Body. +/// @note This is for convenience, if you need code to control the logic, use block API instead. +- (nonnull instancetype)initWithMethod:(nullable NSString *)method headers:(nullable NSDictionary *)headers body:(nullable NSData *)body; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderRequestModifier.m b/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderRequestModifier.m new file mode 100644 index 0000000..c12c84f --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderRequestModifier.m @@ -0,0 +1,71 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageDownloaderRequestModifier.h" + +@interface SDWebImageDownloaderRequestModifier () + +@property (nonatomic, copy, nonnull) SDWebImageDownloaderRequestModifierBlock block; + +@end + +@implementation SDWebImageDownloaderRequestModifier + +- (instancetype)initWithBlock:(SDWebImageDownloaderRequestModifierBlock)block { + self = [super init]; + if (self) { + self.block = block; + } + return self; +} + ++ (instancetype)requestModifierWithBlock:(SDWebImageDownloaderRequestModifierBlock)block { + SDWebImageDownloaderRequestModifier *requestModifier = [[SDWebImageDownloaderRequestModifier alloc] initWithBlock:block]; + return requestModifier; +} + +- (NSURLRequest *)modifiedRequestWithRequest:(NSURLRequest *)request { + if (!self.block) { + return nil; + } + return self.block(request); +} + +@end + +@implementation SDWebImageDownloaderRequestModifier (Conveniences) + +- (instancetype)initWithMethod:(NSString *)method { + return [self initWithMethod:method headers:nil body:nil]; +} + +- (instancetype)initWithHeaders:(NSDictionary *)headers { + return [self initWithMethod:nil headers:headers body:nil]; +} + +- (instancetype)initWithBody:(NSData *)body { + return [self initWithMethod:nil headers:nil body:body]; +} + +- (instancetype)initWithMethod:(NSString *)method headers:(NSDictionary *)headers body:(NSData *)body { + method = method ? [method copy] : @"GET"; + headers = [headers copy]; + body = [body copy]; + return [self initWithBlock:^NSURLRequest * _Nullable(NSURLRequest * _Nonnull request) { + NSMutableURLRequest *mutableRequest = [request mutableCopy]; + mutableRequest.HTTPMethod = method; + mutableRequest.HTTPBody = body; + for (NSString *header in headers) { + NSString *value = headers[header]; + [mutableRequest setValue:value forHTTPHeaderField:header]; + } + return [mutableRequest copy]; + }]; +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderResponseModifier.h b/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderResponseModifier.h new file mode 100644 index 0000000..009e6a1 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderResponseModifier.h @@ -0,0 +1,72 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" + +typedef NSURLResponse * _Nullable (^SDWebImageDownloaderResponseModifierBlock)(NSURLResponse * _Nonnull response); + +/** + This is the protocol for downloader response modifier. + We can use a block to specify the downloader response modifier. But Using protocol can make this extensible, and allow Swift user to use it easily instead of using `@convention(block)` to store a block into context options. + */ +@protocol SDWebImageDownloaderResponseModifier + +/// Modify the original URL response and return a new response. You can use this to check MIME-Type, mock server response, etc. +/// @param response The original URL response, note for HTTP request it's actually a `NSHTTPURLResponse` instance +/// @note If nil is returned, the image download will marked as cancelled with error `SDWebImageErrorInvalidDownloadResponse` +- (nullable NSURLResponse *)modifiedResponseWithResponse:(nonnull NSURLResponse *)response; + +@end + +/** + A downloader response modifier class with block. + */ +@interface SDWebImageDownloaderResponseModifier : NSObject + +/// Create the response modifier with block +/// @param block A block to control modifier logic +- (nonnull instancetype)initWithBlock:(nonnull SDWebImageDownloaderResponseModifierBlock)block; + +/// Create the response modifier with block +/// @param block A block to control modifier logic ++ (nonnull instancetype)responseModifierWithBlock:(nonnull SDWebImageDownloaderResponseModifierBlock)block; + +- (nonnull instancetype)init NS_UNAVAILABLE; ++ (nonnull instancetype)new NS_UNAVAILABLE; + +@end + +/** +A convenient response modifier to provide the HTTP response including HTTP Status Code, Version and Headers. +*/ +@interface SDWebImageDownloaderResponseModifier (Conveniences) + +/// Create the response modifier with HTTP Status code. +/// @param statusCode HTTP Status Code. +/// @note This is for convenience, if you need code to control the logic, use block API instead. +- (nonnull instancetype)initWithStatusCode:(NSInteger)statusCode; + +/// Create the response modifier with HTTP Version. Status code defaults to 200. +/// @param version HTTP Version, nil means "HTTP/1.1". +/// @note This is for convenience, if you need code to control the logic, use block API instead. +- (nonnull instancetype)initWithVersion:(nullable NSString *)version; + +/// Create the response modifier with HTTP Headers. Status code defaults to 200. +/// @param headers HTTP Headers. Case insensitive according to HTTP/1.1(HTTP/2) standard. The headers will override the same fields from original response. +/// @note This is for convenience, if you need code to control the logic, use block API instead. +- (nonnull instancetype)initWithHeaders:(nullable NSDictionary *)headers; + +/// Create the response modifier with HTTP Status Code, Version and Headers. +/// @param statusCode HTTP Status Code. +/// @param version HTTP Version, nil means "HTTP/1.1". +/// @param headers HTTP Headers. Case insensitive according to HTTP/1.1(HTTP/2) standard. The headers will override the same fields from original response. +/// @note This is for convenience, if you need code to control the logic, use block API instead. +- (nonnull instancetype)initWithStatusCode:(NSInteger)statusCode version:(nullable NSString *)version headers:(nullable NSDictionary *)headers; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderResponseModifier.m b/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderResponseModifier.m new file mode 100644 index 0000000..6acf02a --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderResponseModifier.m @@ -0,0 +1,73 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + + +#import "SDWebImageDownloaderResponseModifier.h" + +@interface SDWebImageDownloaderResponseModifier () + +@property (nonatomic, copy, nonnull) SDWebImageDownloaderResponseModifierBlock block; + +@end + +@implementation SDWebImageDownloaderResponseModifier + +- (instancetype)initWithBlock:(SDWebImageDownloaderResponseModifierBlock)block { + self = [super init]; + if (self) { + self.block = block; + } + return self; +} + ++ (instancetype)responseModifierWithBlock:(SDWebImageDownloaderResponseModifierBlock)block { + SDWebImageDownloaderResponseModifier *responseModifier = [[SDWebImageDownloaderResponseModifier alloc] initWithBlock:block]; + return responseModifier; +} + +- (nullable NSURLResponse *)modifiedResponseWithResponse:(nonnull NSURLResponse *)response { + if (!self.block) { + return nil; + } + return self.block(response); +} + +@end + +@implementation SDWebImageDownloaderResponseModifier (Conveniences) + +- (instancetype)initWithStatusCode:(NSInteger)statusCode { + return [self initWithStatusCode:statusCode version:nil headers:nil]; +} + +- (instancetype)initWithVersion:(NSString *)version { + return [self initWithStatusCode:200 version:version headers:nil]; +} + +- (instancetype)initWithHeaders:(NSDictionary *)headers { + return [self initWithStatusCode:200 version:nil headers:headers]; +} + +- (instancetype)initWithStatusCode:(NSInteger)statusCode version:(NSString *)version headers:(NSDictionary *)headers { + version = version ? [version copy] : @"HTTP/1.1"; + headers = [headers copy]; + return [self initWithBlock:^NSURLResponse * _Nullable(NSURLResponse * _Nonnull response) { + if (![response isKindOfClass:NSHTTPURLResponse.class]) { + return response; + } + NSMutableDictionary *mutableHeaders = [((NSHTTPURLResponse *)response).allHeaderFields mutableCopy]; + for (NSString *header in headers) { + NSString *value = headers[header]; + mutableHeaders[header] = value; + } + NSHTTPURLResponse *httpResponse = [[NSHTTPURLResponse alloc] initWithURL:response.URL statusCode:statusCode HTTPVersion:version headerFields:[mutableHeaders copy]]; + return httpResponse; + }]; +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDWebImageError.h b/Pods/SDWebImage/SDWebImage/Core/SDWebImageError.h new file mode 100644 index 0000000..652b0d7 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDWebImageError.h @@ -0,0 +1,33 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * (c) Jamie Pinkham + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +/// An error domain represent SDWebImage loading system with custom codes +FOUNDATION_EXPORT NSErrorDomain const _Nonnull SDWebImageErrorDomain; + +/// The response instance for invalid download response (NSURLResponse *) +FOUNDATION_EXPORT NSErrorUserInfoKey const _Nonnull SDWebImageErrorDownloadResponseKey; +/// The HTTP status code for invalid download response (NSNumber *) +FOUNDATION_EXPORT NSErrorUserInfoKey const _Nonnull SDWebImageErrorDownloadStatusCodeKey; +/// The HTTP MIME content type for invalid download response (NSString *) +FOUNDATION_EXPORT NSErrorUserInfoKey const _Nonnull SDWebImageErrorDownloadContentTypeKey; + +/// SDWebImage error domain and codes +typedef NS_ERROR_ENUM(SDWebImageErrorDomain, SDWebImageError) { + SDWebImageErrorInvalidURL = 1000, // The URL is invalid, such as nil URL or corrupted URL + SDWebImageErrorBadImageData = 1001, // The image data can not be decoded to image, or the image data is empty + SDWebImageErrorCacheNotModified = 1002, // The remote location specify that the cached image is not modified, such as the HTTP response 304 code. It's useful for `SDWebImageRefreshCached` + SDWebImageErrorBlackListed = 1003, // The URL is blacklisted because of unrecoverable failure marked by downloader (such as 404), you can use `.retryFailed` option to avoid this + SDWebImageErrorInvalidDownloadOperation = 2000, // The image download operation is invalid, such as nil operation or unexpected error occur when operation initialized + SDWebImageErrorInvalidDownloadStatusCode = 2001, // The image download response a invalid status code. You can check the status code in error's userInfo under `SDWebImageErrorDownloadStatusCodeKey` + SDWebImageErrorCancelled = 2002, // The image loading operation is cancelled before finished, during either async disk cache query, or waiting before actual network request. For actual network request error, check `NSURLErrorDomain` error domain and code. + SDWebImageErrorInvalidDownloadResponse = 2003, // When using response modifier, the modified download response is nil and marked as failed. + SDWebImageErrorInvalidDownloadContentType = 2004, // The image download response a invalid content type. You can check the MIME content type in error's userInfo under `SDWebImageErrorDownloadContentTypeKey` +}; diff --git a/Pods/SDWebImage/SDWebImage/Core/SDWebImageError.m b/Pods/SDWebImage/SDWebImage/Core/SDWebImageError.m new file mode 100644 index 0000000..bd0d17a --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDWebImageError.m @@ -0,0 +1,16 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * (c) Jamie Pinkham + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageError.h" + +NSErrorDomain const _Nonnull SDWebImageErrorDomain = @"SDWebImageErrorDomain"; + +NSErrorUserInfoKey const _Nonnull SDWebImageErrorDownloadResponseKey = @"SDWebImageErrorDownloadResponseKey"; +NSErrorUserInfoKey const _Nonnull SDWebImageErrorDownloadStatusCodeKey = @"SDWebImageErrorDownloadStatusCodeKey"; +NSErrorUserInfoKey const _Nonnull SDWebImageErrorDownloadContentTypeKey = @"SDWebImageErrorDownloadContentTypeKey"; diff --git a/Pods/SDWebImage/SDWebImage/Core/SDWebImageIndicator.h b/Pods/SDWebImage/SDWebImage/Core/SDWebImageIndicator.h new file mode 100644 index 0000000..522dc47 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDWebImageIndicator.h @@ -0,0 +1,119 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +#if SD_UIKIT || SD_MAC + +/** + A protocol to custom the indicator during the image loading. + All of these methods are called from main queue. + */ +@protocol SDWebImageIndicator + +@required +/** + The view associate to the indicator. + + @return The indicator view + */ +@property (nonatomic, strong, readonly, nonnull) UIView *indicatorView; + +/** + Start the animating for indicator. + */ +- (void)startAnimatingIndicator; + +/** + Stop the animating for indicator. + */ +- (void)stopAnimatingIndicator; + +@optional +/** + Update the loading progress (0-1.0) for indicator. Optional + + @param progress The progress, value between 0 and 1.0 + */ +- (void)updateIndicatorProgress:(double)progress; + +@end + +#pragma mark - Activity Indicator + +/** + Activity indicator class. + for UIKit(macOS), it use a `UIActivityIndicatorView`. + for AppKit(macOS), it use a `NSProgressIndicator` with the spinning style. + */ +@interface SDWebImageActivityIndicator : NSObject + +#if SD_UIKIT +@property (nonatomic, strong, readonly, nonnull) UIActivityIndicatorView *indicatorView; +#else +@property (nonatomic, strong, readonly, nonnull) NSProgressIndicator *indicatorView; +#endif + +@end + +/** + Convenience way to use activity indicator. + */ +@interface SDWebImageActivityIndicator (Conveniences) + +#if !SD_VISION +/// These indicator use the fixed color without dark mode support +/// gray-style activity indicator +@property (nonatomic, class, nonnull, readonly) SDWebImageActivityIndicator *grayIndicator; +/// large gray-style activity indicator +@property (nonatomic, class, nonnull, readonly) SDWebImageActivityIndicator *grayLargeIndicator; +/// white-style activity indicator +@property (nonatomic, class, nonnull, readonly) SDWebImageActivityIndicator *whiteIndicator; +/// large white-style activity indicator +@property (nonatomic, class, nonnull, readonly) SDWebImageActivityIndicator *whiteLargeIndicator; +#endif +/// These indicator use the system style, supports dark mode if available (iOS 13+/macOS 10.14+) +/// large activity indicator +@property (nonatomic, class, nonnull, readonly) SDWebImageActivityIndicator *largeIndicator; +/// medium activity indicator +@property (nonatomic, class, nonnull, readonly) SDWebImageActivityIndicator *mediumIndicator; + +@end + +#pragma mark - Progress Indicator + +/** + Progress indicator class. + for UIKit(macOS), it use a `UIProgressView`. + for AppKit(macOS), it use a `NSProgressIndicator` with the bar style. + */ +@interface SDWebImageProgressIndicator : NSObject + +#if SD_UIKIT +@property (nonatomic, strong, readonly, nonnull) UIProgressView *indicatorView; +#else +@property (nonatomic, strong, readonly, nonnull) NSProgressIndicator *indicatorView; +#endif + +@end + +/** + Convenience way to create progress indicator. Remember to specify the indicator width or use layout constraint if need. + */ +@interface SDWebImageProgressIndicator (Conveniences) + +/// default-style progress indicator +@property (nonatomic, class, nonnull, readonly) SDWebImageProgressIndicator *defaultIndicator; +#if SD_UIKIT +/// bar-style progress indicator +@property (nonatomic, class, nonnull, readonly) SDWebImageProgressIndicator *barIndicator API_UNAVAILABLE(tvos); +#endif + +@end + +#endif diff --git a/Pods/SDWebImage/SDWebImage/Core/SDWebImageIndicator.m b/Pods/SDWebImage/SDWebImage/Core/SDWebImageIndicator.m new file mode 100644 index 0000000..031d6c9 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDWebImageIndicator.m @@ -0,0 +1,291 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageIndicator.h" + +#if SD_UIKIT || SD_MAC + +#if SD_MAC +#import +#import +#endif + +#pragma mark - Activity Indicator + +@interface SDWebImageActivityIndicator () + +#if SD_UIKIT +@property (nonatomic, strong, readwrite, nonnull) UIActivityIndicatorView *indicatorView; +#else +@property (nonatomic, strong, readwrite, nonnull) NSProgressIndicator *indicatorView; +#endif + +@end + +@implementation SDWebImageActivityIndicator + +- (instancetype)init { + self = [super init]; + if (self) { + [self commonInit]; + } + return self; +} + +#if SD_UIKIT +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +- (void)commonInit { +#if SD_VISION + UIActivityIndicatorViewStyle style = UIActivityIndicatorViewStyleMedium; +#else + UIActivityIndicatorViewStyle style; + if (@available(iOS 13.0, tvOS 13.0, *)) { + style = UIActivityIndicatorViewStyleMedium; + } else { + style = UIActivityIndicatorViewStyleWhite; + } +#endif + self.indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:style]; + self.indicatorView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin; +} +#pragma clang diagnostic pop +#endif + +#if SD_MAC +- (void)commonInit { + self.indicatorView = [[NSProgressIndicator alloc] initWithFrame:NSZeroRect]; + self.indicatorView.style = NSProgressIndicatorStyleSpinning; + self.indicatorView.controlSize = NSControlSizeSmall; + [self.indicatorView sizeToFit]; + self.indicatorView.autoresizingMask = NSViewMaxXMargin | NSViewMinXMargin | NSViewMaxYMargin | NSViewMinYMargin; +} +#endif + +- (void)startAnimatingIndicator { +#if SD_UIKIT + [self.indicatorView startAnimating]; +#else + [self.indicatorView startAnimation:nil]; +#endif + self.indicatorView.hidden = NO; +} + +- (void)stopAnimatingIndicator { +#if SD_UIKIT + [self.indicatorView stopAnimating]; +#else + [self.indicatorView stopAnimation:nil]; +#endif + self.indicatorView.hidden = YES; +} + +@end + +@implementation SDWebImageActivityIndicator (Conveniences) + +#if !SD_VISION +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" ++ (SDWebImageActivityIndicator *)grayIndicator { + SDWebImageActivityIndicator *indicator = [SDWebImageActivityIndicator new]; +#if SD_UIKIT +#if SD_IOS + indicator.indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray; +#else + indicator.indicatorView.color = [UIColor colorWithWhite:0 alpha:0.45]; // Color from `UIActivityIndicatorViewStyleGray` +#endif +#else + indicator.indicatorView.appearance = [NSAppearance appearanceNamed:NSAppearanceNameAqua]; // Disable dark mode support +#endif + return indicator; +} + ++ (SDWebImageActivityIndicator *)grayLargeIndicator { + SDWebImageActivityIndicator *indicator = SDWebImageActivityIndicator.grayIndicator; +#if SD_UIKIT + UIColor *grayColor = indicator.indicatorView.color; + indicator.indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge; + indicator.indicatorView.color = grayColor; +#else + indicator.indicatorView.appearance = [NSAppearance appearanceNamed:NSAppearanceNameAqua]; // Disable dark mode support + indicator.indicatorView.controlSize = NSControlSizeRegular; +#endif + [indicator.indicatorView sizeToFit]; + return indicator; +} + ++ (SDWebImageActivityIndicator *)whiteIndicator { + SDWebImageActivityIndicator *indicator = [SDWebImageActivityIndicator new]; +#if SD_UIKIT + indicator.indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite; +#else + indicator.indicatorView.appearance = [NSAppearance appearanceNamed:NSAppearanceNameAqua]; // Disable dark mode support + CIFilter *lighten = [CIFilter filterWithName:@"CIColorControls"]; + [lighten setDefaults]; + [lighten setValue:@(1) forKey:kCIInputBrightnessKey]; + indicator.indicatorView.contentFilters = @[lighten]; +#endif + return indicator; +} + ++ (SDWebImageActivityIndicator *)whiteLargeIndicator { + SDWebImageActivityIndicator *indicator = SDWebImageActivityIndicator.whiteIndicator; +#if SD_UIKIT + indicator.indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge; +#else + indicator.indicatorView.appearance = [NSAppearance appearanceNamed:NSAppearanceNameAqua]; // Disable dark mode support + indicator.indicatorView.controlSize = NSControlSizeRegular; + [indicator.indicatorView sizeToFit]; +#endif + return indicator; +} +#endif + ++ (SDWebImageActivityIndicator *)largeIndicator { + SDWebImageActivityIndicator *indicator = [SDWebImageActivityIndicator new]; +#if SD_VISION + indicator.indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleLarge; +#elif SD_UIKIT + if (@available(iOS 13.0, tvOS 13.0, *)) { + indicator.indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleLarge; + } else { + indicator.indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge; + } +#else + indicator.indicatorView.controlSize = NSControlSizeRegular; + [indicator.indicatorView sizeToFit]; +#endif + return indicator; +} + ++ (SDWebImageActivityIndicator *)mediumIndicator { + SDWebImageActivityIndicator *indicator = [SDWebImageActivityIndicator new]; +#if SD_VISION + indicator.indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleMedium; +#elif SD_UIKIT + if (@available(iOS 13.0, tvOS 13.0, *)) { + indicator.indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleMedium; + } else { + indicator.indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite; + } +#else + indicator.indicatorView.controlSize = NSControlSizeSmall; + [indicator.indicatorView sizeToFit]; +#endif + return indicator; +} +#pragma clang diagnostic pop + +@end + +#pragma mark - Progress Indicator + +@interface SDWebImageProgressIndicator () + +#if SD_UIKIT +@property (nonatomic, strong, readwrite, nonnull) UIProgressView *indicatorView; +#else +@property (nonatomic, strong, readwrite, nonnull) NSProgressIndicator *indicatorView; +#endif + +@end + +@implementation SDWebImageProgressIndicator + +- (instancetype)init { + self = [super init]; + if (self) { + [self commonInit]; + } + return self; +} + +#if SD_UIKIT +- (void)commonInit { + self.indicatorView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault]; + self.indicatorView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin; +} +#endif + +#if SD_MAC +- (void)commonInit { + self.indicatorView = [[NSProgressIndicator alloc] initWithFrame:NSMakeRect(0, 0, 160, 0)]; // Width from `UIProgressView` default width + self.indicatorView.style = NSProgressIndicatorStyleBar; + self.indicatorView.controlSize = NSControlSizeSmall; + [self.indicatorView sizeToFit]; + self.indicatorView.autoresizingMask = NSViewMaxXMargin | NSViewMinXMargin | NSViewMaxYMargin | NSViewMinYMargin; +} +#endif + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability" +- (void)startAnimatingIndicator { + self.indicatorView.hidden = NO; +#if SD_UIKIT + if ([self.indicatorView respondsToSelector:@selector(observedProgress)] && self.indicatorView.observedProgress) { + // Ignore NSProgress + } else { + self.indicatorView.progress = 0; + } +#else + self.indicatorView.indeterminate = YES; + self.indicatorView.doubleValue = 0; + [self.indicatorView startAnimation:nil]; +#endif +} + +- (void)stopAnimatingIndicator { + self.indicatorView.hidden = YES; +#if SD_UIKIT + if ([self.indicatorView respondsToSelector:@selector(observedProgress)] && self.indicatorView.observedProgress) { + // Ignore NSProgress + } else { + self.indicatorView.progress = 1; + } +#else + self.indicatorView.indeterminate = NO; + self.indicatorView.doubleValue = 100; + [self.indicatorView stopAnimation:nil]; +#endif +} + +- (void)updateIndicatorProgress:(double)progress { +#if SD_UIKIT + if ([self.indicatorView respondsToSelector:@selector(observedProgress)] && self.indicatorView.observedProgress) { + // Ignore NSProgress + } else { + [self.indicatorView setProgress:progress animated:YES]; + } +#else + self.indicatorView.indeterminate = progress > 0 ? NO : YES; + self.indicatorView.doubleValue = progress * 100; +#endif +} +#pragma clang diagnostic pop + +@end + +@implementation SDWebImageProgressIndicator (Conveniences) + ++ (SDWebImageProgressIndicator *)defaultIndicator { + SDWebImageProgressIndicator *indicator = [SDWebImageProgressIndicator new]; + return indicator; +} + +#if SD_UIKIT ++ (SDWebImageProgressIndicator *)barIndicator API_UNAVAILABLE(tvos) { + SDWebImageProgressIndicator *indicator = [SDWebImageProgressIndicator new]; + indicator.indicatorView.progressViewStyle = UIProgressViewStyleBar; + return indicator; +} +#endif + +@end + +#endif diff --git a/Pods/SDWebImage/SDWebImage/Core/SDWebImageManager.h b/Pods/SDWebImage/SDWebImage/Core/SDWebImageManager.h new file mode 100644 index 0000000..1219ce3 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDWebImageManager.h @@ -0,0 +1,290 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" +#import "SDWebImageOperation.h" +#import "SDImageCacheDefine.h" +#import "SDImageLoader.h" +#import "SDImageTransformer.h" +#import "SDWebImageCacheKeyFilter.h" +#import "SDWebImageCacheSerializer.h" +#import "SDWebImageOptionsProcessor.h" + +typedef void(^SDExternalCompletionBlock)(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL); + +typedef void(^SDInternalCompletionBlock)(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL); + +/** + A combined operation representing the cache and loader operation. You can use it to cancel the load process. + */ +@interface SDWebImageCombinedOperation : NSObject + +/** + Cancel the current operation, including cache and loader process + */ +- (void)cancel; + +/// Whether the operation has been cancelled. +@property (nonatomic, assign, readonly, getter=isCancelled) BOOL cancelled; + +/** + The cache operation from the image cache query + */ +@property (strong, nonatomic, nullable, readonly) id cacheOperation; + +/** + The loader operation from the image loader (such as download operation) + */ +@property (strong, nonatomic, nullable, readonly) id loaderOperation; + +@end + + +@class SDWebImageManager; + +/** + The manager delegate protocol. + */ +@protocol SDWebImageManagerDelegate + +@optional + +/** + * Controls which image should be downloaded when the image is not found in the cache. + * + * @param imageManager The current `SDWebImageManager` + * @param imageURL The url of the image to be downloaded + * + * @return Return NO to prevent the downloading of the image on cache misses. If not implemented, YES is implied. + */ +- (BOOL)imageManager:(nonnull SDWebImageManager *)imageManager shouldDownloadImageForURL:(nonnull NSURL *)imageURL; + +/** + * Controls the complicated logic to mark as failed URLs when download error occur. + * If the delegate implement this method, we will not use the built-in way to mark URL as failed based on error code; + @param imageManager The current `SDWebImageManager` + @param imageURL The url of the image + @param error The download error for the url + @return Whether to block this url or not. Return YES to mark this URL as failed. + */ +- (BOOL)imageManager:(nonnull SDWebImageManager *)imageManager shouldBlockFailedURL:(nonnull NSURL *)imageURL withError:(nonnull NSError *)error; + +@end + +/** + * The SDWebImageManager is the class behind the UIImageView+WebCache category and likes. + * It ties the asynchronous downloader (SDWebImageDownloader) with the image cache store (SDImageCache). + * You can use this class directly to benefit from web image downloading with caching in another context than + * a UIView. + * + * Here is a simple example of how to use SDWebImageManager: + * + * @code + +SDWebImageManager *manager = [SDWebImageManager sharedManager]; +[manager loadImageWithURL:imageURL + options:0 + progress:nil + completed:^(UIImage *image, NSData *data, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { + if (image) { + // do something with image + } + }]; + + * @endcode + */ +@interface SDWebImageManager : NSObject + +/** + * The delegate for manager. Defaults to nil. + */ +@property (weak, nonatomic, nullable) id delegate; + +/** + * The image cache used by manager to query image cache. + */ +@property (strong, nonatomic, readonly, nonnull) id imageCache; + +/** + * The image loader used by manager to load image. + */ +@property (strong, nonatomic, readonly, nonnull) id imageLoader; + +/** + The image transformer for manager. It's used for image transform after the image load finished and store the transformed image to cache, see `SDImageTransformer`. + Defaults to nil, which means no transform is applied. + @note This will affect all the load requests for this manager if you provide. However, you can pass `SDWebImageContextImageTransformer` in context arg to explicitly use that transformer instead. + */ +@property (strong, nonatomic, nullable) id transformer; + +/** + * The cache filter is used to convert an URL into a cache key each time SDWebImageManager need cache key to use image cache. + * + * The following example sets a filter in the application delegate that will remove any query-string from the + * URL before to use it as a cache key: + * + * @code + SDWebImageManager.sharedManager.cacheKeyFilter =[SDWebImageCacheKeyFilter cacheKeyFilterWithBlock:^NSString * _Nullable(NSURL * _Nonnull url) { + url = [[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path]; + return [url absoluteString]; + }]; + * @endcode + */ +@property (nonatomic, strong, nullable) id cacheKeyFilter; + +/** + * The cache serializer is used to convert the decoded image, the source downloaded data, to the actual data used for storing to the disk cache. If you return nil, means to generate the data from the image instance, see `SDImageCache`. + * For example, if you are using WebP images and facing the slow decoding time issue when later retrieving from disk cache again. You can try to encode the decoded image to JPEG/PNG format to disk cache instead of source downloaded data. + * @note The `image` arg is nonnull, but when you also provide an image transformer and the image is transformed, the `data` arg may be nil, take attention to this case. + * @note This method is called from a global queue in order to not to block the main thread. + * @code + SDWebImageManager.sharedManager.cacheSerializer = [SDWebImageCacheSerializer cacheSerializerWithBlock:^NSData * _Nullable(UIImage * _Nonnull image, NSData * _Nullable data, NSURL * _Nullable imageURL) { + SDImageFormat format = [NSData sd_imageFormatForImageData:data]; + switch (format) { + case SDImageFormatWebP: + return image.images ? data : nil; + default: + return data; + } +}]; + * @endcode + * The default value is nil. Means we just store the source downloaded data to disk cache. + */ +@property (nonatomic, strong, nullable) id cacheSerializer; + +/** + The options processor is used, to have a global control for all the image request options and context option for current manager. + @note If you use `transformer`, `cacheKeyFilter` or `cacheSerializer` property of manager, the input context option already apply those properties before passed. This options processor is a better replacement for those property in common usage. + For example, you can control the global options, based on the URL or original context option like the below code. + + * @code + SDWebImageManager.sharedManager.optionsProcessor = [SDWebImageOptionsProcessor optionsProcessorWithBlock:^SDWebImageOptionsResult * _Nullable(NSURL * _Nullable url, SDWebImageOptions options, SDWebImageContext * _Nullable context) { + // Only do animation on `SDAnimatedImageView` + if (!context[SDWebImageContextAnimatedImageClass]) { + options |= SDWebImageDecodeFirstFrameOnly; + } + // Do not force decode for png url + if ([url.lastPathComponent isEqualToString:@"png"]) { + options |= SDWebImageAvoidDecodeImage; + } + // Always use screen scale factor + SDWebImageMutableContext *mutableContext = [NSDictionary dictionaryWithDictionary:context]; + mutableContext[SDWebImageContextImageScaleFactor] = @(UIScreen.mainScreen.scale); + context = [mutableContext copy]; + + return [[SDWebImageOptionsResult alloc] initWithOptions:options context:context]; + }]; + * @endcode + */ +@property (nonatomic, strong, nullable) id optionsProcessor; + +/** + * Check one or more operations running + */ +@property (nonatomic, assign, readonly, getter=isRunning) BOOL running; + +/** + The default image cache when the manager which is created with no arguments. Such as shared manager or init. + Defaults to nil. Means using `SDImageCache.sharedImageCache` + */ +@property (nonatomic, class, nullable) id defaultImageCache; + +/** + The default image loader for manager which is created with no arguments. Such as shared manager or init. + Defaults to nil. Means using `SDWebImageDownloader.sharedDownloader` + */ +@property (nonatomic, class, nullable) id defaultImageLoader; + +/** + * Returns global shared manager instance. + */ +@property (nonatomic, class, readonly, nonnull) SDWebImageManager *sharedManager; + +/** + * Allows to specify instance of cache and image loader used with image manager. + * @return new instance of `SDWebImageManager` with specified cache and loader. + */ +- (nonnull instancetype)initWithCache:(nonnull id)cache loader:(nonnull id)loader NS_DESIGNATED_INITIALIZER; + +/** + * Downloads the image at the given URL if not present in cache or return the cached version otherwise. + * + * @param url The URL to the image + * @param options A mask to specify options to use for this request + * @param progressBlock A block called while image is downloading + * @note the progress block is executed on a background queue + * @param completedBlock A block called when operation has been completed. + * + * This parameter is required. + * + * This block has no return value and takes the requested UIImage as first parameter and the NSData representation as second parameter. + * In case of error the image parameter is nil and the third parameter may contain an NSError. + * + * The forth parameter is an `SDImageCacheType` enum indicating if the image was retrieved from the local cache + * or from the memory cache or from the network. + * + * The fifth parameter is set to NO when the SDWebImageProgressiveLoad option is used and the image is + * downloading. This block is thus called repeatedly with a partial image. When image is fully downloaded, the + * block is called a last time with the full image and the last parameter set to YES. + * + * The last parameter is the original image URL + * + * @return Returns an instance of SDWebImageCombinedOperation, which you can cancel the loading process. + */ +- (nullable SDWebImageCombinedOperation *)loadImageWithURL:(nullable NSURL *)url + options:(SDWebImageOptions)options + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nonnull SDInternalCompletionBlock)completedBlock; + +/** + * Downloads the image at the given URL if not present in cache or return the cached version otherwise. + * + * @param url The URL to the image + * @param options A mask to specify options to use for this request + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + * @param progressBlock A block called while image is downloading + * @note the progress block is executed on a background queue + * @param completedBlock A block called when operation has been completed. + * + * @return Returns an instance of SDWebImageCombinedOperation, which you can cancel the loading process. + */ +- (nullable SDWebImageCombinedOperation *)loadImageWithURL:(nullable NSURL *)url + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nonnull SDInternalCompletionBlock)completedBlock; + +/** + * Cancel all current operations + */ +- (void)cancelAll; + +/** + * Remove the specify URL from failed black list. + * @param url The failed URL. + */ +- (void)removeFailedURL:(nonnull NSURL *)url; + +/** + * Remove all the URL from failed black list. + */ +- (void)removeAllFailedURLs; + +/** + * Return the cache key for a given URL, does not considerate transformer or thumbnail. + * @note This method does not have context option, only use the url and manager level cacheKeyFilter to generate the cache key. + */ +- (nullable NSString *)cacheKeyForURL:(nullable NSURL *)url; + +/** + * Return the cache key for a given URL and context option. + * @note The context option like `.thumbnailPixelSize` and `.imageTransformer` will effect the generated cache key, using this if you have those context associated. +*/ +- (nullable NSString *)cacheKeyForURL:(nullable NSURL *)url context:(nullable SDWebImageContext *)context; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDWebImageManager.m b/Pods/SDWebImage/SDWebImage/Core/SDWebImageManager.m new file mode 100644 index 0000000..df607c5 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDWebImageManager.m @@ -0,0 +1,800 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageManager.h" +#import "SDImageCache.h" +#import "SDWebImageDownloader.h" +#import "UIImage+Metadata.h" +#import "SDAssociatedObject.h" +#import "SDWebImageError.h" +#import "SDInternalMacros.h" +#import "SDCallbackQueue.h" + +static id _defaultImageCache; +static id _defaultImageLoader; + +@interface SDWebImageCombinedOperation () + +@property (assign, nonatomic, getter = isCancelled) BOOL cancelled; +@property (strong, nonatomic, readwrite, nullable) id loaderOperation; +@property (strong, nonatomic, readwrite, nullable) id cacheOperation; +@property (weak, nonatomic, nullable) SDWebImageManager *manager; + +@end + +@interface SDWebImageManager () { + SD_LOCK_DECLARE(_failedURLsLock); // a lock to keep the access to `failedURLs` thread-safe + SD_LOCK_DECLARE(_runningOperationsLock); // a lock to keep the access to `runningOperations` thread-safe +} + +@property (strong, nonatomic, readwrite, nonnull) SDImageCache *imageCache; +@property (strong, nonatomic, readwrite, nonnull) id imageLoader; +@property (strong, nonatomic, nonnull) NSMutableSet *failedURLs; +@property (strong, nonatomic, nonnull) NSMutableSet *runningOperations; + +@end + +@implementation SDWebImageManager + ++ (id)defaultImageCache { + return _defaultImageCache; +} + ++ (void)setDefaultImageCache:(id)defaultImageCache { + if (defaultImageCache && ![defaultImageCache conformsToProtocol:@protocol(SDImageCache)]) { + return; + } + _defaultImageCache = defaultImageCache; +} + ++ (id)defaultImageLoader { + return _defaultImageLoader; +} + ++ (void)setDefaultImageLoader:(id)defaultImageLoader { + if (defaultImageLoader && ![defaultImageLoader conformsToProtocol:@protocol(SDImageLoader)]) { + return; + } + _defaultImageLoader = defaultImageLoader; +} + ++ (nonnull instancetype)sharedManager { + static dispatch_once_t once; + static id instance; + dispatch_once(&once, ^{ + instance = [self new]; + }); + return instance; +} + +- (nonnull instancetype)init { + id cache = [[self class] defaultImageCache]; + if (!cache) { + cache = [SDImageCache sharedImageCache]; + } + id loader = [[self class] defaultImageLoader]; + if (!loader) { + loader = [SDWebImageDownloader sharedDownloader]; + } + return [self initWithCache:cache loader:loader]; +} + +- (nonnull instancetype)initWithCache:(nonnull id)cache loader:(nonnull id)loader { + if ((self = [super init])) { + _imageCache = cache; + _imageLoader = loader; + _failedURLs = [NSMutableSet new]; + SD_LOCK_INIT(_failedURLsLock); + _runningOperations = [NSMutableSet new]; + SD_LOCK_INIT(_runningOperationsLock); + } + return self; +} + +- (nullable NSString *)cacheKeyForURL:(nullable NSURL *)url { + if (!url) { + return @""; + } + + NSString *key; + // Cache Key Filter + id cacheKeyFilter = self.cacheKeyFilter; + if (cacheKeyFilter) { + key = [cacheKeyFilter cacheKeyForURL:url]; + } else { + key = url.absoluteString; + } + + return key; +} + +- (nullable NSString *)originalCacheKeyForURL:(nullable NSURL *)url context:(nullable SDWebImageContext *)context { + if (!url) { + return @""; + } + + NSString *key; + // Cache Key Filter + id cacheKeyFilter = self.cacheKeyFilter; + if (context[SDWebImageContextCacheKeyFilter]) { + cacheKeyFilter = context[SDWebImageContextCacheKeyFilter]; + } + if (cacheKeyFilter) { + key = [cacheKeyFilter cacheKeyForURL:url]; + } else { + key = url.absoluteString; + } + + return key; +} + +- (nullable NSString *)cacheKeyForURL:(nullable NSURL *)url context:(nullable SDWebImageContext *)context { + if (!url) { + return @""; + } + + NSString *key; + // Cache Key Filter + id cacheKeyFilter = self.cacheKeyFilter; + if (context[SDWebImageContextCacheKeyFilter]) { + cacheKeyFilter = context[SDWebImageContextCacheKeyFilter]; + } + if (cacheKeyFilter) { + key = [cacheKeyFilter cacheKeyForURL:url]; + } else { + key = url.absoluteString; + } + + // Thumbnail Key Appending + NSValue *thumbnailSizeValue = context[SDWebImageContextImageThumbnailPixelSize]; + if (thumbnailSizeValue != nil) { + CGSize thumbnailSize = CGSizeZero; +#if SD_MAC + thumbnailSize = thumbnailSizeValue.sizeValue; +#else + thumbnailSize = thumbnailSizeValue.CGSizeValue; +#endif + BOOL preserveAspectRatio = YES; + NSNumber *preserveAspectRatioValue = context[SDWebImageContextImagePreserveAspectRatio]; + if (preserveAspectRatioValue != nil) { + preserveAspectRatio = preserveAspectRatioValue.boolValue; + } + key = SDThumbnailedKeyForKey(key, thumbnailSize, preserveAspectRatio); + } + + // Transformer Key Appending + id transformer = self.transformer; + if (context[SDWebImageContextImageTransformer]) { + transformer = context[SDWebImageContextImageTransformer]; + if ([transformer isEqual:NSNull.null]) { + transformer = nil; + } + } + if (transformer) { + key = SDTransformedKeyForKey(key, transformer.transformerKey); + } + + return key; +} + +- (SDWebImageCombinedOperation *)loadImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDImageLoaderProgressBlock)progressBlock completed:(SDInternalCompletionBlock)completedBlock { + return [self loadImageWithURL:url options:options context:nil progress:progressBlock completed:completedBlock]; +} + +- (SDWebImageCombinedOperation *)loadImageWithURL:(nullable NSURL *)url + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nonnull SDInternalCompletionBlock)completedBlock { + // Invoking this method without a completedBlock is pointless + NSAssert(completedBlock != nil, @"If you mean to prefetch the image, use -[SDWebImagePrefetcher prefetchURLs] instead"); + + // Very common mistake is to send the URL using NSString object instead of NSURL. For some strange reason, Xcode won't + // throw any warning for this type mismatch. Here we failsafe this error by allowing URLs to be passed as NSString. + if ([url isKindOfClass:NSString.class]) { + url = [NSURL URLWithString:(NSString *)url]; + } + + // Prevents app crashing on argument type error like sending NSNull instead of NSURL + if (![url isKindOfClass:NSURL.class]) { + url = nil; + } + + SDWebImageCombinedOperation *operation = [SDWebImageCombinedOperation new]; + operation.manager = self; + + BOOL isFailedUrl = NO; + if (url) { + SD_LOCK(_failedURLsLock); + isFailedUrl = [self.failedURLs containsObject:url]; + SD_UNLOCK(_failedURLsLock); + } + + // Preprocess the options and context arg to decide the final the result for manager + SDWebImageOptionsResult *result = [self processedResultForURL:url options:options context:context]; + + if (url.absoluteString.length == 0 || (!(options & SDWebImageRetryFailed) && isFailedUrl)) { + NSString *description = isFailedUrl ? @"Image url is blacklisted" : @"Image url is nil"; + NSInteger code = isFailedUrl ? SDWebImageErrorBlackListed : SDWebImageErrorInvalidURL; + [self callCompletionBlockForOperation:operation completion:completedBlock error:[NSError errorWithDomain:SDWebImageErrorDomain code:code userInfo:@{NSLocalizedDescriptionKey : description}] queue:result.context[SDWebImageContextCallbackQueue] url:url]; + return operation; + } + + SD_LOCK(_runningOperationsLock); + [self.runningOperations addObject:operation]; + SD_UNLOCK(_runningOperationsLock); + + // Start the entry to load image from cache, the longest steps are below + // Steps without transformer: + // 1. query image from cache, miss + // 2. download data and image + // 3. store image to cache + + // Steps with transformer: + // 1. query transformed image from cache, miss + // 2. query original image from cache, miss + // 3. download data and image + // 4. do transform in CPU + // 5. store original image to cache + // 6. store transformed image to cache + [self callCacheProcessForOperation:operation url:url options:result.options context:result.context progress:progressBlock completed:completedBlock]; + + return operation; +} + +- (void)cancelAll { + SD_LOCK(_runningOperationsLock); + NSSet *copiedOperations = [self.runningOperations copy]; + SD_UNLOCK(_runningOperationsLock); + [copiedOperations makeObjectsPerformSelector:@selector(cancel)]; // This will call `safelyRemoveOperationFromRunning:` and remove from the array +} + +- (BOOL)isRunning { + BOOL isRunning = NO; + SD_LOCK(_runningOperationsLock); + isRunning = (self.runningOperations.count > 0); + SD_UNLOCK(_runningOperationsLock); + return isRunning; +} + +- (void)removeFailedURL:(NSURL *)url { + if (!url) { + return; + } + SD_LOCK(_failedURLsLock); + [self.failedURLs removeObject:url]; + SD_UNLOCK(_failedURLsLock); +} + +- (void)removeAllFailedURLs { + SD_LOCK(_failedURLsLock); + [self.failedURLs removeAllObjects]; + SD_UNLOCK(_failedURLsLock); +} + +#pragma mark - Private + +// Query normal cache process +- (void)callCacheProcessForOperation:(nonnull SDWebImageCombinedOperation *)operation + url:(nonnull NSURL *)url + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDInternalCompletionBlock)completedBlock { + // Grab the image cache to use + id imageCache = context[SDWebImageContextImageCache]; + if (!imageCache) { + imageCache = self.imageCache; + } + // Get the query cache type + SDImageCacheType queryCacheType = SDImageCacheTypeAll; + if (context[SDWebImageContextQueryCacheType]) { + queryCacheType = [context[SDWebImageContextQueryCacheType] integerValue]; + } + + // Check whether we should query cache + BOOL shouldQueryCache = !SD_OPTIONS_CONTAINS(options, SDWebImageFromLoaderOnly); + if (shouldQueryCache) { + // transformed cache key + NSString *key = [self cacheKeyForURL:url context:context]; + // to avoid the SDImageCache's sync logic use the mismatched cache key + // we should strip the `thumbnail` related context + SDWebImageMutableContext *mutableContext = [context mutableCopy]; + mutableContext[SDWebImageContextImageThumbnailPixelSize] = nil; + mutableContext[SDWebImageContextImagePreserveAspectRatio] = nil; + @weakify(operation); + operation.cacheOperation = [imageCache queryImageForKey:key options:options context:mutableContext cacheType:queryCacheType completion:^(UIImage * _Nullable cachedImage, NSData * _Nullable cachedData, SDImageCacheType cacheType) { + @strongify(operation); + if (!operation || operation.isCancelled) { + // Image combined operation cancelled by user + [self callCompletionBlockForOperation:operation completion:completedBlock error:[NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorCancelled userInfo:@{NSLocalizedDescriptionKey : @"Operation cancelled by user during querying the cache"}] queue:context[SDWebImageContextCallbackQueue] url:url]; + [self safelyRemoveOperationFromRunning:operation]; + return; + } else if (!cachedImage) { + NSString *originKey = [self originalCacheKeyForURL:url context:context]; + BOOL mayInOriginalCache = ![key isEqualToString:originKey]; + // Have a chance to query original cache instead of downloading, then applying transform + // Thumbnail decoding is done inside SDImageCache's decoding part, which does not need post processing for transform + if (mayInOriginalCache) { + [self callOriginalCacheProcessForOperation:operation url:url options:options context:context progress:progressBlock completed:completedBlock]; + return; + } + } + // Continue download process + [self callDownloadProcessForOperation:operation url:url options:options context:context cachedImage:cachedImage cachedData:cachedData cacheType:cacheType progress:progressBlock completed:completedBlock]; + }]; + } else { + // Continue download process + [self callDownloadProcessForOperation:operation url:url options:options context:context cachedImage:nil cachedData:nil cacheType:SDImageCacheTypeNone progress:progressBlock completed:completedBlock]; + } +} + +// Query original cache process +- (void)callOriginalCacheProcessForOperation:(nonnull SDWebImageCombinedOperation *)operation + url:(nonnull NSURL *)url + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDInternalCompletionBlock)completedBlock { + // Grab the image cache to use, choose standalone original cache firstly + id imageCache = context[SDWebImageContextOriginalImageCache]; + if (!imageCache) { + // if no standalone cache available, use default cache + imageCache = context[SDWebImageContextImageCache]; + if (!imageCache) { + imageCache = self.imageCache; + } + } + // Get the original query cache type + SDImageCacheType originalQueryCacheType = SDImageCacheTypeDisk; + if (context[SDWebImageContextOriginalQueryCacheType]) { + originalQueryCacheType = [context[SDWebImageContextOriginalQueryCacheType] integerValue]; + } + + // Check whether we should query original cache + BOOL shouldQueryOriginalCache = (originalQueryCacheType != SDImageCacheTypeNone); + if (shouldQueryOriginalCache) { + // Get original cache key generation without transformer + NSString *key = [self originalCacheKeyForURL:url context:context]; + @weakify(operation); + operation.cacheOperation = [imageCache queryImageForKey:key options:options context:context cacheType:originalQueryCacheType completion:^(UIImage * _Nullable cachedImage, NSData * _Nullable cachedData, SDImageCacheType cacheType) { + @strongify(operation); + if (!operation || operation.isCancelled) { + // Image combined operation cancelled by user + [self callCompletionBlockForOperation:operation completion:completedBlock error:[NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorCancelled userInfo:@{NSLocalizedDescriptionKey : @"Operation cancelled by user during querying the cache"}] queue:context[SDWebImageContextCallbackQueue] url:url]; + [self safelyRemoveOperationFromRunning:operation]; + return; + } else if (!cachedImage) { + // Original image cache miss. Continue download process + [self callDownloadProcessForOperation:operation url:url options:options context:context cachedImage:nil cachedData:nil cacheType:SDImageCacheTypeNone progress:progressBlock completed:completedBlock]; + return; + } + + // Skip downloading and continue transform process, and ignore .refreshCached option for now + [self callTransformProcessForOperation:operation url:url options:options context:context originalImage:cachedImage originalData:cachedData cacheType:cacheType finished:YES completed:completedBlock]; + + [self safelyRemoveOperationFromRunning:operation]; + }]; + } else { + // Continue download process + [self callDownloadProcessForOperation:operation url:url options:options context:context cachedImage:nil cachedData:nil cacheType:SDImageCacheTypeNone progress:progressBlock completed:completedBlock]; + } +} + +// Download process +- (void)callDownloadProcessForOperation:(nonnull SDWebImageCombinedOperation *)operation + url:(nonnull NSURL *)url + options:(SDWebImageOptions)options + context:(SDWebImageContext *)context + cachedImage:(nullable UIImage *)cachedImage + cachedData:(nullable NSData *)cachedData + cacheType:(SDImageCacheType)cacheType + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDInternalCompletionBlock)completedBlock { + // Mark the cache operation end + @synchronized (operation) { + operation.cacheOperation = nil; + } + + // Grab the image loader to use + id imageLoader = context[SDWebImageContextImageLoader]; + if (!imageLoader) { + imageLoader = self.imageLoader; + } + + // Check whether we should download image from network + BOOL shouldDownload = !SD_OPTIONS_CONTAINS(options, SDWebImageFromCacheOnly); + shouldDownload &= (!cachedImage || options & SDWebImageRefreshCached); + shouldDownload &= (![self.delegate respondsToSelector:@selector(imageManager:shouldDownloadImageForURL:)] || [self.delegate imageManager:self shouldDownloadImageForURL:url]); + if ([imageLoader respondsToSelector:@selector(canRequestImageForURL:options:context:)]) { + shouldDownload &= [imageLoader canRequestImageForURL:url options:options context:context]; + } else { + shouldDownload &= [imageLoader canRequestImageForURL:url]; + } + if (shouldDownload) { + if (cachedImage && options & SDWebImageRefreshCached) { + // If image was found in the cache but SDWebImageRefreshCached is provided, notify about the cached image + // AND try to re-download it in order to let a chance to NSURLCache to refresh it from server. + [self callCompletionBlockForOperation:operation completion:completedBlock image:cachedImage data:cachedData error:nil cacheType:cacheType finished:YES queue:context[SDWebImageContextCallbackQueue] url:url]; + // Pass the cached image to the image loader. The image loader should check whether the remote image is equal to the cached image. + SDWebImageMutableContext *mutableContext; + if (context) { + mutableContext = [context mutableCopy]; + } else { + mutableContext = [NSMutableDictionary dictionary]; + } + mutableContext[SDWebImageContextLoaderCachedImage] = cachedImage; + context = [mutableContext copy]; + } + + @weakify(operation); + operation.loaderOperation = [imageLoader requestImageWithURL:url options:options context:context progress:progressBlock completed:^(UIImage *downloadedImage, NSData *downloadedData, NSError *error, BOOL finished) { + @strongify(operation); + if (!operation || operation.isCancelled) { + // Image combined operation cancelled by user + [self callCompletionBlockForOperation:operation completion:completedBlock error:[NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorCancelled userInfo:@{NSLocalizedDescriptionKey : @"Operation cancelled by user during sending the request"}] queue:context[SDWebImageContextCallbackQueue] url:url]; + } else if (cachedImage && options & SDWebImageRefreshCached && [error.domain isEqualToString:SDWebImageErrorDomain] && error.code == SDWebImageErrorCacheNotModified) { + // Image refresh hit the NSURLCache cache, do not call the completion block + } else if ([error.domain isEqualToString:SDWebImageErrorDomain] && error.code == SDWebImageErrorCancelled) { + // Download operation cancelled by user before sending the request, don't block failed URL + [self callCompletionBlockForOperation:operation completion:completedBlock error:error queue:context[SDWebImageContextCallbackQueue] url:url]; + } else if (error) { + [self callCompletionBlockForOperation:operation completion:completedBlock error:error queue:context[SDWebImageContextCallbackQueue] url:url]; + BOOL shouldBlockFailedURL = [self shouldBlockFailedURLWithURL:url error:error options:options context:context]; + + if (shouldBlockFailedURL) { + SD_LOCK(self->_failedURLsLock); + [self.failedURLs addObject:url]; + SD_UNLOCK(self->_failedURLsLock); + } + } else { + if ((options & SDWebImageRetryFailed)) { + SD_LOCK(self->_failedURLsLock); + [self.failedURLs removeObject:url]; + SD_UNLOCK(self->_failedURLsLock); + } + // Continue transform process + [self callTransformProcessForOperation:operation url:url options:options context:context originalImage:downloadedImage originalData:downloadedData cacheType:SDImageCacheTypeNone finished:finished completed:completedBlock]; + } + + if (finished) { + [self safelyRemoveOperationFromRunning:operation]; + } + }]; + } else if (cachedImage) { + [self callCompletionBlockForOperation:operation completion:completedBlock image:cachedImage data:cachedData error:nil cacheType:cacheType finished:YES queue:context[SDWebImageContextCallbackQueue] url:url]; + [self safelyRemoveOperationFromRunning:operation]; + } else { + // Image not in cache and download disallowed by delegate + [self callCompletionBlockForOperation:operation completion:completedBlock image:nil data:nil error:nil cacheType:SDImageCacheTypeNone finished:YES queue:context[SDWebImageContextCallbackQueue] url:url]; + [self safelyRemoveOperationFromRunning:operation]; + } +} + +// Transform process +- (void)callTransformProcessForOperation:(nonnull SDWebImageCombinedOperation *)operation + url:(nonnull NSURL *)url + options:(SDWebImageOptions)options + context:(SDWebImageContext *)context + originalImage:(nullable UIImage *)originalImage + originalData:(nullable NSData *)originalData + cacheType:(SDImageCacheType)cacheType + finished:(BOOL)finished + completed:(nullable SDInternalCompletionBlock)completedBlock { + id transformer = context[SDWebImageContextImageTransformer]; + if ([transformer isEqual:NSNull.null]) { + transformer = nil; + } + // transformer check + BOOL shouldTransformImage = originalImage && transformer; + shouldTransformImage = shouldTransformImage && (!originalImage.sd_isAnimated || (options & SDWebImageTransformAnimatedImage)); + shouldTransformImage = shouldTransformImage && (!originalImage.sd_isVector || (options & SDWebImageTransformVectorImage)); + // thumbnail check + BOOL isThumbnail = originalImage.sd_isThumbnail; + NSData *cacheData = originalData; + UIImage *cacheImage = originalImage; + if (isThumbnail) { + cacheData = nil; // thumbnail don't store full size data + originalImage = nil; // thumbnail don't have full size image + } + + if (shouldTransformImage) { + // transformed cache key + NSString *key = [self cacheKeyForURL:url context:context]; + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ + // Case that transformer on thumbnail, which this time need full pixel image + UIImage *transformedImage = [transformer transformedImageWithImage:cacheImage forKey:key]; + if (transformedImage) { + // We need keep some metadata from the full size image when needed + // Because most of our transformer does not care about these information + // So we add a **post-process** logic here, not a good design :( + BOOL preserveImageMetadata = YES; + if ([transformer respondsToSelector:@selector(preserveImageMetadata)]) { + preserveImageMetadata = transformer.preserveImageMetadata; + } + if (preserveImageMetadata) { + SDImageCopyAssociatedObject(cacheImage, transformedImage); + } + // Mark the transformed + transformedImage.sd_isTransformed = YES; + [self callStoreOriginCacheProcessForOperation:operation url:url options:options context:context originalImage:originalImage cacheImage:transformedImage originalData:originalData cacheData:nil cacheType:cacheType finished:finished completed:completedBlock]; + } else { + [self callStoreOriginCacheProcessForOperation:operation url:url options:options context:context originalImage:originalImage cacheImage:cacheImage originalData:originalData cacheData:cacheData cacheType:cacheType finished:finished completed:completedBlock]; + } + }); + } else { + [self callStoreOriginCacheProcessForOperation:operation url:url options:options context:context originalImage:originalImage cacheImage:cacheImage originalData:originalData cacheData:cacheData cacheType:cacheType finished:finished completed:completedBlock]; + } +} + +// Store origin cache process +- (void)callStoreOriginCacheProcessForOperation:(nonnull SDWebImageCombinedOperation *)operation + url:(nonnull NSURL *)url + options:(SDWebImageOptions)options + context:(SDWebImageContext *)context + originalImage:(nullable UIImage *)originalImage + cacheImage:(nullable UIImage *)cacheImage + originalData:(nullable NSData *)originalData + cacheData:(nullable NSData *)cacheData + cacheType:(SDImageCacheType)cacheType + finished:(BOOL)finished + completed:(nullable SDInternalCompletionBlock)completedBlock { + // Grab the image cache to use, choose standalone original cache firstly + id imageCache = context[SDWebImageContextOriginalImageCache]; + if (!imageCache) { + // if no standalone cache available, use default cache + imageCache = context[SDWebImageContextImageCache]; + if (!imageCache) { + imageCache = self.imageCache; + } + } + // the original store image cache type + SDImageCacheType originalStoreCacheType = SDImageCacheTypeDisk; + if (context[SDWebImageContextOriginalStoreCacheType]) { + originalStoreCacheType = [context[SDWebImageContextOriginalStoreCacheType] integerValue]; + } + id cacheSerializer = context[SDWebImageContextCacheSerializer]; + + // If the original cacheType is disk, since we don't need to store the original data again + // Strip the disk from the originalStoreCacheType + if (cacheType == SDImageCacheTypeDisk) { + if (originalStoreCacheType == SDImageCacheTypeDisk) originalStoreCacheType = SDImageCacheTypeNone; + if (originalStoreCacheType == SDImageCacheTypeAll) originalStoreCacheType = SDImageCacheTypeMemory; + } + + // Get original cache key generation without transformer + NSString *key = [self originalCacheKeyForURL:url context:context]; + if (finished && cacheSerializer && (originalStoreCacheType == SDImageCacheTypeDisk || originalStoreCacheType == SDImageCacheTypeAll)) { + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ + NSData *newOriginalData = [cacheSerializer cacheDataWithImage:originalImage originalData:originalData imageURL:url]; + // Store original image and data + [self storeImage:originalImage imageData:newOriginalData forKey:key options:options context:context imageCache:imageCache cacheType:originalStoreCacheType finished:finished completion:^{ + // Continue store cache process, transformed data is nil + [self callStoreCacheProcessForOperation:operation url:url options:options context:context image:cacheImage data:cacheData cacheType:cacheType finished:finished completed:completedBlock]; + }]; + }); + } else { + // Store original image and data + [self storeImage:originalImage imageData:originalData forKey:key options:options context:context imageCache:imageCache cacheType:originalStoreCacheType finished:finished completion:^{ + // Continue store cache process, transformed data is nil + [self callStoreCacheProcessForOperation:operation url:url options:options context:context image:cacheImage data:cacheData cacheType:cacheType finished:finished completed:completedBlock]; + }]; + } +} + +// Store normal cache process +- (void)callStoreCacheProcessForOperation:(nonnull SDWebImageCombinedOperation *)operation + url:(nonnull NSURL *)url + options:(SDWebImageOptions)options + context:(SDWebImageContext *)context + image:(nullable UIImage *)image + data:(nullable NSData *)data + cacheType:(SDImageCacheType)cacheType + finished:(BOOL)finished + completed:(nullable SDInternalCompletionBlock)completedBlock { + // Grab the image cache to use + id imageCache = context[SDWebImageContextImageCache]; + if (!imageCache) { + imageCache = self.imageCache; + } + // the target image store cache type + SDImageCacheType storeCacheType = SDImageCacheTypeAll; + if (context[SDWebImageContextStoreCacheType]) { + storeCacheType = [context[SDWebImageContextStoreCacheType] integerValue]; + } + id cacheSerializer = context[SDWebImageContextCacheSerializer]; + + // transformed cache key + NSString *key = [self cacheKeyForURL:url context:context]; + if (finished && cacheSerializer && (storeCacheType == SDImageCacheTypeDisk || storeCacheType == SDImageCacheTypeAll)) { + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ + NSData *newData = [cacheSerializer cacheDataWithImage:image originalData:data imageURL:url]; + // Store image and data + [self storeImage:image imageData:newData forKey:key options:options context:context imageCache:imageCache cacheType:storeCacheType finished:finished completion:^{ + [self callCompletionBlockForOperation:operation completion:completedBlock image:image data:data error:nil cacheType:cacheType finished:finished queue:context[SDWebImageContextCallbackQueue] url:url]; + }]; + }); + } else { + // Store image and data + [self storeImage:image imageData:data forKey:key options:options context:context imageCache:imageCache cacheType:storeCacheType finished:finished completion:^{ + [self callCompletionBlockForOperation:operation completion:completedBlock image:image data:data error:nil cacheType:cacheType finished:finished queue:context[SDWebImageContextCallbackQueue] url:url]; + }]; + } +} + +#pragma mark - Helper + +- (void)safelyRemoveOperationFromRunning:(nullable SDWebImageCombinedOperation*)operation { + if (!operation) { + return; + } + SD_LOCK(_runningOperationsLock); + [self.runningOperations removeObject:operation]; + SD_UNLOCK(_runningOperationsLock); +} + +- (void)storeImage:(nullable UIImage *)image + imageData:(nullable NSData *)data + forKey:(nullable NSString *)key + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + imageCache:(nonnull id)imageCache + cacheType:(SDImageCacheType)cacheType + finished:(BOOL)finished + completion:(nullable SDWebImageNoParamsBlock)completion { + BOOL waitStoreCache = SD_OPTIONS_CONTAINS(options, SDWebImageWaitStoreCache); + // Ignore progressive data cache + if (!finished) { + if (completion) { + completion(); + } + return; + } + // Check whether we should wait the store cache finished. If not, callback immediately + if ([imageCache respondsToSelector:@selector(storeImage:imageData:forKey:options:context:cacheType:completion:)]) { + [imageCache storeImage:image imageData:data forKey:key options:options context:context cacheType:cacheType completion:^{ + if (waitStoreCache) { + if (completion) { + completion(); + } + } + }]; + } else { + [imageCache storeImage:image imageData:data forKey:key cacheType:cacheType completion:^{ + if (waitStoreCache) { + if (completion) { + completion(); + } + } + }]; + } + if (!waitStoreCache) { + if (completion) { + completion(); + } + } +} + +- (void)callCompletionBlockForOperation:(nullable SDWebImageCombinedOperation*)operation + completion:(nullable SDInternalCompletionBlock)completionBlock + error:(nullable NSError *)error + queue:(nullable SDCallbackQueue *)queue + url:(nullable NSURL *)url { + [self callCompletionBlockForOperation:operation completion:completionBlock image:nil data:nil error:error cacheType:SDImageCacheTypeNone finished:YES queue:queue url:url]; +} + +- (void)callCompletionBlockForOperation:(nullable SDWebImageCombinedOperation*)operation + completion:(nullable SDInternalCompletionBlock)completionBlock + image:(nullable UIImage *)image + data:(nullable NSData *)data + error:(nullable NSError *)error + cacheType:(SDImageCacheType)cacheType + finished:(BOOL)finished + queue:(nullable SDCallbackQueue *)queue + url:(nullable NSURL *)url { + if (completionBlock) { + [(queue ?: SDCallbackQueue.mainQueue) async:^{ + completionBlock(image, data, error, cacheType, finished, url); + }]; + } +} + +- (BOOL)shouldBlockFailedURLWithURL:(nonnull NSURL *)url + error:(nonnull NSError *)error + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context { + id imageLoader = context[SDWebImageContextImageLoader]; + if (!imageLoader) { + imageLoader = self.imageLoader; + } + // Check whether we should block failed url + BOOL shouldBlockFailedURL; + if ([self.delegate respondsToSelector:@selector(imageManager:shouldBlockFailedURL:withError:)]) { + shouldBlockFailedURL = [self.delegate imageManager:self shouldBlockFailedURL:url withError:error]; + } else { + if ([imageLoader respondsToSelector:@selector(shouldBlockFailedURLWithURL:error:options:context:)]) { + shouldBlockFailedURL = [imageLoader shouldBlockFailedURLWithURL:url error:error options:options context:context]; + } else { + shouldBlockFailedURL = [imageLoader shouldBlockFailedURLWithURL:url error:error]; + } + } + + return shouldBlockFailedURL; +} + +- (SDWebImageOptionsResult *)processedResultForURL:(NSURL *)url options:(SDWebImageOptions)options context:(SDWebImageContext *)context { + SDWebImageOptionsResult *result; + SDWebImageMutableContext *mutableContext = [SDWebImageMutableContext dictionary]; + + // Image Transformer from manager + if (!context[SDWebImageContextImageTransformer]) { + id transformer = self.transformer; + [mutableContext setValue:transformer forKey:SDWebImageContextImageTransformer]; + } + // Cache key filter from manager + if (!context[SDWebImageContextCacheKeyFilter]) { + id cacheKeyFilter = self.cacheKeyFilter; + [mutableContext setValue:cacheKeyFilter forKey:SDWebImageContextCacheKeyFilter]; + } + // Cache serializer from manager + if (!context[SDWebImageContextCacheSerializer]) { + id cacheSerializer = self.cacheSerializer; + [mutableContext setValue:cacheSerializer forKey:SDWebImageContextCacheSerializer]; + } + + if (mutableContext.count > 0) { + if (context) { + [mutableContext addEntriesFromDictionary:context]; + } + context = [mutableContext copy]; + } + + // Apply options processor + if (self.optionsProcessor) { + result = [self.optionsProcessor processedResultForURL:url options:options context:context]; + } + if (!result) { + // Use default options result + result = [[SDWebImageOptionsResult alloc] initWithOptions:options context:context]; + } + + return result; +} + +@end + + +@implementation SDWebImageCombinedOperation + +- (BOOL)isCancelled { + // Need recursive lock (user's cancel block may check isCancelled), do not use SD_LOCK + @synchronized (self) { + return _cancelled; + } +} + +- (void)cancel { + // Need recursive lock (user's cancel block may check isCancelled), do not use SD_LOCK + @synchronized(self) { + if (_cancelled) { + return; + } + _cancelled = YES; + if (self.cacheOperation) { + [self.cacheOperation cancel]; + self.cacheOperation = nil; + } + if (self.loaderOperation) { + [self.loaderOperation cancel]; + self.loaderOperation = nil; + } + [self.manager safelyRemoveOperationFromRunning:self]; + } +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDWebImageOperation.h b/Pods/SDWebImage/SDWebImage/Core/SDWebImageOperation.h new file mode 100644 index 0000000..bc4224f --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDWebImageOperation.h @@ -0,0 +1,27 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import + +/// A protocol represents cancelable operation. +@protocol SDWebImageOperation + +/// Cancel the operation +- (void)cancel; + +@optional + +/// Whether the operation has been cancelled. +@property (nonatomic, assign, readonly, getter=isCancelled) BOOL cancelled; + +@end + +/// NSOperation conform to `SDWebImageOperation`. +@interface NSOperation (SDWebImageOperation) + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDWebImageOperation.m b/Pods/SDWebImage/SDWebImage/Core/SDWebImageOperation.m new file mode 100644 index 0000000..0d6e880 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDWebImageOperation.m @@ -0,0 +1,14 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageOperation.h" + +/// NSOperation conform to `SDWebImageOperation`. +@implementation NSOperation (SDWebImageOperation) + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDWebImageOptionsProcessor.h b/Pods/SDWebImage/SDWebImage/Core/SDWebImageOptionsProcessor.h new file mode 100644 index 0000000..361dfed --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDWebImageOptionsProcessor.h @@ -0,0 +1,78 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" +#import "SDWebImageDefine.h" + +@class SDWebImageOptionsResult; + +typedef SDWebImageOptionsResult * _Nullable(^SDWebImageOptionsProcessorBlock)(NSURL * _Nullable url, SDWebImageOptions options, SDWebImageContext * _Nullable context); + +/** + The options result contains both options and context. + */ +@interface SDWebImageOptionsResult : NSObject + +/** + WebCache options. + */ +@property (nonatomic, assign, readonly) SDWebImageOptions options; + +/** + Context options. + */ +@property (nonatomic, copy, readonly, nullable) SDWebImageContext *context; + +/** + Create a new options result. + + @param options options + @param context context + @return The options result contains both options and context. + */ +- (nonnull instancetype)initWithOptions:(SDWebImageOptions)options context:(nullable SDWebImageContext *)context; + +- (nonnull instancetype)init NS_UNAVAILABLE; ++ (nonnull instancetype)new NS_UNAVAILABLE; + +@end + +/** + This is the protocol for options processor. + Options processor can be used, to control the final result for individual image request's `SDWebImageOptions` and `SDWebImageContext` + Implements the protocol to have a global control for each indivadual image request's option. + */ +@protocol SDWebImageOptionsProcessor + +/** + Return the processed options result for specify image URL, with its options and context + + @param url The URL to the image + @param options A mask to specify options to use for this request + @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + @return The processed result, contains both options and context + */ +- (nullable SDWebImageOptionsResult *)processedResultForURL:(nullable NSURL *)url + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context; + +@end + +/** + A options processor class with block. + */ +@interface SDWebImageOptionsProcessor : NSObject + +- (nonnull instancetype)initWithBlock:(nonnull SDWebImageOptionsProcessorBlock)block; ++ (nonnull instancetype)optionsProcessorWithBlock:(nonnull SDWebImageOptionsProcessorBlock)block; + +- (nonnull instancetype)init NS_UNAVAILABLE; ++ (nonnull instancetype)new NS_UNAVAILABLE; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDWebImageOptionsProcessor.m b/Pods/SDWebImage/SDWebImage/Core/SDWebImageOptionsProcessor.m new file mode 100644 index 0000000..8e7bc35 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDWebImageOptionsProcessor.m @@ -0,0 +1,59 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageOptionsProcessor.h" + +@interface SDWebImageOptionsResult () + +@property (nonatomic, assign) SDWebImageOptions options; +@property (nonatomic, copy, nullable) SDWebImageContext *context; + +@end + +@implementation SDWebImageOptionsResult + +- (instancetype)initWithOptions:(SDWebImageOptions)options context:(SDWebImageContext *)context { + self = [super init]; + if (self) { + self.options = options; + self.context = context; + } + return self; +} + +@end + +@interface SDWebImageOptionsProcessor () + +@property (nonatomic, copy, nonnull) SDWebImageOptionsProcessorBlock block; + +@end + +@implementation SDWebImageOptionsProcessor + +- (instancetype)initWithBlock:(SDWebImageOptionsProcessorBlock)block { + self = [super init]; + if (self) { + self.block = block; + } + return self; +} + ++ (instancetype)optionsProcessorWithBlock:(SDWebImageOptionsProcessorBlock)block { + SDWebImageOptionsProcessor *optionsProcessor = [[SDWebImageOptionsProcessor alloc] initWithBlock:block]; + return optionsProcessor; +} + +- (SDWebImageOptionsResult *)processedResultForURL:(NSURL *)url options:(SDWebImageOptions)options context:(SDWebImageContext *)context { + if (!self.block) { + return nil; + } + return self.block(url, options, context); +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDWebImagePrefetcher.h b/Pods/SDWebImage/SDWebImage/Core/SDWebImagePrefetcher.h new file mode 100644 index 0000000..2256cc0 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDWebImagePrefetcher.h @@ -0,0 +1,168 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageManager.h" + +@class SDWebImagePrefetcher; + +/** + A token represents a list of URLs, can be used to cancel the download. + */ +@interface SDWebImagePrefetchToken : NSObject + +/** + * Cancel the current prefetching. + */ +- (void)cancel; + +/** + list of URLs of current prefetching. + */ +@property (nonatomic, copy, readonly, nullable) NSArray *urls; + +@end + +/** + The prefetcher delegate protocol + */ +@protocol SDWebImagePrefetcherDelegate + +@optional + +/** + * Called when an image was prefetched. Which means it's called when one URL from any of prefetching finished. + * + * @param imagePrefetcher The current image prefetcher + * @param imageURL The image url that was prefetched + * @param finishedCount The total number of images that were prefetched (successful or not) + * @param totalCount The total number of images that were to be prefetched + */ +- (void)imagePrefetcher:(nonnull SDWebImagePrefetcher *)imagePrefetcher didPrefetchURL:(nullable NSURL *)imageURL finishedCount:(NSUInteger)finishedCount totalCount:(NSUInteger)totalCount; + +/** + * Called when all images are prefetched. Which means it's called when all URLs from all of prefetching finished. + * @param imagePrefetcher The current image prefetcher + * @param totalCount The total number of images that were prefetched (whether successful or not) + * @param skippedCount The total number of images that were skipped + */ +- (void)imagePrefetcher:(nonnull SDWebImagePrefetcher *)imagePrefetcher didFinishWithTotalCount:(NSUInteger)totalCount skippedCount:(NSUInteger)skippedCount; + +@end + +typedef void(^SDWebImagePrefetcherProgressBlock)(NSUInteger noOfFinishedUrls, NSUInteger noOfTotalUrls); +typedef void(^SDWebImagePrefetcherCompletionBlock)(NSUInteger noOfFinishedUrls, NSUInteger noOfSkippedUrls); + +/** + * Prefetch some URLs in the cache for future use. Images are downloaded in low priority. + */ +@interface SDWebImagePrefetcher : NSObject + +/** + * The web image manager used by prefetcher to prefetch images. + * @note You can specify a standalone manager and downloader with custom configuration suitable for image prefetching. Such as `currentDownloadCount` or `downloadTimeout`. + */ +@property (strong, nonatomic, readonly, nonnull) SDWebImageManager *manager; + +/** + * Maximum number of URLs to prefetch at the same time. Defaults to 3. + */ +@property (nonatomic, assign) NSUInteger maxConcurrentPrefetchCount; + +/** + * The options for prefetcher. Defaults to SDWebImageLowPriority. + * @deprecated Prefetcher is designed to be used shared and should not effect others. So in 5.15.0 we added API `prefetchURLs:options:context:`. If you want global control, try to use `SDWebImageOptionsProcessor` in manager level. + */ +@property (nonatomic, assign) SDWebImageOptions options API_DEPRECATED("Use individual prefetch options param instead", macos(10.10, API_TO_BE_DEPRECATED), ios(8.0, API_TO_BE_DEPRECATED), tvos(9.0, API_TO_BE_DEPRECATED), watchos(2.0, API_TO_BE_DEPRECATED)); + +/** + * The context for prefetcher. Defaults to nil. + * @deprecated Prefetcher is designed to be used shared and should not effect others. So in 5.15.0 we added API `prefetchURLs:options:context:`. If you want global control, try to use `SDWebImageOptionsProcessor` in `SDWebImageManager.optionsProcessor`. + */ +@property (nonatomic, copy, nullable) SDWebImageContext *context API_DEPRECATED("Use individual prefetch context param instead", macos(10.10, API_TO_BE_DEPRECATED), ios(8.0, API_TO_BE_DEPRECATED), tvos(9.0, API_TO_BE_DEPRECATED), watchos(2.0, API_TO_BE_DEPRECATED)); + +/** + * Queue options for prefetcher when call the progressBlock, completionBlock and delegate methods. Defaults to Main Queue. + * @deprecated 5.15.0 introduce SDCallbackQueue, use that is preferred and has higher priority. The set/get to this property will translate to that instead. + * @note The call is asynchronously to avoid blocking target queue. (see SDCallbackPolicyDispatch) + * @note The delegate queue should be set before any prefetching start and may not be changed during prefetching to avoid thread-safe problem. + */ +@property (strong, nonatomic, nonnull) dispatch_queue_t delegateQueue API_DEPRECATED("Use SDWebImageContextCallbackQueue context param instead, see SDCallbackQueue", macos(10.10, 10.10), ios(8.0, 8.0), tvos(9.0, 9.0), watchos(2.0, 2.0)); + +/** + * The delegate for the prefetcher. Defaults to nil. + */ +@property (weak, nonatomic, nullable) id delegate; + +/** + * Returns the global shared image prefetcher instance. It use a standalone manager which is different from shared manager. + */ +@property (nonatomic, class, readonly, nonnull) SDWebImagePrefetcher *sharedImagePrefetcher; + +/** + * Allows you to instantiate a prefetcher with any arbitrary image manager. + */ +- (nonnull instancetype)initWithImageManager:(nonnull SDWebImageManager *)manager NS_DESIGNATED_INITIALIZER; + +/** + * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching. It based on the image manager so the image may from the cache and network according to the `options` property. + * Prefetching is separate to each other, which means the progressBlock and completionBlock you provide is bind to the prefetching for the list of urls. + * Attention that call this will not cancel previous fetched urls. You should keep the token return by this to cancel or cancel all the prefetch. + * + * @param urls list of URLs to prefetch + * @return the token to cancel the current prefetching. + */ +- (nullable SDWebImagePrefetchToken *)prefetchURLs:(nullable NSArray *)urls; + +/** + * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching. It based on the image manager so the image may from the cache and network according to the `options` property. + * Prefetching is separate to each other, which means the progressBlock and completionBlock you provide is bind to the prefetching for the list of urls. + * Attention that call this will not cancel previous fetched urls. You should keep the token return by this to cancel or cancel all the prefetch. + * + * @param urls list of URLs to prefetch + * @param progressBlock block to be called when progress updates; + * first parameter is the number of completed (successful or not) requests, + * second parameter is the total number of images originally requested to be prefetched + * @param completionBlock block to be called when the current prefetching is completed + * first param is the number of completed (successful or not) requests, + * second parameter is the number of skipped requests + * @return the token to cancel the current prefetching. + */ +- (nullable SDWebImagePrefetchToken *)prefetchURLs:(nullable NSArray *)urls + progress:(nullable SDWebImagePrefetcherProgressBlock)progressBlock + completed:(nullable SDWebImagePrefetcherCompletionBlock)completionBlock; + +/** + * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching. It based on the image manager so the image may from the cache and network according to the `options` property. + * Prefetching is separate to each other, which means the progressBlock and completionBlock you provide is bind to the prefetching for the list of urls. + * Attention that call this will not cancel previous fetched urls. You should keep the token return by this to cancel or cancel all the prefetch. + * + * @param urls list of URLs to prefetch + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + * @param progressBlock block to be called when progress updates; + * first parameter is the number of completed (successful or not) requests, + * second parameter is the total number of images originally requested to be prefetched + * @param completionBlock block to be called when the current prefetching is completed + * first param is the number of completed (successful or not) requests, + * second parameter is the number of skipped requests + * @return the token to cancel the current prefetching. + */ +- (nullable SDWebImagePrefetchToken *)prefetchURLs:(nullable NSArray *)urls + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDWebImagePrefetcherProgressBlock)progressBlock + completed:(nullable SDWebImagePrefetcherCompletionBlock)completionBlock; + +/** + * Remove and cancel all the prefeching for the prefetcher. + */ +- (void)cancelPrefetching; + + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDWebImagePrefetcher.m b/Pods/SDWebImage/SDWebImage/Core/SDWebImagePrefetcher.m new file mode 100644 index 0000000..1a385f5 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDWebImagePrefetcher.m @@ -0,0 +1,341 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImagePrefetcher.h" +#import "SDAsyncBlockOperation.h" +#import "SDCallbackQueue.h" +#import "SDInternalMacros.h" +#import + +@interface SDCallbackQueue () + +@property (nonatomic, strong, nonnull) dispatch_queue_t queue; + +@end + +@interface SDWebImagePrefetchToken () { + @public + // Though current implementation, `SDWebImageManager` completion block is always on main queue. But however, there is no guarantee in docs. And we may introduce config to specify custom queue in the future. + // These value are just used as incrementing counter, keep thread-safe using memory_order_relaxed for performance. + atomic_ulong _skippedCount; + atomic_ulong _finishedCount; + atomic_flag _isAllFinished; + + unsigned long _totalCount; + + // Used to ensure NSPointerArray thread safe + SD_LOCK_DECLARE(_prefetchOperationsLock); + SD_LOCK_DECLARE(_loadOperationsLock); +} + +@property (nonatomic, copy, readwrite) NSArray *urls; +@property (nonatomic, strong) NSPointerArray *loadOperations; +@property (nonatomic, strong) NSPointerArray *prefetchOperations; +@property (nonatomic, weak) SDWebImagePrefetcher *prefetcher; +@property (nonatomic, assign) SDWebImageOptions options; +@property (nonatomic, copy, nullable) SDWebImageContext *context; +@property (nonatomic, copy, nullable) SDWebImagePrefetcherCompletionBlock completionBlock; +@property (nonatomic, copy, nullable) SDWebImagePrefetcherProgressBlock progressBlock; + +@end + +@interface SDWebImagePrefetcher () + +@property (strong, nonatomic, nonnull) SDWebImageManager *manager; +@property (strong, atomic, nonnull) NSMutableSet *runningTokens; +@property (strong, nonatomic, nonnull) NSOperationQueue *prefetchQueue; +@property (strong, nonatomic, nullable) SDCallbackQueue *callbackQueue; + +@end + +@implementation SDWebImagePrefetcher + ++ (nonnull instancetype)sharedImagePrefetcher { + static dispatch_once_t once; + static id instance; + dispatch_once(&once, ^{ + instance = [self new]; + }); + return instance; +} + +- (nonnull instancetype)init { + return [self initWithImageManager:[SDWebImageManager new]]; +} + +- (nonnull instancetype)initWithImageManager:(SDWebImageManager *)manager { + if ((self = [super init])) { + _manager = manager; + _runningTokens = [NSMutableSet set]; + _options = SDWebImageLowPriority; + _prefetchQueue = [NSOperationQueue new]; + self.maxConcurrentPrefetchCount = 3; + } + return self; +} + +- (void)setMaxConcurrentPrefetchCount:(NSUInteger)maxConcurrentPrefetchCount { + self.prefetchQueue.maxConcurrentOperationCount = maxConcurrentPrefetchCount; +} + +- (NSUInteger)maxConcurrentPrefetchCount { + return self.prefetchQueue.maxConcurrentOperationCount; +} + +- (void)setDelegateQueue:(dispatch_queue_t)delegateQueue { + // Deprecate and translate to SDCallbackQueue + _callbackQueue = [[SDCallbackQueue alloc] initWithDispatchQueue:delegateQueue]; + _callbackQueue.policy = SDCallbackPolicyDispatch; +} + +- (dispatch_queue_t)delegateQueue { + // Deprecate and translate to SDCallbackQueue + return (_callbackQueue ?: SDCallbackQueue.mainQueue).queue; +} + +#pragma mark - Prefetch +- (nullable SDWebImagePrefetchToken *)prefetchURLs:(nullable NSArray *)urls { + return [self prefetchURLs:urls progress:nil completed:nil]; +} + +- (nullable SDWebImagePrefetchToken *)prefetchURLs:(nullable NSArray *)urls + progress:(nullable SDWebImagePrefetcherProgressBlock)progressBlock + completed:(nullable SDWebImagePrefetcherCompletionBlock)completionBlock { + return [self prefetchURLs:urls options:self.options context:self.context progress:progressBlock completed:completionBlock]; +} + +- (nullable SDWebImagePrefetchToken *)prefetchURLs:(nullable NSArray *)urls + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDWebImagePrefetcherProgressBlock)progressBlock + completed:(nullable SDWebImagePrefetcherCompletionBlock)completionBlock { + if (!urls || urls.count == 0) { + if (completionBlock) { + completionBlock(0, 0); + } + return nil; + } + SDWebImagePrefetchToken *token = [SDWebImagePrefetchToken new]; + token.prefetcher = self; + token.urls = urls; + token.options = options; + token.context = context; + token->_skippedCount = 0; + token->_finishedCount = 0; + token->_totalCount = token.urls.count; + atomic_flag_clear(&(token->_isAllFinished)); + token.loadOperations = [NSPointerArray weakObjectsPointerArray]; + token.prefetchOperations = [NSPointerArray weakObjectsPointerArray]; + token.progressBlock = progressBlock; + token.completionBlock = completionBlock; + [self addRunningToken:token]; + [self startPrefetchWithToken:token]; + + return token; +} + +- (void)startPrefetchWithToken:(SDWebImagePrefetchToken * _Nonnull)token { + for (NSURL *url in token.urls) { + @weakify(self); + SDAsyncBlockOperation *prefetchOperation = [SDAsyncBlockOperation blockOperationWithBlock:^(SDAsyncBlockOperation * _Nonnull asyncOperation) { + @strongify(self); + if (!self || asyncOperation.isCancelled) { + return; + } + id operation = [self.manager loadImageWithURL:url options:token.options context:token.context progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) { + @strongify(self); + if (!self) { + return; + } + if (!finished) { + return; + } + atomic_fetch_add_explicit(&(token->_finishedCount), 1, memory_order_relaxed); + if (error) { + // Add last failed + atomic_fetch_add_explicit(&(token->_skippedCount), 1, memory_order_relaxed); + } + + // Current operation finished + [self callProgressBlockForToken:token imageURL:imageURL]; + + if (atomic_load_explicit(&(token->_finishedCount), memory_order_relaxed) == token->_totalCount) { + // All finished + if (!atomic_flag_test_and_set_explicit(&(token->_isAllFinished), memory_order_relaxed)) { + [self callCompletionBlockForToken:token]; + [self removeRunningToken:token]; + } + } + [asyncOperation complete]; + }]; + NSAssert(operation != nil, @"Operation should not be nil, [SDWebImageManager loadImageWithURL:options:context:progress:completed:] break prefetch logic"); + SD_LOCK(token->_loadOperationsLock); + [token.loadOperations addPointer:(__bridge void *)operation]; + SD_UNLOCK(token->_loadOperationsLock); + }]; + SD_LOCK(token->_prefetchOperationsLock); + [token.prefetchOperations addPointer:(__bridge void *)prefetchOperation]; + SD_UNLOCK(token->_prefetchOperationsLock); + [self.prefetchQueue addOperation:prefetchOperation]; + } +} + +#pragma mark - Cancel +- (void)cancelPrefetching { + @synchronized(self.runningTokens) { + NSSet *copiedTokens = [self.runningTokens copy]; + [copiedTokens makeObjectsPerformSelector:@selector(cancel)]; + [self.runningTokens removeAllObjects]; + } +} + +- (void)callProgressBlockForToken:(SDWebImagePrefetchToken *)token imageURL:(NSURL *)url { + if (!token) { + return; + } + BOOL shouldCallDelegate = [self.delegate respondsToSelector:@selector(imagePrefetcher:didPrefetchURL:finishedCount:totalCount:)]; + NSUInteger tokenFinishedCount = [self tokenFinishedCount]; + NSUInteger tokenTotalCount = [self tokenTotalCount]; + NSUInteger finishedCount = atomic_load_explicit(&(token->_finishedCount), memory_order_relaxed); + NSUInteger totalCount = token->_totalCount; + SDCallbackQueue *queue = token.context[SDWebImageContextCallbackQueue]; + if (!queue) { + queue = self.callbackQueue; + } + [(queue ?: SDCallbackQueue.mainQueue) async:^{ + if (shouldCallDelegate) { + [self.delegate imagePrefetcher:self didPrefetchURL:url finishedCount:tokenFinishedCount totalCount:tokenTotalCount]; + } + if (token.progressBlock) { + token.progressBlock(finishedCount, totalCount); + } + }]; +} + +- (void)callCompletionBlockForToken:(SDWebImagePrefetchToken *)token { + if (!token) { + return; + } + BOOL shoulCallDelegate = [self.delegate respondsToSelector:@selector(imagePrefetcher:didFinishWithTotalCount:skippedCount:)] && ([self countOfRunningTokens] == 1); // last one + NSUInteger tokenTotalCount = [self tokenTotalCount]; + NSUInteger tokenSkippedCount = [self tokenSkippedCount]; + NSUInteger finishedCount = atomic_load_explicit(&(token->_finishedCount), memory_order_relaxed); + NSUInteger skippedCount = atomic_load_explicit(&(token->_skippedCount), memory_order_relaxed); + SDCallbackQueue *queue = token.context[SDWebImageContextCallbackQueue]; + if (!queue) { + queue = self.callbackQueue; + } + [(queue ?: SDCallbackQueue.mainQueue) async:^{ + if (shoulCallDelegate) { + [self.delegate imagePrefetcher:self didFinishWithTotalCount:tokenTotalCount skippedCount:tokenSkippedCount]; + } + if (token.completionBlock) { + token.completionBlock(finishedCount, skippedCount); + } + }]; +} + +#pragma mark - Helper +- (NSUInteger)tokenTotalCount { + NSUInteger tokenTotalCount = 0; + @synchronized (self.runningTokens) { + for (SDWebImagePrefetchToken *token in self.runningTokens) { + tokenTotalCount += token->_totalCount; + } + } + return tokenTotalCount; +} + +- (NSUInteger)tokenSkippedCount { + NSUInteger tokenSkippedCount = 0; + @synchronized (self.runningTokens) { + for (SDWebImagePrefetchToken *token in self.runningTokens) { + tokenSkippedCount += atomic_load_explicit(&(token->_skippedCount), memory_order_relaxed); + } + } + return tokenSkippedCount; +} + +- (NSUInteger)tokenFinishedCount { + NSUInteger tokenFinishedCount = 0; + @synchronized (self.runningTokens) { + for (SDWebImagePrefetchToken *token in self.runningTokens) { + tokenFinishedCount += atomic_load_explicit(&(token->_finishedCount), memory_order_relaxed); + } + } + return tokenFinishedCount; +} + +- (void)addRunningToken:(SDWebImagePrefetchToken *)token { + if (!token) { + return; + } + @synchronized (self.runningTokens) { + [self.runningTokens addObject:token]; + } +} + +- (void)removeRunningToken:(SDWebImagePrefetchToken *)token { + if (!token) { + return; + } + @synchronized (self.runningTokens) { + [self.runningTokens removeObject:token]; + } +} + +- (NSUInteger)countOfRunningTokens { + NSUInteger count = 0; + @synchronized (self.runningTokens) { + count = self.runningTokens.count; + } + return count; +} + +@end + +@implementation SDWebImagePrefetchToken + +- (instancetype)init { + self = [super init]; + if (self) { + SD_LOCK_INIT(_prefetchOperationsLock); + SD_LOCK_INIT(_loadOperationsLock); + } + return self; +} + +- (void)cancel { + SD_LOCK(_prefetchOperationsLock); + [self.prefetchOperations compact]; + for (id operation in self.prefetchOperations) { + id strongOperation = operation; + if (strongOperation) { + [strongOperation cancel]; + } + } + self.prefetchOperations.count = 0; + SD_UNLOCK(_prefetchOperationsLock); + + SD_LOCK(_loadOperationsLock); + [self.loadOperations compact]; + for (id operation in self.loadOperations) { + id strongOperation = operation; + if (strongOperation) { + [strongOperation cancel]; + } + } + self.loadOperations.count = 0; + SD_UNLOCK(_loadOperationsLock); + + self.completionBlock = nil; + self.progressBlock = nil; + [self.prefetcher removeRunningToken:self]; +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/SDWebImageTransition.h b/Pods/SDWebImage/SDWebImage/Core/SDWebImageTransition.h new file mode 100644 index 0000000..889372e --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDWebImageTransition.h @@ -0,0 +1,131 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +#if SD_UIKIT || SD_MAC +#import "SDImageCache.h" + +#if SD_UIKIT +typedef UIViewAnimationOptions SDWebImageAnimationOptions; +#else +typedef NS_OPTIONS(NSUInteger, SDWebImageAnimationOptions) { + SDWebImageAnimationOptionAllowsImplicitAnimation = 1 << 0, // specify `allowsImplicitAnimation` for the `NSAnimationContext` + + SDWebImageAnimationOptionCurveEaseInOut = 0 << 16, // default + SDWebImageAnimationOptionCurveEaseIn = 1 << 16, + SDWebImageAnimationOptionCurveEaseOut = 2 << 16, + SDWebImageAnimationOptionCurveLinear = 3 << 16, + + SDWebImageAnimationOptionTransitionNone = 0 << 20, // default + SDWebImageAnimationOptionTransitionFlipFromLeft = 1 << 20, + SDWebImageAnimationOptionTransitionFlipFromRight = 2 << 20, + SDWebImageAnimationOptionTransitionCurlUp = 3 << 20, + SDWebImageAnimationOptionTransitionCurlDown = 4 << 20, + SDWebImageAnimationOptionTransitionCrossDissolve = 5 << 20, + SDWebImageAnimationOptionTransitionFlipFromTop = 6 << 20, + SDWebImageAnimationOptionTransitionFlipFromBottom = 7 << 20, +}; +#endif + +typedef void (^SDWebImageTransitionPreparesBlock)(__kindof UIView * _Nonnull view, UIImage * _Nullable image, NSData * _Nullable imageData, SDImageCacheType cacheType, NSURL * _Nullable imageURL); +typedef void (^SDWebImageTransitionAnimationsBlock)(__kindof UIView * _Nonnull view, UIImage * _Nullable image); +typedef void (^SDWebImageTransitionCompletionBlock)(BOOL finished); + +/** + This class is used to provide a transition animation after the view category load image finished. Use this on `sd_imageTransition` in UIView+WebCache.h + for UIKit(iOS & tvOS), we use `+[UIView transitionWithView:duration:options:animations:completion]` for transition animation. + for AppKit(macOS), we use `+[NSAnimationContext runAnimationGroup:completionHandler:]` for transition animation. You can call `+[NSAnimationContext currentContext]` to grab the context during animations block. + @note These transition are provided for basic usage. If you need complicated animation, consider to directly use Core Animation or use `SDWebImageAvoidAutoSetImage` and implement your own after image load finished. + */ +@interface SDWebImageTransition : NSObject + +/** + By default, we set the image to the view at the beginning of the animations. You can disable this and provide custom set image process + */ +@property (nonatomic, assign) BOOL avoidAutoSetImage; +/** + The duration of the transition animation, measured in seconds. Defaults to 0.5. + */ +@property (nonatomic, assign) NSTimeInterval duration; +/** + The timing function used for all animations within this transition animation (macOS). + */ +@property (nonatomic, strong, nullable) CAMediaTimingFunction *timingFunction API_UNAVAILABLE(ios, tvos, watchos) API_DEPRECATED("Use SDWebImageAnimationOptions instead, or grab NSAnimationContext.currentContext and modify the timingFunction", macos(10.10, 10.10)); +/** + A mask of options indicating how you want to perform the animations. + */ +@property (nonatomic, assign) SDWebImageAnimationOptions animationOptions; +/** + A block object to be executed before the animation sequence starts. + */ +@property (nonatomic, copy, nullable) SDWebImageTransitionPreparesBlock prepares; +/** + A block object that contains the changes you want to make to the specified view. + */ +@property (nonatomic, copy, nullable) SDWebImageTransitionAnimationsBlock animations; +/** + A block object to be executed when the animation sequence ends. + */ +@property (nonatomic, copy, nullable) SDWebImageTransitionCompletionBlock completion; + +@end + +/** + Convenience way to create transition. Remember to specify the duration if needed. + for UIKit, these transition just use the correspond `animationOptions`. By default we enable `UIViewAnimationOptionAllowUserInteraction` to allow user interaction during transition. + for AppKit, these transition use Core Animation in `animations`. So your view must be layer-backed. Set `wantsLayer = YES` before you apply it. + */ +@interface SDWebImageTransition (Conveniences) + +/// Fade-in transition. +@property (nonatomic, class, nonnull, readonly) SDWebImageTransition *fadeTransition; +/// Flip from left transition. +@property (nonatomic, class, nonnull, readonly) SDWebImageTransition *flipFromLeftTransition; +/// Flip from right transition. +@property (nonatomic, class, nonnull, readonly) SDWebImageTransition *flipFromRightTransition; +/// Flip from top transition. +@property (nonatomic, class, nonnull, readonly) SDWebImageTransition *flipFromTopTransition; +/// Flip from bottom transition. +@property (nonatomic, class, nonnull, readonly) SDWebImageTransition *flipFromBottomTransition; +/// Curl up transition. +@property (nonatomic, class, nonnull, readonly) SDWebImageTransition *curlUpTransition; +/// Curl down transition. +@property (nonatomic, class, nonnull, readonly) SDWebImageTransition *curlDownTransition; + +/// Fade-in transition with duration. +/// @param duration transition duration, use ease-in-out ++ (nonnull instancetype)fadeTransitionWithDuration:(NSTimeInterval)duration NS_SWIFT_NAME(fade(duration:)); + +/// Flip from left transition with duration. +/// @param duration transition duration, use ease-in-out ++ (nonnull instancetype)flipFromLeftTransitionWithDuration:(NSTimeInterval)duration NS_SWIFT_NAME(flipFromLeft(duration:)); + +/// Flip from right transition with duration. +/// @param duration transition duration, use ease-in-out ++ (nonnull instancetype)flipFromRightTransitionWithDuration:(NSTimeInterval)duration NS_SWIFT_NAME(flipFromRight(duration:)); + +/// Flip from top transition with duration. +/// @param duration transition duration, use ease-in-out ++ (nonnull instancetype)flipFromTopTransitionWithDuration:(NSTimeInterval)duration NS_SWIFT_NAME(flipFromTop(duration:)); + +/// Flip from bottom transition with duration. +/// @param duration transition duration, use ease-in-out ++ (nonnull instancetype)flipFromBottomTransitionWithDuration:(NSTimeInterval)duration NS_SWIFT_NAME(flipFromBottom(duration:)); + +/// Curl up transition with duration. +/// @param duration transition duration, use ease-in-out ++ (nonnull instancetype)curlUpTransitionWithDuration:(NSTimeInterval)duration NS_SWIFT_NAME(curlUp(duration:)); + +/// Curl down transition with duration. +/// @param duration transition duration, use ease-in-out ++ (nonnull instancetype)curlDownTransitionWithDuration:(NSTimeInterval)duration NS_SWIFT_NAME(curlDown(duration:)); + +@end + +#endif diff --git a/Pods/SDWebImage/SDWebImage/Core/SDWebImageTransition.m b/Pods/SDWebImage/SDWebImage/Core/SDWebImageTransition.m new file mode 100644 index 0000000..4990a73 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/SDWebImageTransition.m @@ -0,0 +1,194 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageTransition.h" + +#if SD_UIKIT || SD_MAC + +#if SD_MAC +#import "SDWebImageTransitionInternal.h" +#import "SDInternalMacros.h" + +CAMediaTimingFunction * SDTimingFunctionFromAnimationOptions(SDWebImageAnimationOptions options) { + if (SD_OPTIONS_CONTAINS(SDWebImageAnimationOptionCurveLinear, options)) { + return [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]; + } else if (SD_OPTIONS_CONTAINS(SDWebImageAnimationOptionCurveEaseIn, options)) { + return [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]; + } else if (SD_OPTIONS_CONTAINS(SDWebImageAnimationOptionCurveEaseOut, options)) { + return [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut]; + } else if (SD_OPTIONS_CONTAINS(SDWebImageAnimationOptionCurveEaseInOut, options)) { + return [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; + } else { + return [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]; + } +} + +CATransition * SDTransitionFromAnimationOptions(SDWebImageAnimationOptions options) { + if (SD_OPTIONS_CONTAINS(options, SDWebImageAnimationOptionTransitionCrossDissolve)) { + CATransition *trans = [CATransition animation]; + trans.type = kCATransitionFade; + return trans; + } else if (SD_OPTIONS_CONTAINS(options, SDWebImageAnimationOptionTransitionFlipFromLeft)) { + CATransition *trans = [CATransition animation]; + trans.type = kCATransitionPush; + trans.subtype = kCATransitionFromLeft; + return trans; + } else if (SD_OPTIONS_CONTAINS(options, SDWebImageAnimationOptionTransitionFlipFromRight)) { + CATransition *trans = [CATransition animation]; + trans.type = kCATransitionPush; + trans.subtype = kCATransitionFromRight; + return trans; + } else if (SD_OPTIONS_CONTAINS(options, SDWebImageAnimationOptionTransitionFlipFromTop)) { + CATransition *trans = [CATransition animation]; + trans.type = kCATransitionPush; + trans.subtype = kCATransitionFromTop; + return trans; + } else if (SD_OPTIONS_CONTAINS(options, SDWebImageAnimationOptionTransitionFlipFromBottom)) { + CATransition *trans = [CATransition animation]; + trans.type = kCATransitionPush; + trans.subtype = kCATransitionFromBottom; + return trans; + } else if (SD_OPTIONS_CONTAINS(options, SDWebImageAnimationOptionTransitionCurlUp)) { + CATransition *trans = [CATransition animation]; + trans.type = kCATransitionReveal; + trans.subtype = kCATransitionFromTop; + return trans; + } else if (SD_OPTIONS_CONTAINS(options, SDWebImageAnimationOptionTransitionCurlDown)) { + CATransition *trans = [CATransition animation]; + trans.type = kCATransitionReveal; + trans.subtype = kCATransitionFromBottom; + return trans; + } else { + return nil; + } +} +#endif + +@implementation SDWebImageTransition + +- (instancetype)init { + self = [super init]; + if (self) { + self.duration = 0.5; + } + return self; +} + +@end + +@implementation SDWebImageTransition (Conveniences) + ++ (SDWebImageTransition *)fadeTransition { + return [self fadeTransitionWithDuration:0.5]; +} + ++ (SDWebImageTransition *)fadeTransitionWithDuration:(NSTimeInterval)duration { + SDWebImageTransition *transition = [SDWebImageTransition new]; + transition.duration = duration; +#if SD_UIKIT + transition.animationOptions = UIViewAnimationOptionTransitionCrossDissolve | UIViewAnimationOptionAllowUserInteraction; +#else + transition.animationOptions = SDWebImageAnimationOptionTransitionCrossDissolve; +#endif + return transition; +} + ++ (SDWebImageTransition *)flipFromLeftTransition { + return [self flipFromLeftTransitionWithDuration:0.5]; +} + ++ (SDWebImageTransition *)flipFromLeftTransitionWithDuration:(NSTimeInterval)duration { + SDWebImageTransition *transition = [SDWebImageTransition new]; + transition.duration = duration; +#if SD_UIKIT + transition.animationOptions = UIViewAnimationOptionTransitionFlipFromLeft | UIViewAnimationOptionAllowUserInteraction; +#else + transition.animationOptions = SDWebImageAnimationOptionTransitionFlipFromLeft; +#endif + return transition; +} + ++ (SDWebImageTransition *)flipFromRightTransition { + return [self flipFromRightTransitionWithDuration:0.5]; +} + ++ (SDWebImageTransition *)flipFromRightTransitionWithDuration:(NSTimeInterval)duration { + SDWebImageTransition *transition = [SDWebImageTransition new]; + transition.duration = duration; +#if SD_UIKIT + transition.animationOptions = UIViewAnimationOptionTransitionFlipFromRight | UIViewAnimationOptionAllowUserInteraction; +#else + transition.animationOptions = SDWebImageAnimationOptionTransitionFlipFromRight; +#endif + return transition; +} + ++ (SDWebImageTransition *)flipFromTopTransition { + return [self flipFromTopTransitionWithDuration:0.5]; +} + ++ (SDWebImageTransition *)flipFromTopTransitionWithDuration:(NSTimeInterval)duration { + SDWebImageTransition *transition = [SDWebImageTransition new]; + transition.duration = duration; +#if SD_UIKIT + transition.animationOptions = UIViewAnimationOptionTransitionFlipFromTop | UIViewAnimationOptionAllowUserInteraction; +#else + transition.animationOptions = SDWebImageAnimationOptionTransitionFlipFromTop; +#endif + return transition; +} + ++ (SDWebImageTransition *)flipFromBottomTransition { + return [self flipFromBottomTransitionWithDuration:0.5]; +} + ++ (SDWebImageTransition *)flipFromBottomTransitionWithDuration:(NSTimeInterval)duration { + SDWebImageTransition *transition = [SDWebImageTransition new]; + transition.duration = duration; +#if SD_UIKIT + transition.animationOptions = UIViewAnimationOptionTransitionFlipFromBottom | UIViewAnimationOptionAllowUserInteraction; +#else + transition.animationOptions = SDWebImageAnimationOptionTransitionFlipFromBottom; +#endif + return transition; +} + ++ (SDWebImageTransition *)curlUpTransition { + return [self curlUpTransitionWithDuration:0.5]; +} + ++ (SDWebImageTransition *)curlUpTransitionWithDuration:(NSTimeInterval)duration { + SDWebImageTransition *transition = [SDWebImageTransition new]; + transition.duration = duration; +#if SD_UIKIT + transition.animationOptions = UIViewAnimationOptionTransitionCurlUp | UIViewAnimationOptionAllowUserInteraction; +#else + transition.animationOptions = SDWebImageAnimationOptionTransitionCurlUp; +#endif + return transition; +} + ++ (SDWebImageTransition *)curlDownTransition { + return [self curlDownTransitionWithDuration:0.5]; +} + ++ (SDWebImageTransition *)curlDownTransitionWithDuration:(NSTimeInterval)duration { + SDWebImageTransition *transition = [SDWebImageTransition new]; + transition.duration = duration; +#if SD_UIKIT + transition.animationOptions = UIViewAnimationOptionTransitionCurlDown | UIViewAnimationOptionAllowUserInteraction; +#else + transition.animationOptions = SDWebImageAnimationOptionTransitionCurlDown; +#endif + transition.duration = duration; + return transition; +} + +@end + +#endif diff --git a/Pods/SDWebImage/SDWebImage/Core/UIButton+WebCache.h b/Pods/SDWebImage/SDWebImage/Core/UIButton+WebCache.h new file mode 100644 index 0000000..8a898c7 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/UIButton+WebCache.h @@ -0,0 +1,402 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +#if SD_UIKIT + +#import "SDWebImageManager.h" + +/** + * Integrates SDWebImage async downloading and caching of remote images with UIButton. + */ +@interface UIButton (WebCache) + +#pragma mark - Image + +/** + * Get the current image URL. + * This simply translate to `[self sd_imageURLForState:self.state]` from v5.18.0 + */ +@property (nonatomic, strong, readonly, nullable) NSURL *sd_currentImageURL; + +/** + * Get the image URL for a control state. + * + * @param state Which state you want to know the URL for. The values are described in UIControlState. + */ +- (nullable NSURL *)sd_imageURLForState:(UIControlState)state; + +/** + * Get the image operation key for a control state. + * + * @param state Which state you want to know the URL for. The values are described in UIControlState. + */ +- (nonnull NSString *)sd_imageOperationKeyForState:(UIControlState)state; + +/** + * Set the button `image` with an `url`. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state NS_REFINED_FOR_SWIFT; + +/** + * Set the button `image` with an `url` and a placeholder. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @see sd_setImageWithURL:placeholderImage:options: + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + placeholderImage:(nullable UIImage *)placeholder NS_REFINED_FOR_SWIFT; + +/** + * Set the button `image` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options NS_REFINED_FOR_SWIFT; + +/** + * Set the button `image` with an `url`, placeholder, custom options and context. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context; + +/** + * Set the button `image` with an `url`. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the button `image` with an `url`, placeholder. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + placeholderImage:(nullable UIImage *)placeholder + completed:(nullable SDExternalCompletionBlock)completedBlock NS_REFINED_FOR_SWIFT; + +/** + * Set the button `image` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the button `image` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param progressBlock A block called while image is downloading + * @note the progress block is executed on a background queue + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the button `image` with an `url`, placeholder, custom options and context. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + * @param progressBlock A block called while image is downloading + * @note the progress block is executed on a background queue + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock; + +#pragma mark - Background Image + +/** + * Get the current background image URL. + */ +@property (nonatomic, strong, readonly, nullable) NSURL *sd_currentBackgroundImageURL; + +/** + * Get the background image operation key for a control state. + * + * @param state Which state you want to know the URL for. The values are described in UIControlState. + */ +- (nonnull NSString *)sd_backgroundImageOperationKeyForState:(UIControlState)state; + +/** + * Get the background image URL for a control state. + * + * @param state Which state you want to know the URL for. The values are described in UIControlState. + */ +- (nullable NSURL *)sd_backgroundImageURLForState:(UIControlState)state; + +/** + * Set the button `backgroundImage` with an `url`. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + */ +- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state NS_REFINED_FOR_SWIFT; + +/** + * Set the button `backgroundImage` with an `url` and a placeholder. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @see sd_setImageWithURL:placeholderImage:options: + */ +- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + placeholderImage:(nullable UIImage *)placeholder NS_REFINED_FOR_SWIFT; + +/** + * Set the button `backgroundImage` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + */ +- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options NS_REFINED_FOR_SWIFT; + +/** + * Set the button `backgroundImage` with an `url`, placeholder, custom options and context. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + */ +- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context; + +/** + * Set the button `backgroundImage` with an `url`. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the button `backgroundImage` with an `url`, placeholder. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + placeholderImage:(nullable UIImage *)placeholder + completed:(nullable SDExternalCompletionBlock)completedBlock NS_REFINED_FOR_SWIFT; + +/** + * Set the button `backgroundImage` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the button `backgroundImage` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param progressBlock A block called while image is downloading + * @note the progress block is executed on a background queue + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the button `backgroundImage` with an `url`, placeholder, custom options and context. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + * @param progressBlock A block called while image is downloading + * @note the progress block is executed on a background queue + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock; + +#pragma mark - Cancel + +/** + * Cancel the current image download + */ +- (void)sd_cancelImageLoadForState:(UIControlState)state; + +/** + * Cancel the current backgroundImage download + */ +- (void)sd_cancelBackgroundImageLoadForState:(UIControlState)state; + +@end + +#endif diff --git a/Pods/SDWebImage/SDWebImage/Core/UIButton+WebCache.m b/Pods/SDWebImage/SDWebImage/Core/UIButton+WebCache.m new file mode 100644 index 0000000..a681436 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/UIButton+WebCache.m @@ -0,0 +1,198 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "UIButton+WebCache.h" + +#if SD_UIKIT + +#import "objc/runtime.h" +#import "UIView+WebCacheOperation.h" +#import "UIView+WebCacheState.h" +#import "UIView+WebCache.h" +#import "SDInternalMacros.h" + +@implementation UIButton (WebCache) + +#pragma mark - Image + +- (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state { + [self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder { + [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options { + [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:options progress:nil completed:nil]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options context:(nullable SDWebImageContext *)context { + [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:options context:context progress:nil completed:nil]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:options progress:nil completed:completedBlock]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options progress:(nullable SDImageLoaderProgressBlock)progressBlock completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:options context:nil progress:progressBlock completed:completedBlock]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock { + SDWebImageMutableContext *mutableContext; + if (context) { + mutableContext = [context mutableCopy]; + } else { + mutableContext = [NSMutableDictionary dictionary]; + } + mutableContext[SDWebImageContextSetImageOperationKey] = [self sd_imageOperationKeyForState:state]; + @weakify(self); + [self sd_internalSetImageWithURL:url + placeholderImage:placeholder + options:options + context:mutableContext + setImageBlock:^(UIImage * _Nullable image, NSData * _Nullable imageData, SDImageCacheType cacheType, NSURL * _Nullable imageURL) { + @strongify(self); + [self setImage:image forState:state]; + } + progress:progressBlock + completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) { + if (completedBlock) { + completedBlock(image, error, cacheType, imageURL); + } + }]; +} + +#pragma mark - Background Image + +- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state { + [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil]; +} + +- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder { + [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil]; +} + +- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options { + [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options progress:nil completed:nil]; +} + +- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options context:(nullable SDWebImageContext *)context { + [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options context:context progress:nil completed:nil]; +} + +- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock]; +} + +- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock]; +} + +- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options progress:nil completed:completedBlock]; +} + +- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options progress:(nullable SDImageLoaderProgressBlock)progressBlock completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options context:nil progress:progressBlock completed:completedBlock]; +} + +- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock { + SDWebImageMutableContext *mutableContext; + if (context) { + mutableContext = [context mutableCopy]; + } else { + mutableContext = [NSMutableDictionary dictionary]; + } + mutableContext[SDWebImageContextSetImageOperationKey] = [self sd_backgroundImageOperationKeyForState:state]; + @weakify(self); + [self sd_internalSetImageWithURL:url + placeholderImage:placeholder + options:options + context:mutableContext + setImageBlock:^(UIImage * _Nullable image, NSData * _Nullable imageData, SDImageCacheType cacheType, NSURL * _Nullable imageURL) { + @strongify(self); + [self setBackgroundImage:image forState:state]; + } + progress:progressBlock + completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) { + if (completedBlock) { + completedBlock(image, error, cacheType, imageURL); + } + }]; +} + +#pragma mark - Cancel + +- (void)sd_cancelImageLoadForState:(UIControlState)state { + [self sd_cancelImageLoadOperationWithKey:[self sd_imageOperationKeyForState:state]]; +} + +- (void)sd_cancelBackgroundImageLoadForState:(UIControlState)state { + [self sd_cancelImageLoadOperationWithKey:[self sd_backgroundImageOperationKeyForState:state]]; +} + +#pragma mark - State + +- (NSString *)sd_imageOperationKeyForState:(UIControlState)state { + return [NSString stringWithFormat:@"UIButtonImageOperation%lu", (unsigned long)state]; +} + +- (NSString *)sd_backgroundImageOperationKeyForState:(UIControlState)state { + return [NSString stringWithFormat:@"UIButtonBackgroundImageOperation%lu", (unsigned long)state]; +} + +- (NSURL *)sd_currentImageURL { + NSURL *url = [self sd_imageURLForState:self.state]; + if (!url) { + [self sd_imageURLForState:UIControlStateNormal]; + } + return url; +} + +- (NSURL *)sd_imageURLForState:(UIControlState)state { + return [self sd_imageLoadStateForKey:[self sd_imageOperationKeyForState:state]].url; +} +#pragma mark - Background State + +- (NSURL *)sd_currentBackgroundImageURL { + NSURL *url = [self sd_backgroundImageURLForState:self.state]; + if (!url) { + url = [self sd_backgroundImageURLForState:UIControlStateNormal]; + } + return url; +} + +- (NSURL *)sd_backgroundImageURLForState:(UIControlState)state { + return [self sd_imageLoadStateForKey:[self sd_backgroundImageOperationKeyForState:state]].url; +} + +@end + +#endif diff --git a/Pods/SDWebImage/SDWebImage/Core/UIImage+ExtendedCacheData.h b/Pods/SDWebImage/SDWebImage/Core/UIImage+ExtendedCacheData.h new file mode 100644 index 0000000..482c8c4 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/UIImage+ExtendedCacheData.h @@ -0,0 +1,24 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* (c) Fabrice Aneche +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import +#import "SDWebImageCompat.h" + +@interface UIImage (ExtendedCacheData) + +/** + Read and Write the extended object and bind it to the image. Which can hold some extra metadata like Image's scale factor, URL rich link, date, etc. + The extended object should conforms to NSCoding, which we use `NSKeyedArchiver` and `NSKeyedUnarchiver` to archive it to data, and write to disk cache. + @note The disk cache preserve both of the data and extended data with the same cache key. For manual query, use the `SDDiskCache` protocol method `extendedDataForKey:` instead. + @note You can specify arbitrary object conforms to NSCoding (NSObject protocol here is used to support object using `NS_ROOT_CLASS`, which is not NSObject subclass). If you load image from disk cache, you should check the extended object class to avoid corrupted data. + @warning This object don't need to implements NSSecureCoding (but it's recommended), because we allows arbitrary class. + */ +@property (nonatomic, strong, nullable) id sd_extendedObject; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/UIImage+ExtendedCacheData.m b/Pods/SDWebImage/SDWebImage/Core/UIImage+ExtendedCacheData.m new file mode 100644 index 0000000..05d29cf --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/UIImage+ExtendedCacheData.m @@ -0,0 +1,23 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* (c) Fabrice Aneche +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import "UIImage+ExtendedCacheData.h" +#import + +@implementation UIImage (ExtendedCacheData) + +- (id)sd_extendedObject { + return objc_getAssociatedObject(self, @selector(sd_extendedObject)); +} + +- (void)setSd_extendedObject:(id)sd_extendedObject { + objc_setAssociatedObject(self, @selector(sd_extendedObject), sd_extendedObject, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/UIImage+ForceDecode.h b/Pods/SDWebImage/SDWebImage/Core/UIImage+ForceDecode.h new file mode 100644 index 0000000..658659a --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/UIImage+ForceDecode.h @@ -0,0 +1,52 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +/** + UIImage category about force decode feature (avoid Image/IO's lazy decoding during rendering behavior). + */ +@interface UIImage (ForceDecode) + +/** + A bool value indicating whether the image has already been decoded. This can help to avoid extra force decode. + Force decode is used for 2 cases: + -- 1. for ImageIO created image (via `CGImageCreateWithImageSource` SPI), it's lazy and we trigger the decode before rendering + -- 2. for non-ImageIO created image (via `CGImageCreate` API), we can ensure it's alignment is suitable to render on screen without copy by CoreAnimation + @note For coder plugin developer, always use the SDImageCoderHelper's `colorSpaceGetDeviceRGB`/`preferredPixelFormat` to create CGImage. + @note For more information why force decode, see: https://github.com/path/FastImageCache#byte-alignment + @note From v5.17.0, the default value is always NO. Use `SDImageForceDecodePolicy` to control complicated policy. + */ +@property (nonatomic, assign) BOOL sd_isDecoded; + +/** + Decode the provided image. This is useful if you want to force decode the image before rendering to improve performance. + + @param image The image to be decoded + @return The decoded image + */ ++ (nullable UIImage *)sd_decodedImageWithImage:(nullable UIImage *)image; + +/** + Decode and scale down the provided image + + @param image The image to be decoded + @return The decoded and scaled down image + */ ++ (nullable UIImage *)sd_decodedAndScaledDownImageWithImage:(nullable UIImage *)image; + +/** + Decode and scale down the provided image with limit bytes + + @param image The image to be decoded + @param bytes The limit bytes size. Provide 0 to use the build-in limit. + @return The decoded and scaled down image + */ ++ (nullable UIImage *)sd_decodedAndScaledDownImageWithImage:(nullable UIImage *)image limitBytes:(NSUInteger)bytes; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/UIImage+ForceDecode.m b/Pods/SDWebImage/SDWebImage/Core/UIImage+ForceDecode.m new file mode 100644 index 0000000..17b122e --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/UIImage+ForceDecode.m @@ -0,0 +1,43 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "UIImage+ForceDecode.h" +#import "SDImageCoderHelper.h" +#import "objc/runtime.h" +#import "NSImage+Compatibility.h" + +@implementation UIImage (ForceDecode) + +- (BOOL)sd_isDecoded { + NSNumber *value = objc_getAssociatedObject(self, @selector(sd_isDecoded)); + return [value boolValue]; +} + +- (void)setSd_isDecoded:(BOOL)sd_isDecoded { + objc_setAssociatedObject(self, @selector(sd_isDecoded), @(sd_isDecoded), OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + ++ (nullable UIImage *)sd_decodedImageWithImage:(nullable UIImage *)image { + if (!image) { + return nil; + } + return [SDImageCoderHelper decodedImageWithImage:image]; +} + ++ (nullable UIImage *)sd_decodedAndScaledDownImageWithImage:(nullable UIImage *)image { + return [self sd_decodedAndScaledDownImageWithImage:image limitBytes:0]; +} + ++ (nullable UIImage *)sd_decodedAndScaledDownImageWithImage:(nullable UIImage *)image limitBytes:(NSUInteger)bytes { + if (!image) { + return nil; + } + return [SDImageCoderHelper decodedAndScaledDownImageWithImage:image limitBytes:bytes]; +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/UIImage+GIF.h b/Pods/SDWebImage/SDWebImage/Core/UIImage+GIF.h new file mode 100644 index 0000000..5da8e19 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/UIImage+GIF.h @@ -0,0 +1,26 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * (c) Laurin Brandner + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +/** + This category is just use as a convenience method. For more detail control, use methods in `UIImage+MultiFormat.h` or directly use `SDImageCoder`. + */ +@interface UIImage (GIF) + +/** + Creates an animated UIImage from an NSData. + This will create animated image if the data is Animated GIF. And will create a static image is the data is Static GIF. + + @param data The GIF data + @return The created image + */ ++ (nullable UIImage *)sd_imageWithGIFData:(nullable NSData *)data; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/UIImage+GIF.m b/Pods/SDWebImage/SDWebImage/Core/UIImage+GIF.m new file mode 100644 index 0000000..7158cf3 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/UIImage+GIF.m @@ -0,0 +1,22 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * (c) Laurin Brandner + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "UIImage+GIF.h" +#import "SDImageGIFCoder.h" + +@implementation UIImage (GIF) + ++ (nullable UIImage *)sd_imageWithGIFData:(nullable NSData *)data { + if (!data) { + return nil; + } + return [[SDImageGIFCoder sharedCoder] decodedImageWithData:data options:0]; +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/UIImage+MemoryCacheCost.h b/Pods/SDWebImage/SDWebImage/Core/UIImage+MemoryCacheCost.h new file mode 100644 index 0000000..0ff2f2f --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/UIImage+MemoryCacheCost.h @@ -0,0 +1,27 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +/** + UIImage category for memory cache cost. + */ +@interface UIImage (MemoryCacheCost) + +/** + The memory cache cost for specify image used by image cache. The cost function is the bytes size held in memory. + If you set some associated object to `UIImage`, you can set the custom value to indicate the memory cost. + + For `UIImage`, this method return the single frame bytes size when `image.images` is nil for static image. Return full frame bytes size when `image.images` is not nil for animated image. + For `NSImage`, this method return the single frame bytes size because `NSImage` does not store all frames in memory. + @note Note that because of the limitations of category this property can get out of sync if you create another instance with CGImage or other methods. + @note For custom animated class conforms to `SDAnimatedImage`, you can override this getter method in your subclass to return a more proper value instead, which representing the current frame's total bytes. + */ +@property (assign, nonatomic) NSUInteger sd_memoryCost; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/UIImage+MemoryCacheCost.m b/Pods/SDWebImage/SDWebImage/Core/UIImage+MemoryCacheCost.m new file mode 100644 index 0000000..b936500 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/UIImage+MemoryCacheCost.m @@ -0,0 +1,47 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "UIImage+MemoryCacheCost.h" +#import "objc/runtime.h" +#import "NSImage+Compatibility.h" + +FOUNDATION_STATIC_INLINE NSUInteger SDMemoryCacheCostForImage(UIImage *image) { + CGImageRef imageRef = image.CGImage; + if (!imageRef) { + return 0; + } + NSUInteger bytesPerFrame = CGImageGetBytesPerRow(imageRef) * CGImageGetHeight(imageRef); + NSUInteger frameCount; +#if SD_MAC + frameCount = 1; +#elif SD_UIKIT || SD_WATCH + // Filter the same frame in `_UIAnimatedImage`. + frameCount = image.images.count > 1 ? [NSSet setWithArray:image.images].count : 1; +#endif + NSUInteger cost = bytesPerFrame * frameCount; + return cost; +} + +@implementation UIImage (MemoryCacheCost) + +- (NSUInteger)sd_memoryCost { + NSNumber *value = objc_getAssociatedObject(self, @selector(sd_memoryCost)); + NSUInteger memoryCost; + if (value != nil) { + memoryCost = [value unsignedIntegerValue]; + } else { + memoryCost = SDMemoryCacheCostForImage(self); + } + return memoryCost; +} + +- (void)setSd_memoryCost:(NSUInteger)sd_memoryCost { + objc_setAssociatedObject(self, @selector(sd_memoryCost), @(sd_memoryCost), OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/UIImage+Metadata.h b/Pods/SDWebImage/SDWebImage/Core/UIImage+Metadata.h new file mode 100644 index 0000000..0aea1df --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/UIImage+Metadata.h @@ -0,0 +1,104 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" +#import "NSData+ImageContentType.h" +#import "SDImageCoder.h" + +/** + UIImage category for image metadata, including animation, loop count, format, incremental, etc. + */ +@interface UIImage (Metadata) + +/** + * UIKit: + * For static image format, this value is always 0. + * For animated image format, 0 means infinite looping. + * Note that because of the limitations of categories this property can get out of sync if you create another instance with CGImage or other methods. + * AppKit: + * NSImage currently only support animated via `NSBitmapImageRep`(GIF) or `SDAnimatedImageRep`(APNG/GIF/WebP) unlike UIImage. + * The getter of this property will get the loop count from animated imageRep + * The setter of this property will set the loop count from animated imageRep + * SDAnimatedImage: + * Returns `animatedImageLoopCount` + */ +@property (nonatomic, assign) NSUInteger sd_imageLoopCount; + +/** + * UIKit: + * Returns the `images`'s count by unapply the patch for the different frame durations. Which matches the real visible frame count when displaying on UIImageView. + * See more in `SDImageCoderHelper.animatedImageWithFrames`. + * Returns 1 for static image. + * AppKit: + * Returns the underlaying `NSBitmapImageRep` or `SDAnimatedImageRep` frame count. + * Returns 1 for static image. + * SDAnimatedImage: + * Returns `animatedImageFrameCount` for animated image, 1 for static image. + */ +@property (nonatomic, assign, readonly) NSUInteger sd_imageFrameCount; + +/** + * UIKit: + * Check the `images` array property. + * AppKit: + * NSImage currently only support animated via GIF imageRep unlike UIImage. It will check the imageRep's frame count > 1. + * SDAnimatedImage: + * Check `animatedImageFrameCount` > 1 + */ +@property (nonatomic, assign, readonly) BOOL sd_isAnimated; + +/** + * UIKit: + * Check the `isSymbolImage` property. Also check the system PDF(iOS 11+) && SVG(iOS 13+) support. + * AppKit: + * NSImage supports PDF && SVG && EPS imageRep, check the imageRep class. + * SDAnimatedImage: + * Returns `NO` + */ +@property (nonatomic, assign, readonly) BOOL sd_isVector; + +/** + * The image format represent the original compressed image data format. + * If you don't manually specify a format, this information is retrieve from CGImage using `CGImageGetUTType`, which may return nil for non-CG based image. At this time it will return `SDImageFormatUndefined` as default value. + * @note Note that because of the limitations of categories this property can get out of sync if you create another instance with CGImage or other methods. + * @note For `SDAnimatedImage`, returns `animatedImageFormat` when animated, or fallback when static. + */ +@property (nonatomic, assign) SDImageFormat sd_imageFormat; + +/** + A bool value indicating whether the image is during incremental decoding and may not contains full pixels. + */ +@property (nonatomic, assign) BOOL sd_isIncremental; + +/** + A bool value indicating that the image is transformed from original image, so the image data may not always match original download one. + */ +@property (nonatomic, assign) BOOL sd_isTransformed; + +/** + A bool value indicating that the image is using thumbnail decode with smaller size, so the image data may not always match original download one. + @note This just check `sd_decodeOptions[.decodeThumbnailPixelSize] > CGSize.zero` + */ +@property (nonatomic, assign, readonly) BOOL sd_isThumbnail; + +/** + A dictionary value contains the decode options when decoded from SDWebImage loading system (say, `SDImageCacheDecodeImageData/SDImageLoaderDecode[Progressive]ImageData`) + It may not always available and only image decoding related options will be saved. (including [.decodeScaleFactor, .decodeThumbnailPixelSize, .decodePreserveAspectRatio, .decodeFirstFrameOnly]) + @note This is used to identify and check the image is from thumbnail decoding, and the callback's data **will be nil** (because this time the data saved to disk does not match the image return to you. If you need full size data, query the cache with full size url key) + @warning You should not store object inside which keep strong reference to image itself, which will cause retain cycle. + @warning This API exist only because of current SDWebImageDownloader bad design which does not callback the context we call it. There will be refactor in future (API break), use with caution. + */ +@property (nonatomic, copy) SDImageCoderOptions *sd_decodeOptions; + +/** + A bool value indicating that the image is using HDR + @note Only valid for CGImage based, for CIImage based, the returned value is not correct. + */ +@property (nonatomic, assign, readonly) BOOL sd_isHighDynamicRange; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/UIImage+Metadata.m b/Pods/SDWebImage/SDWebImage/Core/UIImage+Metadata.m new file mode 100644 index 0000000..1e65c2b --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/UIImage+Metadata.m @@ -0,0 +1,236 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "UIImage+Metadata.h" +#import "NSImage+Compatibility.h" +#import "SDInternalMacros.h" +#import "objc/runtime.h" +#import "SDImageCoderHelper.h" + +@implementation UIImage (Metadata) + +#if SD_UIKIT || SD_WATCH + +- (NSUInteger)sd_imageLoopCount { + NSUInteger imageLoopCount = 0; + NSNumber *value = objc_getAssociatedObject(self, @selector(sd_imageLoopCount)); + if ([value isKindOfClass:[NSNumber class]]) { + imageLoopCount = value.unsignedIntegerValue; + } + return imageLoopCount; +} + +- (void)setSd_imageLoopCount:(NSUInteger)sd_imageLoopCount { + NSNumber *value = @(sd_imageLoopCount); + objc_setAssociatedObject(self, @selector(sd_imageLoopCount), value, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +- (NSUInteger)sd_imageFrameCount { + NSArray *animatedImages = self.images; + if (!animatedImages || animatedImages.count <= 1) { + return 1; + } + NSNumber *value = objc_getAssociatedObject(self, @selector(sd_imageFrameCount)); + if ([value isKindOfClass:[NSNumber class]]) { + return [value unsignedIntegerValue]; + } + __block NSUInteger frameCount = 1; + __block UIImage *previousImage = animatedImages.firstObject; + [animatedImages enumerateObjectsUsingBlock:^(UIImage * _Nonnull image, NSUInteger idx, BOOL * _Nonnull stop) { + // ignore first + if (idx == 0) { + return; + } + if (![image isEqual:previousImage]) { + frameCount++; + } + previousImage = image; + }]; + objc_setAssociatedObject(self, @selector(sd_imageFrameCount), @(frameCount), OBJC_ASSOCIATION_RETAIN_NONATOMIC); + + return frameCount; +} + +- (BOOL)sd_isAnimated { + return (self.images != nil); +} + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-performSelector-leaks" +- (BOOL)sd_isVector { + if (@available(iOS 13.0, tvOS 13.0, watchOS 6.0, *)) { + // Xcode 11 supports symbol image, keep Xcode 10 compatible currently + SEL SymbolSelector = NSSelectorFromString(@"isSymbolImage"); + if ([self respondsToSelector:SymbolSelector] && [self performSelector:SymbolSelector]) { + return YES; + } + // SVG + SEL SVGSelector = SD_SEL_SPI(CGSVGDocument); + if ([self respondsToSelector:SVGSelector] && [self performSelector:SVGSelector]) { + return YES; + } + } + if (@available(iOS 11.0, tvOS 11.0, watchOS 4.0, *)) { + // PDF + SEL PDFSelector = SD_SEL_SPI(CGPDFPage); + if ([self respondsToSelector:PDFSelector] && [self performSelector:PDFSelector]) { + return YES; + } + } + return NO; +} +#pragma clang diagnostic pop + +#else + +- (NSUInteger)sd_imageLoopCount { + NSUInteger imageLoopCount = 0; + NSRect imageRect = NSMakeRect(0, 0, self.size.width, self.size.height); + NSImageRep *imageRep = [self bestRepresentationForRect:imageRect context:nil hints:nil]; + NSBitmapImageRep *bitmapImageRep; + if ([imageRep isKindOfClass:[NSBitmapImageRep class]]) { + bitmapImageRep = (NSBitmapImageRep *)imageRep; + } + if (bitmapImageRep) { + imageLoopCount = [[bitmapImageRep valueForProperty:NSImageLoopCount] unsignedIntegerValue]; + } + return imageLoopCount; +} + +- (void)setSd_imageLoopCount:(NSUInteger)sd_imageLoopCount { + NSRect imageRect = NSMakeRect(0, 0, self.size.width, self.size.height); + NSImageRep *imageRep = [self bestRepresentationForRect:imageRect context:nil hints:nil]; + NSBitmapImageRep *bitmapImageRep; + if ([imageRep isKindOfClass:[NSBitmapImageRep class]]) { + bitmapImageRep = (NSBitmapImageRep *)imageRep; + } + if (bitmapImageRep) { + [bitmapImageRep setProperty:NSImageLoopCount withValue:@(sd_imageLoopCount)]; + } +} + +- (NSUInteger)sd_imageFrameCount { + NSRect imageRect = NSMakeRect(0, 0, self.size.width, self.size.height); + NSImageRep *imageRep = [self bestRepresentationForRect:imageRect context:nil hints:nil]; + NSBitmapImageRep *bitmapImageRep; + if ([imageRep isKindOfClass:[NSBitmapImageRep class]]) { + bitmapImageRep = (NSBitmapImageRep *)imageRep; + } + if (bitmapImageRep) { + return [[bitmapImageRep valueForProperty:NSImageFrameCount] unsignedIntegerValue]; + } + return 1; +} + +- (BOOL)sd_isAnimated { + BOOL isAnimated = NO; + NSRect imageRect = NSMakeRect(0, 0, self.size.width, self.size.height); + NSImageRep *imageRep = [self bestRepresentationForRect:imageRect context:nil hints:nil]; + NSBitmapImageRep *bitmapImageRep; + if ([imageRep isKindOfClass:[NSBitmapImageRep class]]) { + bitmapImageRep = (NSBitmapImageRep *)imageRep; + } + if (bitmapImageRep) { + NSUInteger frameCount = [[bitmapImageRep valueForProperty:NSImageFrameCount] unsignedIntegerValue]; + isAnimated = frameCount > 1 ? YES : NO; + } + return isAnimated; +} + +- (BOOL)sd_isVector { + NSRect imageRect = NSMakeRect(0, 0, self.size.width, self.size.height); + // This may returns a NSProxy, so don't use `class` to check + NSImageRep *imageRep = [self bestRepresentationForRect:imageRect context:nil hints:nil]; + if ([imageRep isKindOfClass:[NSPDFImageRep class]]) { + return YES; + } + if ([imageRep isKindOfClass:[NSEPSImageRep class]]) { + return YES; + } + Class NSSVGImageRepClass = NSClassFromString([NSString stringWithFormat:@"_%@", SD_NSSTRING(NSSVGImageRep)]); + if ([imageRep isKindOfClass:NSSVGImageRepClass]) { + return YES; + } + return NO; +} + +#endif + +- (SDImageFormat)sd_imageFormat { + SDImageFormat imageFormat = SDImageFormatUndefined; + NSNumber *value = objc_getAssociatedObject(self, @selector(sd_imageFormat)); + if ([value isKindOfClass:[NSNumber class]]) { + imageFormat = value.integerValue; + return imageFormat; + } + // Check CGImage's UTType, may return nil for non-Image/IO based image + CFStringRef uttype = CGImageGetUTType(self.CGImage); + imageFormat = [NSData sd_imageFormatFromUTType:uttype]; + return imageFormat; +} + +- (void)setSd_imageFormat:(SDImageFormat)sd_imageFormat { + objc_setAssociatedObject(self, @selector(sd_imageFormat), @(sd_imageFormat), OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +- (void)setSd_isIncremental:(BOOL)sd_isIncremental { + objc_setAssociatedObject(self, @selector(sd_isIncremental), @(sd_isIncremental), OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +- (BOOL)sd_isIncremental { + NSNumber *value = objc_getAssociatedObject(self, @selector(sd_isIncremental)); + return value.boolValue; +} + +- (void)setSd_isTransformed:(BOOL)sd_isTransformed { + objc_setAssociatedObject(self, @selector(sd_isTransformed), @(sd_isTransformed), OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +- (BOOL)sd_isTransformed { + NSNumber *value = objc_getAssociatedObject(self, @selector(sd_isTransformed)); + return value.boolValue; +} + +- (void)setSd_decodeOptions:(SDImageCoderOptions *)sd_decodeOptions { + objc_setAssociatedObject(self, @selector(sd_decodeOptions), sd_decodeOptions, OBJC_ASSOCIATION_COPY_NONATOMIC); +} + +-(BOOL)sd_isThumbnail { + CGSize thumbnailSize = CGSizeZero; + NSValue *thumbnailSizeValue = self.sd_decodeOptions[SDImageCoderDecodeThumbnailPixelSize]; + if (thumbnailSizeValue != nil) { + #if SD_MAC + thumbnailSize = thumbnailSizeValue.sizeValue; + #else + thumbnailSize = thumbnailSizeValue.CGSizeValue; + #endif + } + return thumbnailSize.width > 0 && thumbnailSize.height > 0; +} + +- (SDImageCoderOptions *)sd_decodeOptions { + SDImageCoderOptions *value = objc_getAssociatedObject(self, @selector(sd_decodeOptions)); + if ([value isKindOfClass:NSDictionary.class]) { + return value; + } + return nil; +} + +- (BOOL)sd_isHighDynamicRange { +#if SD_MAC + return [SDImageCoderHelper CGImageIsHDR:self.CGImage]; +#else + if (@available(iOS 17, tvOS 17, watchOS 10, *)) { + return self.isHighDynamicRange; + } else { + return [SDImageCoderHelper CGImageIsHDR:self.CGImage]; + } +#endif +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/UIImage+MultiFormat.h b/Pods/SDWebImage/SDWebImage/Core/UIImage+MultiFormat.h new file mode 100644 index 0000000..e495c74 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/UIImage+MultiFormat.h @@ -0,0 +1,81 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" +#import "NSData+ImageContentType.h" + +/** + UIImage category for convenient image format decoding/encoding. + */ +@interface UIImage (MultiFormat) +#pragma mark - Decode +/** + Create and decode a image with the specify image data + + @param data The image data + @return The created image + */ ++ (nullable UIImage *)sd_imageWithData:(nullable NSData *)data; + +/** + Create and decode a image with the specify image data and scale + + @param data The image data + @param scale The image scale factor. Should be greater than or equal to 1.0. + @return The created image + */ ++ (nullable UIImage *)sd_imageWithData:(nullable NSData *)data scale:(CGFloat)scale; + +/** + Create and decode a image with the specify image data and scale, allow specify animate/static control + + @param data The image data + @param scale The image scale factor. Should be greater than or equal to 1.0. + @param firstFrameOnly Even if the image data is animated image format, decode the first frame only as static image. + @return The created image + */ ++ (nullable UIImage *)sd_imageWithData:(nullable NSData *)data scale:(CGFloat)scale firstFrameOnly:(BOOL)firstFrameOnly; + +#pragma mark - Encode +/** + Encode the current image to the data, the image format is unspecified + + @note If the receiver is `SDAnimatedImage`, this will return the animated image data if available. No more extra encoding process. + @note For macOS, if the receiver contains only `SDAnimatedImageRep`, this will return the animated image data if available. No more extra encoding process. + @return The encoded data. If can't encode, return nil + */ +- (nullable NSData *)sd_imageData; + +/** + Encode the current image to data with the specify image format + + @param imageFormat The specify image format + @return The encoded data. If can't encode, return nil + */ +- (nullable NSData *)sd_imageDataAsFormat:(SDImageFormat)imageFormat NS_SWIFT_NAME(sd_imageData(as:)); + +/** + Encode the current image to data with the specify image format and compression quality + + @param imageFormat The specify image format + @param compressionQuality The quality of the resulting image data. Value between 0.0-1.0. Some coders may not support compression quality. + @return The encoded data. If can't encode, return nil + */ +- (nullable NSData *)sd_imageDataAsFormat:(SDImageFormat)imageFormat compressionQuality:(double)compressionQuality NS_SWIFT_NAME(sd_imageData(as:compressionQuality:)); + +/** + Encode the current image to data with the specify image format and compression quality, allow specify animate/static control + + @param imageFormat The specify image format + @param compressionQuality The quality of the resulting image data. Value between 0.0-1.0. Some coders may not support compression quality. + @param firstFrameOnly Even if the image is animated image, encode the first frame only as static image. + @return The encoded data. If can't encode, return nil + */ +- (nullable NSData *)sd_imageDataAsFormat:(SDImageFormat)imageFormat compressionQuality:(double)compressionQuality firstFrameOnly:(BOOL)firstFrameOnly NS_SWIFT_NAME(sd_imageData(as:compressionQuality:firstFrameOnly:)); + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/UIImage+MultiFormat.m b/Pods/SDWebImage/SDWebImage/Core/UIImage+MultiFormat.m new file mode 100644 index 0000000..a569477 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/UIImage+MultiFormat.m @@ -0,0 +1,61 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "UIImage+MultiFormat.h" +#import "SDImageCodersManager.h" +#import "SDAnimatedImageRep.h" +#import "UIImage+Metadata.h" + +@implementation UIImage (MultiFormat) + ++ (nullable UIImage *)sd_imageWithData:(nullable NSData *)data { + return [self sd_imageWithData:data scale:1]; +} + ++ (nullable UIImage *)sd_imageWithData:(nullable NSData *)data scale:(CGFloat)scale { + return [self sd_imageWithData:data scale:scale firstFrameOnly:NO]; +} + ++ (nullable UIImage *)sd_imageWithData:(nullable NSData *)data scale:(CGFloat)scale firstFrameOnly:(BOOL)firstFrameOnly { + if (!data) { + return nil; + } + SDImageCoderOptions *options = @{SDImageCoderDecodeScaleFactor : @(MAX(scale, 1)), SDImageCoderDecodeFirstFrameOnly : @(firstFrameOnly)}; + return [[SDImageCodersManager sharedManager] decodedImageWithData:data options:options]; +} + +- (nullable NSData *)sd_imageData { +#if SD_MAC + NSRect imageRect = NSMakeRect(0, 0, self.size.width, self.size.height); + NSImageRep *imageRep = [self bestRepresentationForRect:imageRect context:nil hints:nil]; + // Check weak animated data firstly + if ([imageRep isKindOfClass:[SDAnimatedImageRep class]]) { + SDAnimatedImageRep *animatedImageRep = (SDAnimatedImageRep *)imageRep; + NSData *imageData = [animatedImageRep animatedImageData]; + if (imageData) { + return imageData; + } + } +#endif + return [self sd_imageDataAsFormat:self.sd_imageFormat]; +} + +- (nullable NSData *)sd_imageDataAsFormat:(SDImageFormat)imageFormat { + return [self sd_imageDataAsFormat:imageFormat compressionQuality:1]; +} + +- (nullable NSData *)sd_imageDataAsFormat:(SDImageFormat)imageFormat compressionQuality:(double)compressionQuality { + return [self sd_imageDataAsFormat:imageFormat compressionQuality:compressionQuality firstFrameOnly:NO]; +} + +- (nullable NSData *)sd_imageDataAsFormat:(SDImageFormat)imageFormat compressionQuality:(double)compressionQuality firstFrameOnly:(BOOL)firstFrameOnly { + SDImageCoderOptions *options = @{SDImageCoderEncodeCompressionQuality : @(compressionQuality), SDImageCoderEncodeFirstFrameOnly : @(firstFrameOnly)}; + return [[SDImageCodersManager sharedManager] encodedDataWithImage:self format:imageFormat options:options]; +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/UIImage+Transform.h b/Pods/SDWebImage/SDWebImage/Core/UIImage+Transform.h new file mode 100644 index 0000000..245c66e --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/UIImage+Transform.h @@ -0,0 +1,164 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +/// The scale mode to apply when image drawing on a container with different sizes. +typedef NS_ENUM(NSUInteger, SDImageScaleMode) { + /// The option to scale the content to fit the size of itself by changing the aspect ratio of the content if necessary. + SDImageScaleModeFill = 0, + /// The option to scale the content to fit the size of the view by maintaining the aspect ratio. Any remaining area of the view’s bounds is transparent. + SDImageScaleModeAspectFit = 1, + /// The option to scale the content to fill the size of the view. Some portion of the content may be clipped to fill the view’s bounds. + SDImageScaleModeAspectFill = 2 +}; + +#if SD_UIKIT || SD_WATCH +typedef UIRectCorner SDRectCorner; +#else +typedef NS_OPTIONS(NSUInteger, SDRectCorner) { + SDRectCornerTopLeft = 1 << 0, + SDRectCornerTopRight = 1 << 1, + SDRectCornerBottomLeft = 1 << 2, + SDRectCornerBottomRight = 1 << 3, + SDRectCornerAllCorners = ~0UL +}; +#endif + +/** + Provide some common method for `UIImage`. + Image process is based on Core Graphics and vImage. + */ +@interface UIImage (Transform) + +#pragma mark - Image Geometry + +/** + Returns a new image which is resized from this image. + You can specify a larger or smaller size than the image size. The image content will be changed with the scale mode. + + @param size The new size to be resized, values should be positive. + @param scaleMode The scale mode for image content. + @return The new image with the given size. + */ +- (nullable UIImage *)sd_resizedImageWithSize:(CGSize)size scaleMode:(SDImageScaleMode)scaleMode; + +/** + Returns a new image which is cropped from this image. + + @param rect Image's inner rect. + @return The new image with the cropping rect. + */ +- (nullable UIImage *)sd_croppedImageWithRect:(CGRect)rect; + +/** + Rounds a new image with a given corner radius and corners. + + @param cornerRadius The radius of each corner oval. Values larger than half the + rectangle's width or height are clamped appropriately to + half the width or height. + @param corners A bitmask value that identifies the corners that you want + rounded. You can use this parameter to round only a subset + of the corners of the rectangle. + @param borderWidth The inset border line width. Values larger than half the rectangle's + width or height are clamped appropriately to half the width + or height. + @param borderColor The border stroke color. nil means clear color. + @return The new image with the round corner. + */ +- (nullable UIImage *)sd_roundedCornerImageWithRadius:(CGFloat)cornerRadius + corners:(SDRectCorner)corners + borderWidth:(CGFloat)borderWidth + borderColor:(nullable UIColor *)borderColor; + +/** + Returns a new rotated image (relative to the center). + + @param angle Rotated radians in counterclockwise.⟲ + @param fitSize YES: new image's size is extend to fit all content. + NO: image's size will not change, content may be clipped. + @return The new image with the rotation. + */ +- (nullable UIImage *)sd_rotatedImageWithAngle:(CGFloat)angle fitSize:(BOOL)fitSize; + +/** + Returns a new horizontally(vertically) flipped image. + + @param horizontal YES to flip the image horizontally. ⇋ + @param vertical YES to flip the image vertically. ⥯ + @return The new image with the flipping. + */ +- (nullable UIImage *)sd_flippedImageWithHorizontal:(BOOL)horizontal vertical:(BOOL)vertical; + +#pragma mark - Image Blending + +/** + Return a tinted image with the given color. This actually use `sourceIn` blend mode. + @note Before 5.20, this API actually use `sourceAtop` and cause naming confusing. After 5.20, we match UIKit's behavior using `sourceIn`. + + @param tintColor The tint color. + @return The new image with the tint color. + */ +- (nullable UIImage *)sd_tintedImageWithColor:(nonnull UIColor *)tintColor; + +/** + Return a tinted image with the given color and blend mode. + @note The blend mode treat `self` as background image (destination), treat `tintColor` as input image (source). So mostly you need `source` variant blend mode (use `sourceIn` not `destinationIn`), which is different from UIKit's `+[UIImage imageWithTintColor:]`. + + @param tintColor The tint color. + @param blendMode The blend mode. + @return The new image with the tint color. + */ +- (nullable UIImage *)sd_tintedImageWithColor:(nonnull UIColor *)tintColor blendMode:(CGBlendMode)blendMode; + +/** + Return the pixel color at specify position. The point is from the top-left to the bottom-right and 0-based. The returned the color is always be RGBA format. The image must be CG-based. + @note The point's x/y will be converted into integer. + @note The point's x/y should not be smaller than 0, or greater than or equal to width/height. + @note The overhead of object creation means this method is best suited for infrequent color sampling. For heavy image processing, grab the raw bitmap data and process yourself. + + @param point The position of pixel + @warning This API currently support 8 bits per component only (RGBA8888 etc), not RGBA16U/RGBA10 + @return The color for specify pixel, or nil if any error occur + */ +- (nullable UIColor *)sd_colorAtPoint:(CGPoint)point; + +/** + Return the pixel color array with specify rectangle. The rect is from the top-left to the bottom-right and 0-based. The returned the color is always be RGBA format. The image must be CG-based. + @note The rect's origin and size will be converted into integer. + @note The rect's width/height should not be smaller than or equal to 0. The minX/minY should not be smaller than 0. The maxX/maxY should not be greater than width/height. Attention this limit is different from `sd_colorAtPoint:` (point: (0, 0) like rect: (0, 0, 1, 1)) + @note The overhead of object creation means this method is best suited for infrequent color sampling. For heavy image processing, grab the raw bitmap data and process yourself. + + @param rect The rectangle of pixels + @return The color array for specify pixels, or nil if any error occur + */ +- (nullable NSArray *)sd_colorsWithRect:(CGRect)rect; + +#pragma mark - Image Effect + +/** + Return a new image applied a blur effect. + + @param blurRadius The radius of the blur in points, 0 means no blur effect. + + @return The new image with blur effect, or nil if an error occurs (e.g. no enough memory). + */ +- (nullable UIImage *)sd_blurredImageWithRadius:(CGFloat)blurRadius; + +#if SD_UIKIT || SD_MAC +/** + Return a new image applied a CIFilter. + + @param filter The CIFilter to be applied to the image. + @return The new image with the CIFilter, or nil if an error occurs (e.g. no + enough memory). + */ +- (nullable UIImage *)sd_filteredImageWithFilter:(nonnull CIFilter *)filter; +#endif + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/UIImage+Transform.m b/Pods/SDWebImage/SDWebImage/Core/UIImage+Transform.m new file mode 100644 index 0000000..88189be --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/UIImage+Transform.m @@ -0,0 +1,1064 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "UIImage+Transform.h" +#import "NSImage+Compatibility.h" +#import "SDImageGraphics.h" +#import "SDGraphicsImageRenderer.h" +#import "NSBezierPath+SDRoundedCorners.h" +#import "SDInternalMacros.h" +#import +#if SD_UIKIT || SD_MAC +#import +#endif + +static inline CGRect SDCGRectFitWithScaleMode(CGRect rect, CGSize size, SDImageScaleMode scaleMode) { + rect = CGRectStandardize(rect); + size.width = size.width < 0 ? -size.width : size.width; + size.height = size.height < 0 ? -size.height : size.height; + CGPoint center = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect)); + switch (scaleMode) { + case SDImageScaleModeAspectFit: + case SDImageScaleModeAspectFill: { + if (rect.size.width < 0.01 || rect.size.height < 0.01 || + size.width < 0.01 || size.height < 0.01) { + rect.origin = center; + rect.size = CGSizeZero; + } else { + CGFloat scale; + if (scaleMode == SDImageScaleModeAspectFit) { + if (size.width / size.height < rect.size.width / rect.size.height) { + scale = rect.size.height / size.height; + } else { + scale = rect.size.width / size.width; + } + } else { + if (size.width / size.height < rect.size.width / rect.size.height) { + scale = rect.size.width / size.width; + } else { + scale = rect.size.height / size.height; + } + } + size.width *= scale; + size.height *= scale; + rect.size = size; + rect.origin = CGPointMake(center.x - size.width * 0.5, center.y - size.height * 0.5); + } + } break; + case SDImageScaleModeFill: + default: { + rect = rect; + } + } + return rect; +} + +static inline UIColor * SDGetColorFromGrayscale(Pixel_88 pixel, CGBitmapInfo bitmapInfo, CGColorSpaceRef cgColorSpace) { + // Get alpha info, byteOrder info + CGImageAlphaInfo alphaInfo = bitmapInfo & kCGBitmapAlphaInfoMask; + CGBitmapInfo byteOrderInfo = bitmapInfo & kCGBitmapByteOrderMask; + CGFloat w = 0, a = 1; + + BOOL byteOrderNormal = NO; + switch (byteOrderInfo) { + case kCGBitmapByteOrderDefault: { + byteOrderNormal = YES; + } break; + case kCGBitmapByteOrder16Little: + case kCGBitmapByteOrder32Little: { + } break; + case kCGBitmapByteOrder16Big: + case kCGBitmapByteOrder32Big: { + byteOrderNormal = YES; + } break; + default: break; + } + switch (alphaInfo) { + case kCGImageAlphaPremultipliedFirst: + case kCGImageAlphaFirst: { + if (byteOrderNormal) { + // AW + a = pixel[0] / 255.0; + w = pixel[1] / 255.0; + } else { + // WA + w = pixel[0] / 255.0; + a = pixel[1] / 255.0; + } + } + break; + case kCGImageAlphaPremultipliedLast: + case kCGImageAlphaLast: { + if (byteOrderNormal) { + // WA + w = pixel[0] / 255.0; + a = pixel[1] / 255.0; + } else { + // AW + a = pixel[0] / 255.0; + w = pixel[1] / 255.0; + } + } + break; + case kCGImageAlphaNone: { + // W + w = pixel[0] / 255.0; + } + break; + case kCGImageAlphaNoneSkipLast: { + if (byteOrderNormal) { + // WX + w = pixel[0] / 255.0; + } else { + // XW + a = pixel[1] / 255.0; + } + } + break; + case kCGImageAlphaNoneSkipFirst: { + if (byteOrderNormal) { + // XW + a = pixel[1] / 255.0; + } else { + // WX + a = pixel[0] / 255.0; + } + } + break; + case kCGImageAlphaOnly: { + // A + a = pixel[0] / 255.0; + } + break; + default: + break; + } +#if SD_MAC + // Mac supports ColorSync, to ensure the same bahvior, we convert color to sRGB + NSColorSpace *colorSpace = [[NSColorSpace alloc] initWithCGColorSpace:cgColorSpace]; + CGFloat components[2] = {w, a}; + NSColor *color = [NSColor colorWithColorSpace:colorSpace components:components count:2]; + return [color colorUsingColorSpace:NSColorSpace.genericGamma22GrayColorSpace]; +#else + return [UIColor colorWithWhite:w alpha:a]; +#endif +} + +static inline UIColor * SDGetColorFromRGBA8(Pixel_8888 pixel, CGBitmapInfo bitmapInfo, CGColorSpaceRef cgColorSpace) { + // Get alpha info, byteOrder info + CGImageAlphaInfo alphaInfo = bitmapInfo & kCGBitmapAlphaInfoMask; + CGBitmapInfo byteOrderInfo = bitmapInfo & kCGBitmapByteOrderMask; + CGFloat r = 0, g = 0, b = 0, a = 1; + + BOOL byteOrderNormal = NO; + switch (byteOrderInfo) { + case kCGBitmapByteOrderDefault: { + byteOrderNormal = YES; + } break; + case kCGBitmapByteOrder16Little: + case kCGBitmapByteOrder32Little: { + } break; + case kCGBitmapByteOrder16Big: + case kCGBitmapByteOrder32Big: { + byteOrderNormal = YES; + } break; + default: break; + } + switch (alphaInfo) { + case kCGImageAlphaPremultipliedFirst: { + if (byteOrderNormal) { + // ARGB8888-premultiplied + a = pixel[0] / 255.0; + r = pixel[1] / 255.0; + g = pixel[2] / 255.0; + b = pixel[3] / 255.0; + if (a > 0) { + r /= a; + g /= a; + b /= a; + } + } else { + // BGRA8888-premultiplied + b = pixel[0] / 255.0; + g = pixel[1] / 255.0; + r = pixel[2] / 255.0; + a = pixel[3] / 255.0; + if (a > 0) { + r /= a; + g /= a; + b /= a; + } + } + break; + } + case kCGImageAlphaFirst: { + if (byteOrderNormal) { + // ARGB8888 + a = pixel[0] / 255.0; + r = pixel[1] / 255.0; + g = pixel[2] / 255.0; + b = pixel[3] / 255.0; + } else { + // BGRA8888 + b = pixel[0] / 255.0; + g = pixel[1] / 255.0; + r = pixel[2] / 255.0; + a = pixel[3] / 255.0; + } + } + break; + case kCGImageAlphaPremultipliedLast: { + if (byteOrderNormal) { + // RGBA8888-premultiplied + r = pixel[0] / 255.0; + g = pixel[1] / 255.0; + b = pixel[2] / 255.0; + a = pixel[3] / 255.0; + if (a > 0) { + r /= a; + g /= a; + b /= a; + } + } else { + // ABGR8888-premultiplied + a = pixel[0] / 255.0; + b = pixel[1] / 255.0; + g = pixel[2] / 255.0; + r = pixel[3] / 255.0; + if (a > 0) { + r /= a; + g /= a; + b /= a; + } + } + break; + } + case kCGImageAlphaLast: { + if (byteOrderNormal) { + // RGBA8888 + r = pixel[0] / 255.0; + g = pixel[1] / 255.0; + b = pixel[2] / 255.0; + a = pixel[3] / 255.0; + } else { + // ABGR8888 + a = pixel[0] / 255.0; + b = pixel[1] / 255.0; + g = pixel[2] / 255.0; + r = pixel[3] / 255.0; + } + } + break; + case kCGImageAlphaNone: { + if (byteOrderNormal) { + // RGB + r = pixel[0] / 255.0; + g = pixel[1] / 255.0; + b = pixel[2] / 255.0; + } else { + // BGR + b = pixel[0] / 255.0; + g = pixel[1] / 255.0; + r = pixel[2] / 255.0; + } + } + break; + case kCGImageAlphaNoneSkipLast: { + if (byteOrderNormal) { + // RGBX + r = pixel[0] / 255.0; + g = pixel[1] / 255.0; + b = pixel[2] / 255.0; + } else { + // XBGR + b = pixel[1] / 255.0; + g = pixel[2] / 255.0; + r = pixel[3] / 255.0; + } + } + break; + case kCGImageAlphaNoneSkipFirst: { + if (byteOrderNormal) { + // XRGB + r = pixel[1] / 255.0; + g = pixel[2] / 255.0; + b = pixel[3] / 255.0; + } else { + // BGRX + b = pixel[0] / 255.0; + g = pixel[1] / 255.0; + r = pixel[2] / 255.0; + } + } + break; + case kCGImageAlphaOnly: { + // A + a = pixel[0] / 255.0; + } + break; + default: + break; + } +#if SD_MAC + // Mac supports ColorSync, to ensure the same bahvior, we convert color to sRGB + NSColorSpace *colorSpace = [[NSColorSpace alloc] initWithCGColorSpace:cgColorSpace]; + CGFloat components[4] = {r, g, b, a}; + NSColor *color = [NSColor colorWithColorSpace:colorSpace components:components count:4]; + return [color colorUsingColorSpace:NSColorSpace.sRGBColorSpace]; +#else + return [UIColor colorWithRed:r green:g blue:b alpha:a]; +#endif +} + +#if SD_UIKIT || SD_MAC +// Create-Rule, caller should call CGImageRelease +static inline CGImageRef _Nullable SDCreateCGImageFromCIImage(CIImage * _Nonnull ciImage) { + CGImageRef imageRef = NULL; + if (@available(iOS 10, macOS 10.12, tvOS 10, *)) { + imageRef = ciImage.CGImage; + } + if (!imageRef) { + CIContext *context = [CIContext context]; + imageRef = [context createCGImage:ciImage fromRect:ciImage.extent]; + } else { + CGImageRetain(imageRef); + } + return imageRef; +} +#endif + +@implementation UIImage (Transform) + +- (void)sd_drawInRect:(CGRect)rect context:(CGContextRef)context scaleMode:(SDImageScaleMode)scaleMode clipsToBounds:(BOOL)clips { + CGRect drawRect = SDCGRectFitWithScaleMode(rect, self.size, scaleMode); + if (drawRect.size.width == 0 || drawRect.size.height == 0) return; + if (clips) { + if (context) { + CGContextSaveGState(context); + CGContextAddRect(context, rect); + CGContextClip(context); + [self drawInRect:drawRect]; + CGContextRestoreGState(context); + } + } else { + [self drawInRect:drawRect]; + } +} + +- (nullable UIImage *)sd_resizedImageWithSize:(CGSize)size scaleMode:(SDImageScaleMode)scaleMode { + if (size.width <= 0 || size.height <= 0) return nil; + SDGraphicsImageRendererFormat *format = [[SDGraphicsImageRendererFormat alloc] init]; + format.scale = self.scale; + SDGraphicsImageRenderer *renderer = [[SDGraphicsImageRenderer alloc] initWithSize:size format:format]; + UIImage *image = [renderer imageWithActions:^(CGContextRef _Nonnull context) { + [self sd_drawInRect:CGRectMake(0, 0, size.width, size.height) context:context scaleMode:scaleMode clipsToBounds:NO]; + }]; + return image; +} + +- (nullable UIImage *)sd_croppedImageWithRect:(CGRect)rect { + rect.origin.x *= self.scale; + rect.origin.y *= self.scale; + rect.size.width *= self.scale; + rect.size.height *= self.scale; + if (rect.size.width <= 0 || rect.size.height <= 0) return nil; + +#if SD_UIKIT || SD_MAC + // CIImage shortcut + if (self.CIImage) { + CGRect croppingRect = CGRectMake(rect.origin.x, self.size.height - CGRectGetMaxY(rect), rect.size.width, rect.size.height); + CIImage *ciImage = [self.CIImage imageByCroppingToRect:croppingRect]; +#if SD_UIKIT + UIImage *image = [UIImage imageWithCIImage:ciImage scale:self.scale orientation:self.imageOrientation]; +#else + UIImage *image = [[UIImage alloc] initWithCIImage:ciImage scale:self.scale orientation:kCGImagePropertyOrientationUp]; +#endif + return image; + } +#endif + + CGImageRef imageRef = self.CGImage; + if (!imageRef) { + return nil; + } + + CGImageRef croppedImageRef = CGImageCreateWithImageInRect(imageRef, rect); + if (!croppedImageRef) { + return nil; + } +#if SD_UIKIT || SD_WATCH + UIImage *image = [UIImage imageWithCGImage:croppedImageRef scale:self.scale orientation:self.imageOrientation]; +#else + UIImage *image = [[UIImage alloc] initWithCGImage:croppedImageRef scale:self.scale orientation:kCGImagePropertyOrientationUp]; +#endif + CGImageRelease(croppedImageRef); + return image; +} + +- (nullable UIImage *)sd_roundedCornerImageWithRadius:(CGFloat)cornerRadius corners:(SDRectCorner)corners borderWidth:(CGFloat)borderWidth borderColor:(nullable UIColor *)borderColor { + SDGraphicsImageRendererFormat *format = [[SDGraphicsImageRendererFormat alloc] init]; + format.scale = self.scale; + SDGraphicsImageRenderer *renderer = [[SDGraphicsImageRenderer alloc] initWithSize:self.size format:format]; + UIImage *image = [renderer imageWithActions:^(CGContextRef _Nonnull context) { + CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height); + + CGFloat minSize = MIN(self.size.width, self.size.height); + if (borderWidth < minSize / 2) { +#if SD_UIKIT || SD_WATCH + UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectInset(rect, borderWidth, borderWidth) byRoundingCorners:corners cornerRadii:CGSizeMake(cornerRadius, cornerRadius)]; +#else + NSBezierPath *path = [NSBezierPath sd_bezierPathWithRoundedRect:CGRectInset(rect, borderWidth, borderWidth) byRoundingCorners:corners cornerRadius:cornerRadius]; +#endif + [path closePath]; + + CGContextSaveGState(context); + [path addClip]; + [self drawInRect:rect]; + CGContextRestoreGState(context); + } + + if (borderColor && borderWidth < minSize / 2 && borderWidth > 0) { + CGFloat strokeInset = (floor(borderWidth * self.scale) + 0.5) / self.scale; + CGRect strokeRect = CGRectInset(rect, strokeInset, strokeInset); + CGFloat strokeRadius = cornerRadius > self.scale / 2 ? cornerRadius - self.scale / 2 : 0; +#if SD_UIKIT || SD_WATCH + UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:strokeRect byRoundingCorners:corners cornerRadii:CGSizeMake(strokeRadius, strokeRadius)]; +#else + NSBezierPath *path = [NSBezierPath sd_bezierPathWithRoundedRect:strokeRect byRoundingCorners:corners cornerRadius:strokeRadius]; +#endif + [path closePath]; + + path.lineWidth = borderWidth; + [borderColor setStroke]; + [path stroke]; + } + }]; + return image; +} + +- (nullable UIImage *)sd_rotatedImageWithAngle:(CGFloat)angle fitSize:(BOOL)fitSize { + size_t width = self.size.width; + size_t height = self.size.height; + CGRect newRect = CGRectApplyAffineTransform(CGRectMake(0, 0, width, height), + fitSize ? CGAffineTransformMakeRotation(angle) : CGAffineTransformIdentity); + +#if SD_UIKIT || SD_MAC + // CIImage shortcut + if (self.CIImage) { + CIImage *ciImage = self.CIImage; + if (fitSize) { + CGAffineTransform transform = CGAffineTransformMakeRotation(angle); + ciImage = [ciImage imageByApplyingTransform:transform]; + } else { + CIFilter *filter = [CIFilter filterWithName:@"CIStraightenFilter"]; + [filter setValue:ciImage forKey:kCIInputImageKey]; + [filter setValue:@(angle) forKey:kCIInputAngleKey]; + ciImage = filter.outputImage; + } +#if SD_UIKIT || SD_WATCH + UIImage *image = [UIImage imageWithCIImage:ciImage scale:self.scale orientation:self.imageOrientation]; +#else + UIImage *image = [[UIImage alloc] initWithCIImage:ciImage scale:self.scale orientation:kCGImagePropertyOrientationUp]; +#endif + return image; + } +#endif + + SDGraphicsImageRendererFormat *format = [[SDGraphicsImageRendererFormat alloc] init]; + format.scale = self.scale; + SDGraphicsImageRenderer *renderer = [[SDGraphicsImageRenderer alloc] initWithSize:newRect.size format:format]; + UIImage *image = [renderer imageWithActions:^(CGContextRef _Nonnull context) { + CGContextSetShouldAntialias(context, true); + CGContextSetAllowsAntialiasing(context, true); + CGContextSetInterpolationQuality(context, kCGInterpolationHigh); + CGContextTranslateCTM(context, +(newRect.size.width * 0.5), +(newRect.size.height * 0.5)); +#if SD_UIKIT || SD_WATCH + // Use UIKit coordinate system counterclockwise (⟲) + CGContextRotateCTM(context, -angle); +#else + CGContextRotateCTM(context, angle); +#endif + + [self drawInRect:CGRectMake(-(width * 0.5), -(height * 0.5), width, height)]; + }]; + return image; +} + +- (nullable UIImage *)sd_flippedImageWithHorizontal:(BOOL)horizontal vertical:(BOOL)vertical { + size_t width = self.size.width; + size_t height = self.size.height; + +#if SD_UIKIT || SD_MAC + // CIImage shortcut + if (self.CIImage) { + CGAffineTransform transform = CGAffineTransformIdentity; + // Use UIKit coordinate system + if (horizontal) { + CGAffineTransform flipHorizontal = CGAffineTransformMake(-1, 0, 0, 1, width, 0); + transform = CGAffineTransformConcat(transform, flipHorizontal); + } + if (vertical) { + CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, height); + transform = CGAffineTransformConcat(transform, flipVertical); + } + CIImage *ciImage = [self.CIImage imageByApplyingTransform:transform]; +#if SD_UIKIT + UIImage *image = [UIImage imageWithCIImage:ciImage scale:self.scale orientation:self.imageOrientation]; +#else + UIImage *image = [[UIImage alloc] initWithCIImage:ciImage scale:self.scale orientation:kCGImagePropertyOrientationUp]; +#endif + return image; + } +#endif + + SDGraphicsImageRendererFormat *format = [[SDGraphicsImageRendererFormat alloc] init]; + format.scale = self.scale; + SDGraphicsImageRenderer *renderer = [[SDGraphicsImageRenderer alloc] initWithSize:self.size format:format]; + UIImage *image = [renderer imageWithActions:^(CGContextRef _Nonnull context) { + // Use UIKit coordinate system + if (horizontal) { + CGAffineTransform flipHorizontal = CGAffineTransformMake(-1, 0, 0, 1, width, 0); + CGContextConcatCTM(context, flipHorizontal); + } + if (vertical) { + CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, height); + CGContextConcatCTM(context, flipVertical); + } + [self drawInRect:CGRectMake(0, 0, width, height)]; + }]; + return image; +} + +#pragma mark - Image Blending + +#if SD_UIKIT || SD_MAC +static NSString * _Nullable SDGetCIFilterNameFromBlendMode(CGBlendMode blendMode) { + // CGBlendMode: https://developer.apple.com/library/archive/documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_images/dq_images.html#//apple_ref/doc/uid/TP30001066-CH212-CJBIJEFG + // CIFilter: https://developer.apple.com/library/archive/documentation/GraphicsImaging/Reference/CoreImageFilterReference/index.html#//apple_ref/doc/uid/TP30000136-SW71 + NSString *filterName; + switch (blendMode) { + case kCGBlendModeMultiply: + filterName = @"CIMultiplyBlendMode"; + break; + case kCGBlendModeScreen: + filterName = @"CIScreenBlendMode"; + break; + case kCGBlendModeOverlay: + filterName = @"CIOverlayBlendMode"; + break; + case kCGBlendModeDarken: + filterName = @"CIDarkenBlendMode"; + break; + case kCGBlendModeLighten: + filterName = @"CILightenBlendMode"; + break; + case kCGBlendModeColorDodge: + filterName = @"CIColorDodgeBlendMode"; + break; + case kCGBlendModeColorBurn: + filterName = @"CIColorBurnBlendMode"; + break; + case kCGBlendModeSoftLight: + filterName = @"CISoftLightBlendMode"; + break; + case kCGBlendModeHardLight: + filterName = @"CIHardLightBlendMode"; + break; + case kCGBlendModeDifference: + filterName = @"CIDifferenceBlendMode"; + break; + case kCGBlendModeExclusion: + filterName = @"CIExclusionBlendMode"; + break; + case kCGBlendModeHue: + filterName = @"CIHueBlendMode"; + break; + case kCGBlendModeSaturation: + filterName = @"CISaturationBlendMode"; + break; + case kCGBlendModeColor: + // Color blend mode uses the luminance values of the background with the hue and saturation values of the source image. + filterName = @"CIColorBlendMode"; + break; + case kCGBlendModeLuminosity: + filterName = @"CILuminosityBlendMode"; + break; + + // macOS 10.5+ + case kCGBlendModeSourceAtop: + case kCGBlendModeDestinationAtop: + filterName = @"CISourceAtopCompositing"; + break; + case kCGBlendModeSourceIn: + case kCGBlendModeDestinationIn: + filterName = @"CISourceInCompositing"; + break; + case kCGBlendModeSourceOut: + case kCGBlendModeDestinationOut: + filterName = @"CISourceOutCompositing"; + break; + case kCGBlendModeNormal: // SourceOver + case kCGBlendModeDestinationOver: + filterName = @"CISourceOverCompositing"; + break; + + // need special handling + case kCGBlendModeClear: + // use clear color instead + break; + case kCGBlendModeCopy: + // use input color instead + break; + case kCGBlendModeXOR: + // unsupported + break; + case kCGBlendModePlusDarker: + // chain filters + break; + case kCGBlendModePlusLighter: + // chain filters + break; + } + return filterName; +} +#endif + +- (nullable UIImage *)sd_tintedImageWithColor:(nonnull UIColor *)tintColor { + return [self sd_tintedImageWithColor:tintColor blendMode:kCGBlendModeSourceIn]; +} + +- (nullable UIImage *)sd_tintedImageWithColor:(nonnull UIColor *)tintColor blendMode:(CGBlendMode)blendMode { + BOOL hasTint = CGColorGetAlpha(tintColor.CGColor) > __FLT_EPSILON__; + if (!hasTint) { + return self; + } + + // blend mode, see https://en.wikipedia.org/wiki/Alpha_compositing +#if SD_UIKIT || SD_MAC + // CIImage shortcut + CIImage *ciImage = self.CIImage; + if (ciImage) { + CIImage *colorImage = [CIImage imageWithColor:[[CIColor alloc] initWithColor:tintColor]]; + colorImage = [colorImage imageByCroppingToRect:ciImage.extent]; + NSString *filterName = SDGetCIFilterNameFromBlendMode(blendMode); + // Some blend mode is not nativelly supported + if (filterName) { + CIFilter *filter = [CIFilter filterWithName:filterName]; + [filter setValue:colorImage forKey:kCIInputImageKey]; + [filter setValue:ciImage forKey:kCIInputBackgroundImageKey]; + ciImage = filter.outputImage; + } else { + if (blendMode == kCGBlendModeClear) { + // R = 0 + CIColor *clearColor; + if (@available(iOS 10.0, macOS 10.12, tvOS 10.0, *)) { + clearColor = CIColor.clearColor; + } else { + clearColor = [[CIColor alloc] initWithColor:UIColor.clearColor]; + } + colorImage = [CIImage imageWithColor:clearColor]; + colorImage = [colorImage imageByCroppingToRect:ciImage.extent]; + ciImage = colorImage; + } else if (blendMode == kCGBlendModeCopy) { + // R = S + ciImage = colorImage; + } else if (blendMode == kCGBlendModePlusLighter) { + // R = MIN(1, S + D) + // S + D + CIFilter *filter = [CIFilter filterWithName:@"CIAdditionCompositing"]; + [filter setValue:colorImage forKey:kCIInputImageKey]; + [filter setValue:ciImage forKey:kCIInputBackgroundImageKey]; + ciImage = filter.outputImage; + // MIN + ciImage = [ciImage imageByApplyingFilter:@"CIColorClamp" withInputParameters:nil]; + } else if (blendMode == kCGBlendModePlusDarker) { + // R = MAX(0, (1 - D) + (1 - S)) + // (1 - D) + CIFilter *filter1 = [CIFilter filterWithName:@"CIColorControls"]; + [filter1 setValue:ciImage forKey:kCIInputImageKey]; + [filter1 setValue:@(-0.5) forKey:kCIInputBrightnessKey]; + ciImage = filter1.outputImage; + // (1 - S) + CIFilter *filter2 = [CIFilter filterWithName:@"CIColorControls"]; + [filter2 setValue:colorImage forKey:kCIInputImageKey]; + [filter2 setValue:@(-0.5) forKey:kCIInputBrightnessKey]; + colorImage = filter2.outputImage; + // + + CIFilter *filter = [CIFilter filterWithName:@"CIAdditionCompositing"]; + [filter setValue:colorImage forKey:kCIInputImageKey]; + [filter setValue:ciImage forKey:kCIInputBackgroundImageKey]; + ciImage = filter.outputImage; + // MAX + ciImage = [ciImage imageByApplyingFilter:@"CIColorClamp" withInputParameters:nil]; + } else { + SD_LOG("UIImage+Transform error: Unsupported blend mode: %d", blendMode); + ciImage = nil; + } + } + + if (ciImage) { +#if SD_UIKIT + UIImage *image = [UIImage imageWithCIImage:ciImage scale:self.scale orientation:self.imageOrientation]; +#else + UIImage *image = [[UIImage alloc] initWithCIImage:ciImage scale:self.scale orientation:kCGImagePropertyOrientationUp]; +#endif + return image; + } + } +#endif + + CGSize size = self.size; + CGRect rect = { CGPointZero, size }; + CGFloat scale = self.scale; + + SDGraphicsImageRendererFormat *format = [[SDGraphicsImageRendererFormat alloc] init]; + format.scale = scale; + SDGraphicsImageRenderer *renderer = [[SDGraphicsImageRenderer alloc] initWithSize:size format:format]; + UIImage *image = [renderer imageWithActions:^(CGContextRef _Nonnull context) { + [self drawInRect:rect]; + CGContextSetBlendMode(context, blendMode); + CGContextSetFillColorWithColor(context, tintColor.CGColor); + CGContextFillRect(context, rect); + }]; + return image; +} + +- (nullable UIColor *)sd_colorAtPoint:(CGPoint)point { + CGImageRef imageRef = NULL; + // CIImage compatible +#if SD_UIKIT || SD_MAC + if (self.CIImage) { + imageRef = SDCreateCGImageFromCIImage(self.CIImage); + } +#endif + if (!imageRef) { + imageRef = self.CGImage; + CGImageRetain(imageRef); + } + if (!imageRef) { + return nil; + } + + // Check point + size_t width = CGImageGetWidth(imageRef); + size_t height = CGImageGetHeight(imageRef); + size_t x = point.x; + size_t y = point.y; + if (x < 0 || y < 0 || x >= width || y >= height) { + CGImageRelease(imageRef); + return nil; + } + + // Check pixel format + CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef); + size_t bitsPerComponent = CGImageGetBitsPerComponent(imageRef); + if (@available(iOS 12.0, tvOS 12.0, macOS 10.14, watchOS 5.0, *)) { + CGImagePixelFormatInfo pixelFormat = (bitmapInfo & kCGImagePixelFormatMask); + if (pixelFormat != kCGImagePixelFormatPacked || bitsPerComponent > 8) { + // like RGBA1010102, need bitwise to extract pixel from single uint32_t, we don't support currently + SD_LOG("Unsupported pixel format: %u, bpc: %zu for CGImage: %@", pixelFormat, bitsPerComponent, imageRef); + CGImageRelease(imageRef); + return nil; + } + } + + // Get pixels + CGDataProviderRef provider = CGImageGetDataProvider(imageRef); + if (!provider) { + CGImageRelease(imageRef); + return nil; + } + CFDataRef data = CGDataProviderCopyData(provider); + if (!data) { + CGImageRelease(imageRef); + return nil; + } + + // Get pixel at point + size_t bytesPerRow = CGImageGetBytesPerRow(imageRef); + size_t components = CGImageGetBitsPerPixel(imageRef) / bitsPerComponent; + + CFRange range = CFRangeMake(bytesPerRow * y + components * x, components); + if (CFDataGetLength(data) < range.location + range.length) { + CFRelease(data); + CGImageRelease(imageRef); + return nil; + } + // Get color space for transform + CGColorSpaceRef colorSpace = CGImageGetColorSpace(imageRef); + + // greyscale + if (components == 2) { + Pixel_88 pixel = {0}; + CFDataGetBytes(data, range, pixel); + CFRelease(data); + CGImageRelease(imageRef); + // Convert to color + return SDGetColorFromGrayscale(pixel, bitmapInfo, colorSpace); + } else if (components == 3 || components == 4) { + // RGB/RGBA + Pixel_8888 pixel = {0}; + CFDataGetBytes(data, range, pixel); + CFRelease(data); + CGImageRelease(imageRef); + // Convert to color + return SDGetColorFromRGBA8(pixel, bitmapInfo, colorSpace); + } else { + SD_LOG("Unsupported components: %zu for CGImage: %@", components, imageRef); + CFRelease(data); + CGImageRelease(imageRef); + return nil; + } +} + +- (nullable NSArray *)sd_colorsWithRect:(CGRect)rect { + CGImageRef imageRef = NULL; + // CIImage compatible +#if SD_UIKIT || SD_MAC + if (self.CIImage) { + imageRef = SDCreateCGImageFromCIImage(self.CIImage); + } +#endif + if (!imageRef) { + imageRef = self.CGImage; + CGImageRetain(imageRef); + } + if (!imageRef) { + return nil; + } + + // Check rect + size_t width = CGImageGetWidth(imageRef); + size_t height = CGImageGetHeight(imageRef); + if (CGRectGetWidth(rect) <= 0 || CGRectGetHeight(rect) <= 0 || CGRectGetMinX(rect) < 0 || CGRectGetMinY(rect) < 0 || CGRectGetMaxX(rect) > width || CGRectGetMaxY(rect) > height) { + CGImageRelease(imageRef); + return nil; + } + + // Check pixel format + CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef); + size_t bitsPerComponent = CGImageGetBitsPerComponent(imageRef); + if (@available(iOS 12.0, tvOS 12.0, macOS 10.14, watchOS 5.0, *)) { + CGImagePixelFormatInfo pixelFormat = (bitmapInfo & kCGImagePixelFormatMask); + if (pixelFormat != kCGImagePixelFormatPacked || bitsPerComponent > 8) { + // like RGBA1010102, need bitwise to extract pixel from single uint32_t, we don't support currently + SD_LOG("Unsupported pixel format: %u, bpc: %zu for CGImage: %@", pixelFormat, bitsPerComponent, imageRef); + CGImageRelease(imageRef); + return nil; + } + } + + // Get pixels + CGDataProviderRef provider = CGImageGetDataProvider(imageRef); + if (!provider) { + CGImageRelease(imageRef); + return nil; + } + CFDataRef data = CGDataProviderCopyData(provider); + if (!data) { + CGImageRelease(imageRef); + return nil; + } + + // Get pixels with rect + size_t bytesPerRow = CGImageGetBytesPerRow(imageRef); + size_t components = CGImageGetBitsPerPixel(imageRef) / bitsPerComponent; + + size_t start = bytesPerRow * CGRectGetMinY(rect) + components * CGRectGetMinX(rect); + size_t end = bytesPerRow * (CGRectGetMaxY(rect) - 1) + components * CGRectGetMaxX(rect); + if (CFDataGetLength(data) < (CFIndex)end) { + CFRelease(data); + CGImageRelease(imageRef); + return nil; + } + + const UInt8 *pixels = CFDataGetBytePtr(data); + size_t row = CGRectGetMinY(rect); + size_t col = CGRectGetMaxX(rect); + + // Convert to color + NSMutableArray *colors = [NSMutableArray arrayWithCapacity:CGRectGetWidth(rect) * CGRectGetHeight(rect)]; + // ColorSpace + CGColorSpaceRef colorSpace = CGImageGetColorSpace(imageRef); + for (size_t index = start; index < end; index += components) { + if (index >= row * bytesPerRow + col * components) { + // Index beyond the end of current row, go next row + row++; + index = row * bytesPerRow + CGRectGetMinX(rect) * components; + index -= components; + continue; + } + UIColor *color; + if (components == 2) { + Pixel_88 pixel = {pixels[index], pixel[index+1]}; + color = SDGetColorFromGrayscale(pixel, bitmapInfo, colorSpace); + } else { + if (components == 3) { + Pixel_8888 pixel = {pixels[index], pixels[index+1], pixels[index+2], 0}; + color = SDGetColorFromRGBA8(pixel, bitmapInfo, colorSpace); + } else if (components == 4) { + Pixel_8888 pixel = {pixels[index], pixels[index+1], pixels[index+2], pixels[index+3]}; + color = SDGetColorFromRGBA8(pixel, bitmapInfo, colorSpace); + } else { + SD_LOG("Unsupported components: %zu for CGImage: %@", components, imageRef); + break; + } + } + if (color) { + [colors addObject:color]; + } + } + CFRelease(data); + CGImageRelease(imageRef); + + return [colors copy]; +} + +#pragma mark - Image Effect + +// We use vImage to do box convolve for performance and support for watchOS. However, you can just use `CIFilter.CIGaussianBlur`. For other blur effect, use any filter in `CICategoryBlur` +- (nullable UIImage *)sd_blurredImageWithRadius:(CGFloat)blurRadius { + if (self.size.width < 1 || self.size.height < 1) { + return nil; + } + BOOL hasBlur = blurRadius > __FLT_EPSILON__; + if (!hasBlur) { + return self; + } + + CGFloat scale = self.scale; + CGFloat inputRadius = blurRadius * scale; +#if SD_UIKIT || SD_MAC + if (self.CIImage) { + CIFilter *filter = [CIFilter filterWithName:@"CIGaussianBlur"]; + [filter setValue:self.CIImage forKey:kCIInputImageKey]; + [filter setValue:@(inputRadius) forKey:kCIInputRadiusKey]; + CIImage *ciImage = filter.outputImage; + ciImage = [ciImage imageByCroppingToRect:CGRectMake(0, 0, self.size.width, self.size.height)]; +#if SD_UIKIT + UIImage *image = [UIImage imageWithCIImage:ciImage scale:self.scale orientation:self.imageOrientation]; +#else + UIImage *image = [[UIImage alloc] initWithCIImage:ciImage scale:self.scale orientation:kCGImagePropertyOrientationUp]; +#endif + return image; + } +#endif + + CGImageRef imageRef = self.CGImage; + if (!imageRef) { + return nil; + } + + vImage_Buffer effect = {}, scratch = {}; + vImage_Buffer *input = NULL, *output = NULL; + + vImage_CGImageFormat format = { + .bitsPerComponent = 8, + .bitsPerPixel = 32, + .colorSpace = NULL, + .bitmapInfo = kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host, //requests a BGRA buffer. + .version = 0, + .decode = NULL, + .renderingIntent = CGImageGetRenderingIntent(imageRef) + }; + + vImage_Error err; + err = vImageBuffer_InitWithCGImage(&effect, &format, NULL, imageRef, kvImageNoFlags); // vImage will convert to format we requests, no need `vImageConvert` + if (err != kvImageNoError) { + SD_LOG("UIImage+Transform error: vImageBuffer_InitWithCGImage returned error code %zi for inputImage: %@", err, self); + return nil; + } + err = vImageBuffer_Init(&scratch, effect.height, effect.width, format.bitsPerPixel, kvImageNoFlags); + if (err != kvImageNoError) { + SD_LOG("UIImage+Transform error: vImageBuffer_Init returned error code %zi for inputImage: %@", err, self); + return nil; + } + + input = &effect; + output = &scratch; + + // See: https://developer.apple.com/library/archive/samplecode/UIImageEffects/Introduction/Intro.html + if (hasBlur) { + // A description of how to compute the box kernel width from the Gaussian + // radius (aka standard deviation) appears in the SVG spec: + // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement + // + // For larger values of 's' (s >= 2.0), an approximation can be used: Three + // successive box-blurs build a piece-wise quadratic convolution kernel, which + // approximates the Gaussian kernel to within roughly 3%. + // + // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5) + // + // ... if d is odd, use three box-blurs of size 'd', centered on the output pixel. + // + if (inputRadius - 2.0 < __FLT_EPSILON__) inputRadius = 2.0; + uint32_t radius = floor(inputRadius * 3.0 * sqrt(2 * M_PI) / 4 + 0.5); + radius |= 1; // force radius to be odd so that the three box-blur methodology works. + NSInteger tempSize = vImageBoxConvolve_ARGB8888(input, output, NULL, 0, 0, radius, radius, NULL, kvImageGetTempBufferSize | kvImageEdgeExtend); + void *temp = malloc(tempSize); + vImageBoxConvolve_ARGB8888(input, output, temp, 0, 0, radius, radius, NULL, kvImageEdgeExtend); + vImageBoxConvolve_ARGB8888(output, input, temp, 0, 0, radius, radius, NULL, kvImageEdgeExtend); + vImageBoxConvolve_ARGB8888(input, output, temp, 0, 0, radius, radius, NULL, kvImageEdgeExtend); + free(temp); + + vImage_Buffer *tmp = input; + input = output; + output = tmp; + } + + CGImageRef effectCGImage = NULL; + effectCGImage = vImageCreateCGImageFromBuffer(input, &format, NULL, NULL, kvImageNoAllocate, NULL); + if (effectCGImage == NULL) { + effectCGImage = vImageCreateCGImageFromBuffer(input, &format, NULL, NULL, kvImageNoFlags, NULL); + free(input->data); + } + free(output->data); +#if SD_UIKIT || SD_WATCH + UIImage *outputImage = [UIImage imageWithCGImage:effectCGImage scale:self.scale orientation:self.imageOrientation]; +#else + UIImage *outputImage = [[UIImage alloc] initWithCGImage:effectCGImage scale:self.scale orientation:kCGImagePropertyOrientationUp]; +#endif + CGImageRelease(effectCGImage); + + return outputImage; +} + +#if SD_UIKIT || SD_MAC +- (nullable UIImage *)sd_filteredImageWithFilter:(nonnull CIFilter *)filter { + CIImage *inputImage; + if (self.CIImage) { + inputImage = self.CIImage; + } else { + CGImageRef imageRef = self.CGImage; + if (!imageRef) { + return nil; + } + inputImage = [CIImage imageWithCGImage:imageRef]; + } + if (!inputImage) return nil; + + CIContext *context = [CIContext context]; + [filter setValue:inputImage forKey:kCIInputImageKey]; + CIImage *outputImage = filter.outputImage; + if (!outputImage) return nil; + + CGImageRef imageRef = [context createCGImage:outputImage fromRect:outputImage.extent]; + if (!imageRef) return nil; + +#if SD_UIKIT + UIImage *image = [UIImage imageWithCGImage:imageRef scale:self.scale orientation:self.imageOrientation]; +#else + UIImage *image = [[UIImage alloc] initWithCGImage:imageRef scale:self.scale orientation:kCGImagePropertyOrientationUp]; +#endif + CGImageRelease(imageRef); + + return image; +} +#endif + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/UIImageView+HighlightedWebCache.h b/Pods/SDWebImage/SDWebImage/Core/UIImageView+HighlightedWebCache.h new file mode 100644 index 0000000..80fabc6 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/UIImageView+HighlightedWebCache.h @@ -0,0 +1,142 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +#if SD_UIKIT + +#import "SDWebImageManager.h" + +/** + * Integrates SDWebImage async downloading and caching of remote images with UIImageView for highlighted state. + */ +@interface UIImageView (HighlightedWebCache) + +#pragma mark - Highlighted Image + +/** + * Get the current highlighted image URL. + */ +@property (nonatomic, strong, readonly, nullable) NSURL *sd_currentHighlightedImageURL; + +/** + * Set the imageView `highlightedImage` with an `url`. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + */ +- (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url NS_REFINED_FOR_SWIFT; + +/** + * Set the imageView `highlightedImage` with an `url` and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + */ +- (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url + options:(SDWebImageOptions)options NS_REFINED_FOR_SWIFT; + +/** + * Set the imageView `highlightedImage` with an `url`, custom options and context. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + */ +- (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context; + +/** + * Set the imageView `highlightedImage` with an `url`. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url + completed:(nullable SDExternalCompletionBlock)completedBlock NS_REFINED_FOR_SWIFT; + +/** + * Set the imageView `highlightedImage` with an `url` and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url + options:(SDWebImageOptions)options + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the imageView `highlightedImage` with an `url` and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param progressBlock A block called while image is downloading + * @note the progress block is executed on a background queue + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url + options:(SDWebImageOptions)options + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the imageView `highlightedImage` with an `url`, custom options and context. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + * @param progressBlock A block called while image is downloading + * @note the progress block is executed on a background queue + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Cancel the current highlighted image load (for `UIImageView.highlighted`) + * @note For normal image, use `sd_cancelCurrentImageLoad` + */ +- (void)sd_cancelCurrentHighlightedImageLoad; + +@end + +#endif diff --git a/Pods/SDWebImage/SDWebImage/Core/UIImageView+HighlightedWebCache.m b/Pods/SDWebImage/SDWebImage/Core/UIImageView+HighlightedWebCache.m new file mode 100644 index 0000000..bb51c90 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/UIImageView+HighlightedWebCache.m @@ -0,0 +1,85 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "UIImageView+HighlightedWebCache.h" + +#if SD_UIKIT + +#import "UIView+WebCacheOperation.h" +#import "UIView+WebCacheState.h" +#import "UIView+WebCache.h" +#import "SDInternalMacros.h" + +@implementation UIImageView (HighlightedWebCache) + +- (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url { + [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:nil]; +} + +- (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url options:(SDWebImageOptions)options { + [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:nil]; +} + +- (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url options:(SDWebImageOptions)options context:(nullable SDWebImageContext *)context { + [self sd_setHighlightedImageWithURL:url options:options context:context progress:nil completed:nil]; +} + +- (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:completedBlock]; +} + +- (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url options:(SDWebImageOptions)options completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:completedBlock]; +} + +- (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(nullable SDImageLoaderProgressBlock)progressBlock completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setHighlightedImageWithURL:url options:options context:nil progress:progressBlock completed:completedBlock]; +} + +- (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock { + @weakify(self); + SDWebImageMutableContext *mutableContext; + if (context) { + mutableContext = [context mutableCopy]; + } else { + mutableContext = [NSMutableDictionary dictionary]; + } + mutableContext[SDWebImageContextSetImageOperationKey] = @keypath(self, highlightedImage); + [self sd_internalSetImageWithURL:url + placeholderImage:nil + options:options + context:mutableContext + setImageBlock:^(UIImage * _Nullable image, NSData * _Nullable imageData, SDImageCacheType cacheType, NSURL * _Nullable imageURL) { + @strongify(self); + self.highlightedImage = image; + } + progress:progressBlock + completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) { + if (completedBlock) { + completedBlock(image, error, cacheType, imageURL); + } + }]; +} + +#pragma mark - Highlighted State + +- (NSURL *)sd_currentHighlightedImageURL { + return [self sd_imageLoadStateForKey:@keypath(self, highlightedImage)].url; +} + +- (void)sd_cancelCurrentHighlightedImageLoad { + return [self sd_cancelImageLoadOperationWithKey:@keypath(self, highlightedImage)]; +} + +@end + +#endif diff --git a/Pods/SDWebImage/SDWebImage/Core/UIImageView+WebCache.h b/Pods/SDWebImage/SDWebImage/Core/UIImageView+WebCache.h new file mode 100644 index 0000000..46b5a70 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/UIImageView+WebCache.h @@ -0,0 +1,209 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" +#import "SDWebImageManager.h" + +/** + * Usage with a UITableViewCell sub-class: + * + * @code + +#import + +... + +- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath +{ + static NSString *MyIdentifier = @"MyIdentifier"; + + UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier]; + + if (cell == nil) { + cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier]; + } + + // Here we use the provided sd_setImageWithURL:placeholderImage: method to load the web image + // Ensure you use a placeholder image otherwise cells will be initialized with no image + [cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://example.com/image.jpg"] + placeholderImage:[UIImage imageNamed:@"placeholder"]]; + + cell.textLabel.text = @"My Text"; + return cell; +} + + * @endcode + */ + +/** + * Integrates SDWebImage async downloading and caching of remote images with UIImageView. + */ +@interface UIImageView (WebCache) + +#pragma mark - Image State + +/** + * Get the current image URL. + */ +@property (nonatomic, strong, readonly, nullable) NSURL *sd_currentImageURL; + +#pragma mark - Image Loading + +/** + * Set the imageView `image` with an `url`. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url NS_REFINED_FOR_SWIFT; + +/** + * Set the imageView `image` with an `url` and a placeholder. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @see sd_setImageWithURL:placeholderImage:options: + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder NS_REFINED_FOR_SWIFT; + +/** + * Set the imageView `image` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options NS_REFINED_FOR_SWIFT; + +/** + * Set the imageView `image` with an `url`, placeholder, custom options and context. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context; + +/** + * Set the imageView `image` with an `url`. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the imageView `image` with an `url`, placeholder. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + completed:(nullable SDExternalCompletionBlock)completedBlock NS_REFINED_FOR_SWIFT; + +/** + * Set the imageView `image` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the imageView `image` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param progressBlock A block called while image is downloading + * @note the progress block is executed on a background queue + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the imageView `image` with an `url`, placeholder, custom options and context. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + * @param progressBlock A block called while image is downloading + * @note the progress block is executed on a background queue + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Cancel the current normal image load (for `UIImageView.image`) + * @note For highlighted image, use `sd_cancelCurrentHighlightedImageLoad` + */ +- (void)sd_cancelCurrentImageLoad; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/UIImageView+WebCache.m b/Pods/SDWebImage/SDWebImage/Core/UIImageView+WebCache.m new file mode 100644 index 0000000..e461aee --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/UIImageView+WebCache.m @@ -0,0 +1,78 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "UIImageView+WebCache.h" +#import "objc/runtime.h" +#import "UIView+WebCacheOperation.h" +#import "UIView+WebCacheState.h" +#import "UIView+WebCache.h" + +@implementation UIImageView (WebCache) + +- (void)sd_setImageWithURL:(nullable NSURL *)url { + [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder { + [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options { + [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options context:(nullable SDWebImageContext *)context { + [self sd_setImageWithURL:url placeholderImage:placeholder options:options context:context progress:nil completed:nil]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:completedBlock]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:completedBlock]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:completedBlock]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options progress:(nullable SDImageLoaderProgressBlock)progressBlock completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setImageWithURL:url placeholderImage:placeholder options:options context:nil progress:progressBlock completed:completedBlock]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_internalSetImageWithURL:url + placeholderImage:placeholder + options:options + context:context + setImageBlock:nil + progress:progressBlock + completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) { + if (completedBlock) { + completedBlock(image, error, cacheType, imageURL); + } + }]; +} + +#pragma mark - State + +- (NSURL *)sd_currentImageURL { + return [self sd_imageLoadStateForKey:nil].url; +} + +- (void)sd_cancelCurrentImageLoad { + return [self sd_cancelImageLoadOperationWithKey:nil]; +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/UIView+WebCache.h b/Pods/SDWebImage/SDWebImage/Core/UIView+WebCache.h new file mode 100644 index 0000000..2223f9d --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/UIView+WebCache.h @@ -0,0 +1,131 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" +#import "SDWebImageDefine.h" +#import "SDWebImageManager.h" +#import "SDWebImageTransition.h" +#import "SDWebImageIndicator.h" +#import "UIView+WebCacheOperation.h" +#import "UIView+WebCacheState.h" + +/** + The value specify that the image progress unit count cannot be determined because the progressBlock is not been called. + */ +FOUNDATION_EXPORT const int64_t SDWebImageProgressUnitCountUnknown; /* 1LL */ + +typedef void(^SDSetImageBlock)(UIImage * _Nullable image, NSData * _Nullable imageData, SDImageCacheType cacheType, NSURL * _Nullable imageURL); + +/** + Integrates SDWebImage async downloading and caching of remote images with UIView subclass. + */ +@interface UIView (WebCache) + +/** + * Get the current image operation key. Operation key is used to identify the different queries for one view instance (like UIButton). + * See more about this in `SDWebImageContextSetImageOperationKey`. + * + * @note You can use method `UIView+WebCacheOperation` to investigate different queries' operation. + * @note For the history version compatible, when current UIView has property exactly called `image`, the operation key will use `NSStringFromClass(self.class)`. Include `UIImageView.image/NSImageView.image/NSButton.image` (without `UIButton`) + * @warning This property should be only used for single state view, like `UIImageView` without highlighted state. For stateful view like `UIBUtton` (one view can have multiple images loading), check their header to call correct API, like `-[UIButton sd_imageOperationKeyForState:]` + */ +@property (nonatomic, strong, readonly, nullable) NSString *sd_latestOperationKey; + +#pragma mark - State + +/** + * Get the current image URL. + * This simply translate to `[self sd_imageLoadStateForKey:self.sd_latestOperationKey].url` from v5.18.0 + * + * @note Note that because of the limitations of categories this property can get out of sync if you use setImage: directly. + * @warning This property should be only used for single state view, like `UIImageView` without highlighted state. For stateful view like `UIBUtton` (one view can have multiple images loading), use `sd_imageLoadStateForKey:` instead. See `UIView+WebCacheState.h` for more information. + */ +@property (nonatomic, strong, readonly, nullable) NSURL *sd_imageURL; + +/** + * The current image loading progress associated to the view. The unit count is the received size and excepted size of download. + * The `totalUnitCount` and `completedUnitCount` will be reset to 0 after a new image loading start (change from current queue). And they will be set to `SDWebImageProgressUnitCountUnknown` if the progressBlock not been called but the image loading success to mark the progress finished (change from main queue). + * @note You can use Key-Value Observing on the progress, but you should take care that the change to progress is from a background queue during download(the same as progressBlock). If you want to using KVO and update the UI, make sure to dispatch on the main queue. And it's recommend to use some KVO libs like KVOController because it's more safe and easy to use. + * @note The getter will create a progress instance if the value is nil. But by default, we don't create one. If you need to use Key-Value Observing, you must trigger the getter or set a custom progress instance before the loading start. The default value is nil. + * @note Note that because of the limitations of categories this property can get out of sync if you update the progress directly. + * @warning This property should be only used for single state view, like `UIImageView` without highlighted state. For stateful view like `UIBUtton` (one view can have multiple images loading), use `sd_imageLoadStateForKey:` instead. See `UIView+WebCacheState.h` for more information. + */ +@property (nonatomic, strong, null_resettable) NSProgress *sd_imageProgress; + +/** + * Set the imageView `image` with an `url` and optionally a placeholder image. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + * @param setImageBlock Block used for custom set image code. If not provide, use the built-in set image code (supports `UIImageView/NSImageView` and `UIButton/NSButton` currently) + * @param progressBlock A block called while image is downloading + * @note the progress block is executed on a background queue + * @param completedBlock A block called when operation has been completed. + * This block has no return value and takes the requested UIImage as first parameter and the NSData representation as second parameter. + * In case of error the image parameter is nil and the third parameter may contain an NSError. + * + * The forth parameter is an `SDImageCacheType` enum indicating if the image was retrieved from the local cache + * or from the memory cache or from the network. + * + * The fifth parameter normally is always YES. However, if you provide SDWebImageAvoidAutoSetImage with SDWebImageProgressiveLoad options to enable progressive downloading and set the image yourself. This block is thus called repeatedly with a partial image. When image is fully downloaded, the + * block is called a last time with the full image and the last parameter set to YES. + * + * The last parameter is the original image URL + * @return The returned operation for cancelling cache and download operation, typically type is `SDWebImageCombinedOperation` + */ +- (nullable id)sd_internalSetImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + setImageBlock:(nullable SDSetImageBlock)setImageBlock + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDInternalCompletionBlock)completedBlock; + +/** + * Cancel the latest image load, using the `sd_latestOperationKey` as operation key + * This simply translate to `[self sd_cancelImageLoadOperationWithKey:self.sd_latestOperationKey]` + */ +- (void)sd_cancelLatestImageLoad; + +/** + * Cancel the current image load, for single state view. + * This actually does not cancel current loading, because stateful view can load multiple images at the same time (like UIButton, each state can load different images). Just behave the same as `sd_cancelLatestImageLoad` + * + * @warning This method should be only used for single state view, like `UIImageView` without highlighted state. For stateful view like `UIBUtton` (one view can have multiple images loading), use `sd_cancelImageLoadOperationWithKey:` instead. See `UIView+WebCacheOperation.h` for more information. + * @deprecated Use `sd_cancelLatestImageLoad` instead. Which don't cause overload method misunderstanding (`UIImageView+WebCache` provide the same API as this one, but does not do the same thing). This API will be totally removed in v6.0 due to this. + */ +- (void)sd_cancelCurrentImageLoad API_DEPRECATED_WITH_REPLACEMENT("sd_cancelLatestImageLoad", macos(10.10, 10.10), ios(8.0, 8.0), tvos(9.0, 9.0), watchos(2.0, 2.0)); + +#if SD_UIKIT || SD_MAC + +#pragma mark - Image Transition + +/** + The image transition when image load finished. See `SDWebImageTransition`. + If you specify nil, do not do transition. Defaults to nil. + @warning This property should be only used for single state view, like `UIImageView` without highlighted state. For stateful view like `UIBUtton` (one view can have multiple images loading), write your own implementation in `setImageBlock:`, and check current stateful view's state to render the UI. + */ +@property (nonatomic, strong, nullable) SDWebImageTransition *sd_imageTransition; + +#pragma mark - Image Indicator + +/** + The image indicator during the image loading. If you do not need indicator, specify nil. Defaults to nil + The setter will remove the old indicator view and add new indicator view to current view's subview. + @note Because this is UI related, you should access only from the main queue. + @warning This property should be only used for single state view, like `UIImageView` without highlighted state. For stateful view like `UIBUtton` (one view can have multiple images loading), write your own implementation in `setImageBlock:`, and check current stateful view's state to render the UI. + */ +@property (nonatomic, strong, nullable) id sd_imageIndicator; + +#endif + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/UIView+WebCache.m b/Pods/SDWebImage/SDWebImage/Core/UIView+WebCache.m new file mode 100644 index 0000000..4a4984f --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/UIView+WebCache.m @@ -0,0 +1,508 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "UIView+WebCache.h" +#import "objc/runtime.h" +#import "UIView+WebCacheOperation.h" +#import "SDWebImageError.h" +#import "SDInternalMacros.h" +#import "SDWebImageTransitionInternal.h" +#import "SDImageCache.h" +#import "SDCallbackQueue.h" + +const int64_t SDWebImageProgressUnitCountUnknown = 1LL; + +@implementation UIView (WebCache) + +- (nullable NSString *)sd_latestOperationKey { + return objc_getAssociatedObject(self, @selector(sd_latestOperationKey)); +} + +- (void)setSd_latestOperationKey:(NSString * _Nullable)sd_latestOperationKey { + objc_setAssociatedObject(self, @selector(sd_latestOperationKey), sd_latestOperationKey, OBJC_ASSOCIATION_COPY_NONATOMIC); +} + +#pragma mark - State + +- (NSURL *)sd_imageURL { + return [self sd_imageLoadStateForKey:self.sd_latestOperationKey].url; +} + +- (NSProgress *)sd_imageProgress { + SDWebImageLoadState *loadState = [self sd_imageLoadStateForKey:self.sd_latestOperationKey]; + NSProgress *progress = loadState.progress; + if (!progress) { + progress = [[NSProgress alloc] initWithParent:nil userInfo:nil]; + self.sd_imageProgress = progress; + } + return progress; +} + +- (void)setSd_imageProgress:(NSProgress *)sd_imageProgress { + if (!sd_imageProgress) { + return; + } + SDWebImageLoadState *loadState = [self sd_imageLoadStateForKey:self.sd_latestOperationKey]; + if (!loadState) { + loadState = [SDWebImageLoadState new]; + } + loadState.progress = sd_imageProgress; + [self sd_setImageLoadState:loadState forKey:self.sd_latestOperationKey]; +} + +- (nullable id)sd_internalSetImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + setImageBlock:(nullable SDSetImageBlock)setImageBlock + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDInternalCompletionBlock)completedBlock { + + // Very common mistake is to send the URL using NSString object instead of NSURL. For some strange reason, Xcode won't + // throw any warning for this type mismatch. Here we failsafe this error by allowing URLs to be passed as NSString. + // if url is NSString and shouldUseWeakMemoryCache is true, [cacheKeyForURL:context] will crash. just for a global protect. + if ([url isKindOfClass:NSString.class]) { + url = [NSURL URLWithString:(NSString *)url]; + } + // Prevents app crashing on argument type error like sending NSNull instead of NSURL + if (![url isKindOfClass:NSURL.class]) { + url = nil; + } + + if (context) { + // copy to avoid mutable object + context = [context copy]; + } else { + context = [NSDictionary dictionary]; + } + NSString *validOperationKey = context[SDWebImageContextSetImageOperationKey]; + if (!validOperationKey) { + // pass through the operation key to downstream, which can used for tracing operation or image view class + validOperationKey = NSStringFromClass([self class]); + SDWebImageMutableContext *mutableContext = [context mutableCopy]; + mutableContext[SDWebImageContextSetImageOperationKey] = validOperationKey; + context = [mutableContext copy]; + } + self.sd_latestOperationKey = validOperationKey; + if (!(SD_OPTIONS_CONTAINS(options, SDWebImageAvoidAutoCancelImage))) { + // cancel previous loading for the same set-image operation key by default + [self sd_cancelImageLoadOperationWithKey:validOperationKey]; + } + SDWebImageLoadState *loadState = [self sd_imageLoadStateForKey:validOperationKey]; + if (!loadState) { + loadState = [SDWebImageLoadState new]; + } + loadState.url = url; + [self sd_setImageLoadState:loadState forKey:validOperationKey]; + + SDWebImageManager *manager = context[SDWebImageContextCustomManager]; + if (!manager) { + manager = [SDWebImageManager sharedManager]; + } else { + // remove this manager to avoid retain cycle (manger -> loader -> operation -> context -> manager) + SDWebImageMutableContext *mutableContext = [context mutableCopy]; + mutableContext[SDWebImageContextCustomManager] = nil; + context = [mutableContext copy]; + } + SDCallbackQueue *queue = context[SDWebImageContextCallbackQueue]; + BOOL shouldUseWeakCache = NO; + if ([manager.imageCache isKindOfClass:SDImageCache.class]) { + shouldUseWeakCache = ((SDImageCache *)manager.imageCache).config.shouldUseWeakMemoryCache; + } + if (!(options & SDWebImageDelayPlaceholder)) { + if (shouldUseWeakCache) { + NSString *key = [manager cacheKeyForURL:url context:context]; + // call memory cache to trigger weak cache sync logic, ignore the return value and go on normal query + // this unfortunately will cause twice memory cache query, but it's fast enough + // in the future the weak cache feature may be re-design or removed + [((SDImageCache *)manager.imageCache) imageFromMemoryCacheForKey:key]; + } + [(queue ?: SDCallbackQueue.mainQueue) async:^{ + [self sd_setImage:placeholder imageData:nil basedOnClassOrViaCustomSetImageBlock:setImageBlock cacheType:SDImageCacheTypeNone imageURL:url]; + }]; + } + + id operation = nil; + + if (url) { + // reset the progress + NSProgress *imageProgress = loadState.progress; + if (imageProgress) { + imageProgress.totalUnitCount = 0; + imageProgress.completedUnitCount = 0; + } + +#if SD_UIKIT || SD_MAC + // check and start image indicator + [self sd_startImageIndicatorWithQueue:queue]; + id imageIndicator = self.sd_imageIndicator; +#endif + + SDImageLoaderProgressBlock combinedProgressBlock = ^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) { + if (imageProgress) { + imageProgress.totalUnitCount = expectedSize; + imageProgress.completedUnitCount = receivedSize; + } +#if SD_UIKIT || SD_MAC + if ([imageIndicator respondsToSelector:@selector(updateIndicatorProgress:)]) { + double progress = 0; + if (expectedSize != 0) { + progress = (double)receivedSize / expectedSize; + } + progress = MAX(MIN(progress, 1), 0); // 0.0 - 1.0 + dispatch_async(dispatch_get_main_queue(), ^{ + [imageIndicator updateIndicatorProgress:progress]; + }); + } +#endif + if (progressBlock) { + progressBlock(receivedSize, expectedSize, targetURL); + } + }; + @weakify(self); + operation = [manager loadImageWithURL:url options:options context:context progress:combinedProgressBlock completed:^(UIImage *image, NSData *data, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { + @strongify(self); + if (!self) { return; } + // if the progress not been updated, mark it to complete state + if (imageProgress && finished && !error && imageProgress.totalUnitCount == 0 && imageProgress.completedUnitCount == 0) { + imageProgress.totalUnitCount = SDWebImageProgressUnitCountUnknown; + imageProgress.completedUnitCount = SDWebImageProgressUnitCountUnknown; + } + +#if SD_UIKIT || SD_MAC + // check and stop image indicator + if (finished) { + [self sd_stopImageIndicatorWithQueue:queue]; + } +#endif + + BOOL shouldCallCompletedBlock = finished || (options & SDWebImageAvoidAutoSetImage); + BOOL shouldNotSetImage = ((image && (options & SDWebImageAvoidAutoSetImage)) || + (!image && !(options & SDWebImageDelayPlaceholder))); + SDWebImageNoParamsBlock callCompletedBlockClosure = ^{ + if (!self) { return; } + if (!shouldNotSetImage) { + [self sd_setNeedsLayout]; + } + if (completedBlock && shouldCallCompletedBlock) { + completedBlock(image, data, error, cacheType, finished, url); + } + }; + + // case 1a: we got an image, but the SDWebImageAvoidAutoSetImage flag is set + // OR + // case 1b: we got no image and the SDWebImageDelayPlaceholder is not set + if (shouldNotSetImage) { + [(queue ?: SDCallbackQueue.mainQueue) async:callCompletedBlockClosure]; + return; + } + + UIImage *targetImage = nil; + NSData *targetData = nil; + if (image) { + // case 2a: we got an image and the SDWebImageAvoidAutoSetImage is not set + targetImage = image; + targetData = data; + } else if (options & SDWebImageDelayPlaceholder) { + // case 2b: we got no image and the SDWebImageDelayPlaceholder flag is set + targetImage = placeholder; + targetData = nil; + } + +#if SD_UIKIT || SD_MAC + // check whether we should use the image transition + SDWebImageTransition *transition = nil; + BOOL shouldUseTransition = NO; + if (options & SDWebImageForceTransition) { + // Always + shouldUseTransition = YES; + } else if (cacheType == SDImageCacheTypeNone) { + // From network + shouldUseTransition = YES; + } else { + // From disk (and, user don't use sync query) + if (cacheType == SDImageCacheTypeMemory) { + shouldUseTransition = NO; + } else if (cacheType == SDImageCacheTypeDisk) { + if (options & SDWebImageQueryMemoryDataSync || options & SDWebImageQueryDiskDataSync) { + shouldUseTransition = NO; + } else { + shouldUseTransition = YES; + } + } else { + // Not valid cache type, fallback + shouldUseTransition = NO; + } + } + if (finished && shouldUseTransition) { + transition = self.sd_imageTransition; + } +#endif + [(queue ?: SDCallbackQueue.mainQueue) async:^{ +#if SD_UIKIT || SD_MAC + [self sd_setImage:targetImage imageData:targetData options:options basedOnClassOrViaCustomSetImageBlock:setImageBlock transition:transition cacheType:cacheType imageURL:imageURL callback:callCompletedBlockClosure]; +#else + [self sd_setImage:targetImage imageData:targetData basedOnClassOrViaCustomSetImageBlock:setImageBlock cacheType:cacheType imageURL:imageURL]; + callCompletedBlockClosure(); +#endif + }]; + }]; + [self sd_setImageLoadOperation:operation forKey:validOperationKey]; + } else { +#if SD_UIKIT || SD_MAC + [self sd_stopImageIndicatorWithQueue:queue]; +#endif + if (completedBlock) { + [(queue ?: SDCallbackQueue.mainQueue) async:^{ + NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorInvalidURL userInfo:@{NSLocalizedDescriptionKey : @"Image url is nil"}]; + completedBlock(nil, nil, error, SDImageCacheTypeNone, YES, url); + }]; + } + } + + return operation; +} + +- (void)sd_cancelLatestImageLoad { + [self sd_cancelImageLoadOperationWithKey:self.sd_latestOperationKey]; +} + +- (void)sd_cancelCurrentImageLoad { + [self sd_cancelImageLoadOperationWithKey:self.sd_latestOperationKey]; +} + +// Set image logic without transition (like placeholder and watchOS) +- (void)sd_setImage:(UIImage *)image imageData:(NSData *)imageData basedOnClassOrViaCustomSetImageBlock:(SDSetImageBlock)setImageBlock cacheType:(SDImageCacheType)cacheType imageURL:(NSURL *)imageURL { +#if SD_UIKIT || SD_MAC + [self sd_setImage:image imageData:imageData options:0 basedOnClassOrViaCustomSetImageBlock:setImageBlock transition:nil cacheType:cacheType imageURL:imageURL callback:nil]; +#else + // watchOS does not support view transition. Simplify the logic + if (setImageBlock) { + setImageBlock(image, imageData, cacheType, imageURL); + } else if ([self isKindOfClass:[UIImageView class]]) { + UIImageView *imageView = (UIImageView *)self; + [imageView setImage:image]; + } +#endif +} + +// Set image logic with transition +#if SD_UIKIT || SD_MAC +- (void)sd_setImage:(UIImage *)image imageData:(NSData *)imageData options:(SDWebImageOptions)options basedOnClassOrViaCustomSetImageBlock:(SDSetImageBlock)setImageBlock transition:(SDWebImageTransition *)transition cacheType:(SDImageCacheType)cacheType imageURL:(NSURL *)imageURL callback:(SDWebImageNoParamsBlock)callback { + UIView *view = self; + SDSetImageBlock finalSetImageBlock; + if (setImageBlock) { + finalSetImageBlock = setImageBlock; + } else if ([view isKindOfClass:[UIImageView class]]) { + UIImageView *imageView = (UIImageView *)view; + finalSetImageBlock = ^(UIImage *setImage, NSData *setImageData, SDImageCacheType setCacheType, NSURL *setImageURL) { + imageView.image = setImage; + }; + } +#if SD_UIKIT + else if ([view isKindOfClass:[UIButton class]]) { + UIButton *button = (UIButton *)view; + finalSetImageBlock = ^(UIImage *setImage, NSData *setImageData, SDImageCacheType setCacheType, NSURL *setImageURL) { + [button setImage:setImage forState:UIControlStateNormal]; + }; + } +#endif +#if SD_MAC + else if ([view isKindOfClass:[NSButton class]]) { + NSButton *button = (NSButton *)view; + finalSetImageBlock = ^(UIImage *setImage, NSData *setImageData, SDImageCacheType setCacheType, NSURL *setImageURL) { + button.image = setImage; + }; + } +#endif + + BOOL waitTransition = SD_OPTIONS_CONTAINS(options, SDWebImageWaitTransition); + if (transition) { + NSString *originalOperationKey = view.sd_latestOperationKey; + +#if SD_UIKIT + [UIView transitionWithView:view duration:0 options:0 animations:^{ + if (!view.sd_latestOperationKey || ![originalOperationKey isEqualToString:view.sd_latestOperationKey]) { + return; + } + // 0 duration to let UIKit render placeholder and prepares block + if (transition.prepares) { + transition.prepares(view, image, imageData, cacheType, imageURL); + } + } completion:^(BOOL tempFinished) { + [UIView transitionWithView:view duration:transition.duration options:transition.animationOptions animations:^{ + if (!view.sd_latestOperationKey || ![originalOperationKey isEqualToString:view.sd_latestOperationKey]) { + return; + } + if (finalSetImageBlock && !transition.avoidAutoSetImage) { + finalSetImageBlock(image, imageData, cacheType, imageURL); + } + if (transition.animations) { + transition.animations(view, image); + } + } completion:^(BOOL finished) { + if (!view.sd_latestOperationKey || ![originalOperationKey isEqualToString:view.sd_latestOperationKey]) { + return; + } + if (transition.completion) { + transition.completion(finished); + } + if (waitTransition) { + if (callback) { + callback(); + } + } + }]; + }]; +#elif SD_MAC + [NSAnimationContext runAnimationGroup:^(NSAnimationContext * _Nonnull prepareContext) { + if (!view.sd_latestOperationKey || ![originalOperationKey isEqualToString:view.sd_latestOperationKey]) { + return; + } + // 0 duration to let AppKit render placeholder and prepares block + prepareContext.duration = 0; + if (transition.prepares) { + transition.prepares(view, image, imageData, cacheType, imageURL); + } + } completionHandler:^{ + [NSAnimationContext runAnimationGroup:^(NSAnimationContext * _Nonnull context) { + if (!view.sd_latestOperationKey || ![originalOperationKey isEqualToString:view.sd_latestOperationKey]) { + return; + } + context.duration = transition.duration; +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + CAMediaTimingFunction *timingFunction = transition.timingFunction; +#pragma clang diagnostic pop + if (!timingFunction) { + timingFunction = SDTimingFunctionFromAnimationOptions(transition.animationOptions); + } + context.timingFunction = timingFunction; + context.allowsImplicitAnimation = SD_OPTIONS_CONTAINS(transition.animationOptions, SDWebImageAnimationOptionAllowsImplicitAnimation); + if (finalSetImageBlock && !transition.avoidAutoSetImage) { + finalSetImageBlock(image, imageData, cacheType, imageURL); + } + CATransition *trans = SDTransitionFromAnimationOptions(transition.animationOptions); + if (trans) { + [view.layer addAnimation:trans forKey:kCATransition]; + } + if (transition.animations) { + transition.animations(view, image); + } + } completionHandler:^{ + if (!view.sd_latestOperationKey || ![originalOperationKey isEqualToString:view.sd_latestOperationKey]) { + return; + } + if (transition.completion) { + transition.completion(YES); + } + if (waitTransition) { + if (callback) { + callback(); + } + } + }]; + }]; +#endif + if (!waitTransition) { + if (callback) { + callback(); + } + } + } else { + if (finalSetImageBlock) { + finalSetImageBlock(image, imageData, cacheType, imageURL); + // TODO, in 6.0 + // for `waitTransition`, the `setImageBlock` will provide a extra `completionHandler` params + // Execute `callback` only after that completionHandler is called + if (waitTransition) { + if (callback) { + callback(); + } + } + } + if (!waitTransition) { + if (callback) { + callback(); + } + } + } +} +#endif + +- (void)sd_setNeedsLayout { +#if SD_UIKIT + [self setNeedsLayout]; +#elif SD_MAC + [self setNeedsLayout:YES]; +#elif SD_WATCH + // Do nothing because WatchKit automatically layout the view after property change +#endif +} + +#if SD_UIKIT || SD_MAC + +#pragma mark - Image Transition +- (SDWebImageTransition *)sd_imageTransition { + return objc_getAssociatedObject(self, @selector(sd_imageTransition)); +} + +- (void)setSd_imageTransition:(SDWebImageTransition *)sd_imageTransition { + objc_setAssociatedObject(self, @selector(sd_imageTransition), sd_imageTransition, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#pragma mark - Indicator +- (id)sd_imageIndicator { + return objc_getAssociatedObject(self, @selector(sd_imageIndicator)); +} + +- (void)setSd_imageIndicator:(id)sd_imageIndicator { + // Remove the old indicator view + id previousIndicator = self.sd_imageIndicator; + [previousIndicator.indicatorView removeFromSuperview]; + + objc_setAssociatedObject(self, @selector(sd_imageIndicator), sd_imageIndicator, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + + // Add the new indicator view + UIView *view = sd_imageIndicator.indicatorView; + if (CGRectEqualToRect(view.frame, CGRectZero)) { + view.frame = self.bounds; + } + // Center the indicator view +#if SD_MAC + [view setFrameOrigin:CGPointMake(round((NSWidth(self.bounds) - NSWidth(view.frame)) / 2), round((NSHeight(self.bounds) - NSHeight(view.frame)) / 2))]; +#else + view.center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds)); +#endif + view.hidden = NO; + [self addSubview:view]; +} + +- (void)sd_startImageIndicatorWithQueue:(SDCallbackQueue *)queue { + id imageIndicator = self.sd_imageIndicator; + if (!imageIndicator) { + return; + } + [(queue ?: SDCallbackQueue.mainQueue) async:^{ + [imageIndicator startAnimatingIndicator]; + }]; +} + +- (void)sd_stopImageIndicatorWithQueue:(SDCallbackQueue *)queue { + id imageIndicator = self.sd_imageIndicator; + if (!imageIndicator) { + return; + } + [(queue ?: SDCallbackQueue.mainQueue) async:^{ + [imageIndicator stopAnimatingIndicator]; + }]; +} + +#endif + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/UIView+WebCacheOperation.h b/Pods/SDWebImage/SDWebImage/Core/UIView+WebCacheOperation.h new file mode 100644 index 0000000..0bc12ca --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/UIView+WebCacheOperation.h @@ -0,0 +1,52 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" +#import "SDWebImageOperation.h" + +/** + These methods are used to support canceling for UIView image loading, it's designed to be used internal but not external. + All the stored operations are weak, so it will be dealloced after image loading finished. If you need to store operations, use your own class to keep a strong reference for them. + */ +@interface UIView (WebCacheOperation) + +/** + * Get the image load operation for key + * + * @param key key for identifying the operations + * @return the image load operation + * @note If key is nil, means using the NSStringFromClass(self.class) instead, match the behavior of `operation key` + */ +- (nullable id)sd_imageLoadOperationForKey:(nullable NSString *)key; + +/** + * Set the image load operation (storage in a UIView based weak map table) + * + * @param operation the operation, should not be nil or no-op will perform + * @param key key for storing the operation + * @note If key is nil, means using the NSStringFromClass(self.class) instead, match the behavior of `operation key` + */ +- (void)sd_setImageLoadOperation:(nullable id)operation forKey:(nullable NSString *)key; + +/** + * Cancel the operation for the current UIView and key + * + * @param key key for identifying the operations + * @note If key is nil, means using the NSStringFromClass(self.class) instead, match the behavior of `operation key` + */ +- (void)sd_cancelImageLoadOperationWithKey:(nullable NSString *)key; + +/** + * Just remove the operation corresponding to the current UIView and key without cancelling them + * + * @param key key for identifying the operations. + * @note If key is nil, means using the NSStringFromClass(self.class) instead, match the behavior of `operation key` + */ +- (void)sd_removeImageLoadOperationWithKey:(nullable NSString *)key; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/UIView+WebCacheOperation.m b/Pods/SDWebImage/SDWebImage/Core/UIView+WebCacheOperation.m new file mode 100644 index 0000000..99c8fe4 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/UIView+WebCacheOperation.m @@ -0,0 +1,85 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "UIView+WebCacheOperation.h" +#import "objc/runtime.h" + +// key is strong, value is weak because operation instance is retained by SDWebImageManager's runningOperations property +// we should use lock to keep thread-safe because these method may not be accessed from main queue +typedef NSMapTable> SDOperationsDictionary; + +@implementation UIView (WebCacheOperation) + +- (SDOperationsDictionary *)sd_operationDictionary { + @synchronized(self) { + SDOperationsDictionary *operations = objc_getAssociatedObject(self, @selector(sd_operationDictionary)); + if (operations) { + return operations; + } + operations = [[NSMapTable alloc] initWithKeyOptions:NSPointerFunctionsStrongMemory valueOptions:NSPointerFunctionsWeakMemory capacity:0]; + objc_setAssociatedObject(self, @selector(sd_operationDictionary), operations, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + return operations; + } +} + +- (nullable id)sd_imageLoadOperationForKey:(nullable NSString *)key { + id operation; + if (!key) { + key = NSStringFromClass(self.class); + } + SDOperationsDictionary *operationDictionary = [self sd_operationDictionary]; + @synchronized (self) { + operation = [operationDictionary objectForKey:key]; + } + return operation; +} + +- (void)sd_setImageLoadOperation:(nullable id)operation forKey:(nullable NSString *)key { + if (!key) { + key = NSStringFromClass(self.class); + } + if (operation) { + SDOperationsDictionary *operationDictionary = [self sd_operationDictionary]; + @synchronized (self) { + [operationDictionary setObject:operation forKey:key]; + } + } +} + +- (void)sd_cancelImageLoadOperationWithKey:(nullable NSString *)key { + if (!key) { + key = NSStringFromClass(self.class); + } + // Cancel in progress downloader from queue + SDOperationsDictionary *operationDictionary = [self sd_operationDictionary]; + id operation; + + @synchronized (self) { + operation = [operationDictionary objectForKey:key]; + } + if (operation) { + if ([operation respondsToSelector:@selector(cancel)]) { + [operation cancel]; + } + @synchronized (self) { + [operationDictionary removeObjectForKey:key]; + } + } +} + +- (void)sd_removeImageLoadOperationWithKey:(nullable NSString *)key { + if (!key) { + key = NSStringFromClass(self.class); + } + SDOperationsDictionary *operationDictionary = [self sd_operationDictionary]; + @synchronized (self) { + [operationDictionary removeObjectForKey:key]; + } +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/UIView+WebCacheState.h b/Pods/SDWebImage/SDWebImage/Core/UIView+WebCacheState.h new file mode 100644 index 0000000..5276387 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/UIView+WebCacheState.h @@ -0,0 +1,63 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" + +/** + A loading state to manage View Category which contains multiple states. Like UIImgeView.image && UIImageView.highlightedImage + + * @code + SDWebImageLoadState *loadState = [self sd_imageLoadStateForKey:@keypath(self, highlitedImage)]; + NSProgress *highlitedImageProgress = loadState.progress; + * @endcode + */ +@interface SDWebImageLoadState : NSObject + +/** + Image loading URL + */ +@property (nonatomic, strong, nullable) NSURL *url; +/** + Image loading progress. The unit count is the received size and excepted size of download. + */ +@property (nonatomic, strong, nullable) NSProgress *progress; + +@end + +/** + These methods are used for WebCache view which have multiple states for image loading, for example, `UIButton` or `UIImageView.highlightedImage` + It maitain the state container for per-operation, make it possible for control and check each image loading operation's state. + @note For developer who want to add SDWebImage View Category support for their own stateful class, learn more on Wiki. + */ +@interface UIView (WebCacheState) + +/** + Get the image loading state container for specify operation key + + @param key key for identifying the operations + @return The image loading state container + */ +- (nullable SDWebImageLoadState *)sd_imageLoadStateForKey:(nullable NSString *)key; + +/** + Set the image loading state container for specify operation key + + @param state The image loading state container + @param key key for identifying the operations + */ +- (void)sd_setImageLoadState:(nullable SDWebImageLoadState *)state forKey:(nullable NSString *)key; + +/** + Rmove the image loading state container for specify operation key + + @param key key for identifying the operations + */ +- (void)sd_removeImageLoadStateForKey:(nullable NSString *)key; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Core/UIView+WebCacheState.m b/Pods/SDWebImage/SDWebImage/Core/UIView+WebCacheState.m new file mode 100644 index 0000000..7312b98 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Core/UIView+WebCacheState.m @@ -0,0 +1,56 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "UIView+WebCacheState.h" +#import "objc/runtime.h" + +typedef NSMutableDictionary SDStatesDictionary; + +@implementation SDWebImageLoadState + +@end + +@implementation UIView (WebCacheState) + +- (SDStatesDictionary *)sd_imageLoadStateDictionary { + SDStatesDictionary *states = objc_getAssociatedObject(self, @selector(sd_imageLoadStateDictionary)); + if (!states) { + states = [NSMutableDictionary dictionary]; + objc_setAssociatedObject(self, @selector(sd_imageLoadStateDictionary), states, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + return states; +} + +- (SDWebImageLoadState *)sd_imageLoadStateForKey:(NSString *)key { + if (!key) { + key = NSStringFromClass(self.class); + } + @synchronized(self) { + return [self.sd_imageLoadStateDictionary objectForKey:key]; + } +} + +- (void)sd_setImageLoadState:(SDWebImageLoadState *)state forKey:(NSString *)key { + if (!key) { + key = NSStringFromClass(self.class); + } + @synchronized(self) { + self.sd_imageLoadStateDictionary[key] = state; + } +} + +- (void)sd_removeImageLoadStateForKey:(NSString *)key { + if (!key) { + key = NSStringFromClass(self.class); + } + @synchronized(self) { + self.sd_imageLoadStateDictionary[key] = nil; + } +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Private/NSBezierPath+SDRoundedCorners.h b/Pods/SDWebImage/SDWebImage/Private/NSBezierPath+SDRoundedCorners.h new file mode 100644 index 0000000..dfec18b --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Private/NSBezierPath+SDRoundedCorners.h @@ -0,0 +1,24 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +#if SD_MAC + +#import "UIImage+Transform.h" + +@interface NSBezierPath (SDRoundedCorners) + +/** + Convenience way to create a bezier path with the specify rounding corners on macOS. Same as the one on `UIBezierPath`. + */ ++ (nonnull instancetype)sd_bezierPathWithRoundedRect:(NSRect)rect byRoundingCorners:(SDRectCorner)corners cornerRadius:(CGFloat)cornerRadius; + +@end + +#endif diff --git a/Pods/SDWebImage/SDWebImage/Private/NSBezierPath+SDRoundedCorners.m b/Pods/SDWebImage/SDWebImage/Private/NSBezierPath+SDRoundedCorners.m new file mode 100644 index 0000000..b6f7a01 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Private/NSBezierPath+SDRoundedCorners.m @@ -0,0 +1,42 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "NSBezierPath+SDRoundedCorners.h" + +#if SD_MAC + +@implementation NSBezierPath (SDRoundedCorners) + ++ (instancetype)sd_bezierPathWithRoundedRect:(NSRect)rect byRoundingCorners:(SDRectCorner)corners cornerRadius:(CGFloat)cornerRadius { + NSBezierPath *path = [NSBezierPath bezierPath]; + + CGFloat maxCorner = MIN(NSWidth(rect), NSHeight(rect)) / 2; + + CGFloat topLeftRadius = MIN(maxCorner, (corners & SDRectCornerTopLeft) ? cornerRadius : 0); + CGFloat topRightRadius = MIN(maxCorner, (corners & SDRectCornerTopRight) ? cornerRadius : 0); + CGFloat bottomLeftRadius = MIN(maxCorner, (corners & SDRectCornerBottomLeft) ? cornerRadius : 0); + CGFloat bottomRightRadius = MIN(maxCorner, (corners & SDRectCornerBottomRight) ? cornerRadius : 0); + + NSPoint topLeft = NSMakePoint(NSMinX(rect), NSMaxY(rect)); + NSPoint topRight = NSMakePoint(NSMaxX(rect), NSMaxY(rect)); + NSPoint bottomLeft = NSMakePoint(NSMinX(rect), NSMinY(rect)); + NSPoint bottomRight = NSMakePoint(NSMaxX(rect), NSMinY(rect)); + + [path moveToPoint:NSMakePoint(NSMidX(rect), NSMaxY(rect))]; + [path appendBezierPathWithArcFromPoint:topLeft toPoint:bottomLeft radius:topLeftRadius]; + [path appendBezierPathWithArcFromPoint:bottomLeft toPoint:bottomRight radius:bottomLeftRadius]; + [path appendBezierPathWithArcFromPoint:bottomRight toPoint:topRight radius:bottomRightRadius]; + [path appendBezierPathWithArcFromPoint:topRight toPoint:topLeft radius:topRightRadius]; + [path closePath]; + + return path; +} + +@end + +#endif diff --git a/Pods/SDWebImage/SDWebImage/Private/SDAssociatedObject.h b/Pods/SDWebImage/SDWebImage/Private/SDAssociatedObject.h new file mode 100644 index 0000000..199cf4f --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Private/SDAssociatedObject.h @@ -0,0 +1,14 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import "SDWebImageCompat.h" + +/// Copy the associated object from source image to target image. The associated object including all the category read/write properties. +/// @param source source +/// @param target target +FOUNDATION_EXPORT void SDImageCopyAssociatedObject(UIImage * _Nullable source, UIImage * _Nullable target); diff --git a/Pods/SDWebImage/SDWebImage/Private/SDAssociatedObject.m b/Pods/SDWebImage/SDWebImage/Private/SDAssociatedObject.m new file mode 100644 index 0000000..4aff1e0 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Private/SDAssociatedObject.m @@ -0,0 +1,29 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import "SDAssociatedObject.h" +#import "UIImage+Metadata.h" +#import "UIImage+ExtendedCacheData.h" +#import "UIImage+MemoryCacheCost.h" +#import "UIImage+ForceDecode.h" + +void SDImageCopyAssociatedObject(UIImage * _Nullable source, UIImage * _Nullable target) { + if (!source || !target) { + return; + } + // Image Metadata + target.sd_isIncremental = source.sd_isIncremental; + target.sd_isTransformed = source.sd_isTransformed; + target.sd_decodeOptions = source.sd_decodeOptions; + target.sd_imageLoopCount = source.sd_imageLoopCount; + target.sd_imageFormat = source.sd_imageFormat; + // Force Decode + target.sd_isDecoded = source.sd_isDecoded; + // Extended Cache Data + target.sd_extendedObject = source.sd_extendedObject; +} diff --git a/Pods/SDWebImage/SDWebImage/Private/SDAsyncBlockOperation.h b/Pods/SDWebImage/SDWebImage/Private/SDAsyncBlockOperation.h new file mode 100644 index 0000000..a3480de --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Private/SDAsyncBlockOperation.h @@ -0,0 +1,21 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +@class SDAsyncBlockOperation; +typedef void (^SDAsyncBlock)(SDAsyncBlockOperation * __nonnull asyncOperation); + +/// A async block operation, success after you call `completer` (not like `NSBlockOperation` which is for sync block, success on return) +@interface SDAsyncBlockOperation : NSOperation + +- (nonnull instancetype)initWithBlock:(nonnull SDAsyncBlock)block; ++ (nonnull instancetype)blockOperationWithBlock:(nonnull SDAsyncBlock)block; +- (void)complete; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Private/SDAsyncBlockOperation.m b/Pods/SDWebImage/SDWebImage/Private/SDAsyncBlockOperation.m new file mode 100644 index 0000000..7e83a56 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Private/SDAsyncBlockOperation.m @@ -0,0 +1,92 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDAsyncBlockOperation.h" +#import "SDInternalMacros.h" + +@interface SDAsyncBlockOperation () + +@property (nonatomic, copy, nonnull) SDAsyncBlock executionBlock; + +@end + +@implementation SDAsyncBlockOperation + +@synthesize executing = _executing; +@synthesize finished = _finished; + +- (nonnull instancetype)initWithBlock:(nonnull SDAsyncBlock)block { + self = [super init]; + if (self) { + self.executionBlock = block; + } + return self; +} + ++ (nonnull instancetype)blockOperationWithBlock:(nonnull SDAsyncBlock)block { + SDAsyncBlockOperation *operation = [[SDAsyncBlockOperation alloc] initWithBlock:block]; + return operation; +} + +- (void)start { + @synchronized (self) { + if (self.isCancelled) { + self.finished = YES; + return; + } + self.finished = NO; + self.executing = YES; + } + SDAsyncBlock executionBlock = self.executionBlock; + if (executionBlock) { + @weakify(self); + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ + @strongify(self); + if (!self) return; + executionBlock(self); + }); + } +} + +- (void)cancel { + @synchronized (self) { + [super cancel]; + if (self.isExecuting) { + self.executing = NO; + self.finished = YES; + } + } +} + + +- (void)complete { + @synchronized (self) { + if (self.isExecuting) { + self.finished = YES; + self.executing = NO; + } + } +} + +- (void)setFinished:(BOOL)finished { + [self willChangeValueForKey:@"isFinished"]; + _finished = finished; + [self didChangeValueForKey:@"isFinished"]; +} + +- (void)setExecuting:(BOOL)executing { + [self willChangeValueForKey:@"isExecuting"]; + _executing = executing; + [self didChangeValueForKey:@"isExecuting"]; +} + +- (BOOL)isAsynchronous { + return YES; +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Private/SDDeviceHelper.h b/Pods/SDWebImage/SDWebImage/Private/SDDeviceHelper.h new file mode 100644 index 0000000..808866c --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Private/SDDeviceHelper.h @@ -0,0 +1,24 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import +#import "SDWebImageCompat.h" + +/// Device information helper methods +@interface SDDeviceHelper : NSObject + +#pragma mark - RAM ++ (NSUInteger)totalMemory; ++ (NSUInteger)freeMemory; + +#pragma mark - Screen ++ (double)screenScale; ++ (double)screenEDR; ++ (double)screenMaxEDR; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Private/SDDeviceHelper.m b/Pods/SDWebImage/SDWebImage/Private/SDDeviceHelper.m new file mode 100644 index 0000000..98f48c5 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Private/SDDeviceHelper.m @@ -0,0 +1,98 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import "SDDeviceHelper.h" +#import +#import + +@implementation SDDeviceHelper + ++ (NSUInteger)totalMemory { + return (NSUInteger)[[NSProcessInfo processInfo] physicalMemory]; +} + ++ (NSUInteger)freeMemory { + mach_port_t host_port = mach_host_self(); + mach_msg_type_number_t host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t); + vm_size_t page_size; + vm_statistics_data_t vm_stat; + kern_return_t kern; + + kern = host_page_size(host_port, &page_size); + if (kern != KERN_SUCCESS) return 0; + kern = host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size); + if (kern != KERN_SUCCESS) return 0; + return vm_stat.free_count * page_size; +} + ++ (double)screenScale { +#if SD_VISION + CGFloat screenScale = UITraitCollection.currentTraitCollection.displayScale; +#elif SD_WATCH + CGFloat screenScale = [WKInterfaceDevice currentDevice].screenScale; +#elif SD_UIKIT + CGFloat screenScale = [UIScreen mainScreen].scale; +#elif SD_MAC + NSScreen *mainScreen = nil; + if (@available(macOS 10.12, *)) { + mainScreen = [NSScreen mainScreen]; + } else { + mainScreen = [NSScreen screens].firstObject; + } + CGFloat screenScale = mainScreen.backingScaleFactor ?: 1.0f; +#endif + return screenScale; +} + ++ (double)screenEDR { +#if SD_VISION + // no API to query, but it's HDR ready, from the testing, the value is 200 nits + CGFloat EDR = 2.0; +#elif SD_WATCH + // currently no HDR support, fallback to SDR + CGFloat EDR = 1.0; +#elif SD_UIKIT + CGFloat EDR = 1.0; + if (@available(iOS 16.0, tvOS 16.0, *)) { + UIScreen *mainScreen = [UIScreen mainScreen]; + EDR = mainScreen.currentEDRHeadroom; + } +#elif SD_MAC + CGFloat EDR = 1.0; + if (@available(macOS 10.15, *)) { + NSScreen *mainScreen = [NSScreen mainScreen]; + EDR = mainScreen.maximumExtendedDynamicRangeColorComponentValue; + } +#endif + return EDR; +} + ++ (double)screenMaxEDR { +#if SD_VISION + // no API to query, but it's HDR ready, from the testing, the value is 200 nits + CGFloat maxEDR = 2.0; +#elif SD_WATCH + // currently no HDR support, fallback to SDR + CGFloat maxEDR = 1.0; +#elif SD_UIKIT + CGFloat maxEDR = 1.0; + if (@available(iOS 16.0, tvOS 16.0, *)) { + UIScreen *mainScreen = [UIScreen mainScreen]; + maxEDR = mainScreen.potentialEDRHeadroom; + } +#elif SD_MAC + CGFloat maxEDR = 1.0; + if (@available(macOS 10.15, *)) { + NSScreen *mainScreen = [NSScreen mainScreen]; + maxEDR = mainScreen.maximumPotentialExtendedDynamicRangeColorComponentValue; + } +#endif + return maxEDR; +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Private/SDDisplayLink.h b/Pods/SDWebImage/SDWebImage/Private/SDDisplayLink.h new file mode 100644 index 0000000..6582ccb --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Private/SDDisplayLink.h @@ -0,0 +1,29 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import +#import "SDWebImageCompat.h" + +/// Cross-platform display link wrapper. Do not retain the target +/// Use `CADisplayLink` on iOS/tvOS, `CVDisplayLink` on macOS, `NSTimer` on watchOS +@interface SDDisplayLink : NSObject + +@property (readonly, nonatomic, weak, nullable) id target; +@property (readonly, nonatomic, assign, nonnull) SEL selector; +@property (readonly, nonatomic) NSTimeInterval duration; // elapsed time in seconds of previous callback. (or it's first callback, use the time between `start` and callback). Always zero when display link not running +@property (readonly, nonatomic) BOOL isRunning; + ++ (nonnull instancetype)displayLinkWithTarget:(nonnull id)target selector:(nonnull SEL)sel; + +- (void)addToRunLoop:(nonnull NSRunLoop *)runloop forMode:(nonnull NSRunLoopMode)mode; +- (void)removeFromRunLoop:(nonnull NSRunLoop *)runloop forMode:(nonnull NSRunLoopMode)mode; + +- (void)start; +- (void)stop; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Private/SDDisplayLink.m b/Pods/SDWebImage/SDWebImage/Private/SDDisplayLink.m new file mode 100644 index 0000000..aeae570 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Private/SDDisplayLink.m @@ -0,0 +1,292 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import "SDDisplayLink.h" +#import "SDWeakProxy.h" +#if SD_MAC +#import +#elif SD_UIKIT +#import +#endif +#include + +#if SD_MAC +static CVReturn DisplayLinkCallback(CVDisplayLinkRef displayLink, const CVTimeStamp *inNow, const CVTimeStamp *inOutputTime, CVOptionFlags flagsIn, CVOptionFlags *flagsOut, void *displayLinkContext); +#endif + +#if SD_UIKIT +static BOOL kSDDisplayLinkUseTargetTimestamp = NO; // Use `next` fire time, or `previous` fire time (only for CADisplayLink) +#endif + +#define kSDDisplayLinkInterval 1.0 / 60 + +@interface SDDisplayLink () + +@property (nonatomic, assign) NSTimeInterval previousFireTime; +@property (nonatomic, assign) NSTimeInterval nextFireTime; + +#if SD_MAC +@property (nonatomic, assign) CVDisplayLinkRef displayLink; +@property (nonatomic, assign) CVTimeStamp outputTime; +@property (nonatomic, copy) NSRunLoopMode runloopMode; +#elif SD_UIKIT +@property (nonatomic, strong) CADisplayLink *displayLink; +#else +@property (nonatomic, strong) NSTimer *displayLink; +@property (nonatomic, strong) NSRunLoop *runloop; +@property (nonatomic, copy) NSRunLoopMode runloopMode; +#endif + +@end + +@implementation SDDisplayLink + +- (void)dealloc { +#if SD_MAC + if (_displayLink) { + CVDisplayLinkStop(_displayLink); + CVDisplayLinkRelease(_displayLink); + _displayLink = NULL; + } +#elif SD_UIKIT + [_displayLink invalidate]; + _displayLink = nil; +#else + [_displayLink invalidate]; + _displayLink = nil; +#endif +} + +- (instancetype)initWithTarget:(id)target selector:(SEL)sel { + self = [super init]; + if (self) { + _target = target; + _selector = sel; + // CA/CV/NSTimer will retain to the target, we need to break this using weak proxy + SDWeakProxy *weakProxy = [SDWeakProxy proxyWithTarget:self]; +#if SD_UIKIT + if (@available(iOS 10.0, tvOS 10.0, *)) { + // Use static bool, which is a little faster than runtime OS version check + kSDDisplayLinkUseTargetTimestamp = YES; + } +#endif +#if SD_MAC + CVDisplayLinkCreateWithActiveCGDisplays(&_displayLink); + // Simulate retain for target, the target is weak proxy to self + CVDisplayLinkSetOutputCallback(_displayLink, DisplayLinkCallback, (__bridge_retained void *)weakProxy); +#elif SD_UIKIT + _displayLink = [CADisplayLink displayLinkWithTarget:weakProxy selector:@selector(displayLinkDidRefresh:)]; +#else + _displayLink = [NSTimer timerWithTimeInterval:kSDDisplayLinkInterval target:weakProxy selector:@selector(displayLinkDidRefresh:) userInfo:nil repeats:YES]; +#endif + } + return self; +} + ++ (instancetype)displayLinkWithTarget:(id)target selector:(SEL)sel { + SDDisplayLink *displayLink = [[SDDisplayLink alloc] initWithTarget:target selector:sel]; + return displayLink; +} + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability" +- (NSTimeInterval)duration { + NSTimeInterval duration = 0; +#if SD_MAC + CVTimeStamp outputTime = self.outputTime; + double periodPerSecond = (double)outputTime.videoTimeScale * outputTime.rateScalar; + if (periodPerSecond > 0) { + duration = (double)outputTime.videoRefreshPeriod / periodPerSecond; + } +#elif SD_UIKIT + // iOS 10+ use current `targetTimestamp` - previous `targetTimestamp` + // See: WWDC Session 10147 - Optimize for variable refresh rate displays + if (kSDDisplayLinkUseTargetTimestamp) { + NSTimeInterval nextFireTime = self.nextFireTime; + if (nextFireTime != 0) { + duration = self.displayLink.targetTimestamp - nextFireTime; + } else { + // Invalid, fallback `duration` + duration = self.displayLink.duration; + } + } else { + // iOS 9 use current `timestamp` - previous `timestamp` + NSTimeInterval previousFireTime = self.previousFireTime; + if (previousFireTime != 0) { + duration = self.displayLink.timestamp - previousFireTime; + } else { + // Invalid, fallback `duration` + duration = self.displayLink.duration; + } + } +#else + NSTimeInterval nextFireTime = self.nextFireTime; + if (nextFireTime != 0) { + // `CFRunLoopTimerGetNextFireDate`: This time could be a date in the past if a run loop has not been able to process the timer since the firing time arrived. + // Don't rely on this, always calculate based on elapsed time + duration = CFRunLoopTimerGetNextFireDate((__bridge CFRunLoopTimerRef)self.displayLink) - nextFireTime; + } +#endif + // When system sleep, the targetTimestamp will mass up, fallback refresh rate + if (duration < 0) { +#if SD_MAC + // Supports Pro display 120Hz + CGDirectDisplayID display = CVDisplayLinkGetCurrentCGDisplay(_displayLink); + CGDisplayModeRef mode = CGDisplayCopyDisplayMode(display); + if (mode) { + double refreshRate = CGDisplayModeGetRefreshRate(mode); + if (refreshRate > 0) { + duration = 1.0 / refreshRate; + } else { + duration = kSDDisplayLinkInterval; + } + CGDisplayModeRelease(mode); + } else { + duration = kSDDisplayLinkInterval; + } +#elif SD_UIKIT + // Fallback + duration = self.displayLink.duration; +#else + // Watch always 60Hz + duration = kSDDisplayLinkInterval; +#endif + } + return duration; +} +#pragma clang diagnostic pop + +- (BOOL)isRunning { +#if SD_MAC + return CVDisplayLinkIsRunning(self.displayLink); +#elif SD_UIKIT + return !self.displayLink.isPaused; +#else + return self.displayLink.isValid; +#endif +} + +- (void)addToRunLoop:(NSRunLoop *)runloop forMode:(NSRunLoopMode)mode { + if (!runloop || !mode) { + return; + } +#if SD_MAC + self.runloopMode = mode; +#elif SD_UIKIT + [self.displayLink addToRunLoop:runloop forMode:mode]; +#else + self.runloop = runloop; + self.runloopMode = mode; + CFRunLoopMode cfMode; + if ([mode isEqualToString:NSDefaultRunLoopMode]) { + cfMode = kCFRunLoopDefaultMode; + } else if ([mode isEqualToString:NSRunLoopCommonModes]) { + cfMode = kCFRunLoopCommonModes; + } else { + cfMode = (__bridge CFStringRef)mode; + } + CFRunLoopAddTimer(runloop.getCFRunLoop, (__bridge CFRunLoopTimerRef)self.displayLink, cfMode); +#endif +} + +- (void)removeFromRunLoop:(NSRunLoop *)runloop forMode:(NSRunLoopMode)mode { + if (!runloop || !mode) { + return; + } +#if SD_MAC + self.runloopMode = nil; +#elif SD_UIKIT + [self.displayLink removeFromRunLoop:runloop forMode:mode]; +#else + self.runloop = nil; + self.runloopMode = nil; + CFRunLoopMode cfMode; + if ([mode isEqualToString:NSDefaultRunLoopMode]) { + cfMode = kCFRunLoopDefaultMode; + } else if ([mode isEqualToString:NSRunLoopCommonModes]) { + cfMode = kCFRunLoopCommonModes; + } else { + cfMode = (__bridge CFStringRef)mode; + } + CFRunLoopRemoveTimer(runloop.getCFRunLoop, (__bridge CFRunLoopTimerRef)self.displayLink, cfMode); +#endif +} + +- (void)start { +#if SD_MAC + CVDisplayLinkStart(self.displayLink); +#elif SD_UIKIT + self.displayLink.paused = NO; +#else + if (self.displayLink.isValid) { + // Do nothing + } else { + SDWeakProxy *weakProxy = [SDWeakProxy proxyWithTarget:self]; + self.displayLink = [NSTimer timerWithTimeInterval:kSDDisplayLinkInterval target:weakProxy selector:@selector(displayLinkDidRefresh:) userInfo:nil repeats:YES]; + [self addToRunLoop:self.runloop forMode:self.runloopMode]; + } +#endif +} + +- (void)stop { +#if SD_MAC + CVDisplayLinkStop(self.displayLink); +#elif SD_UIKIT + self.displayLink.paused = YES; +#else + [self.displayLink invalidate]; +#endif + self.previousFireTime = 0; + self.nextFireTime = 0; +} + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability" +- (void)displayLinkDidRefresh:(id)displayLink { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-performSelector-leaks" + [_target performSelector:_selector withObject:self]; +#pragma clang diagnostic pop +#if SD_UIKIT + if (kSDDisplayLinkUseTargetTimestamp) { + self.nextFireTime = self.displayLink.targetTimestamp; + } else { + self.previousFireTime = self.displayLink.timestamp; + } +#endif +#if SD_WATCH + self.nextFireTime = CFRunLoopTimerGetNextFireDate((__bridge CFRunLoopTimerRef)self.displayLink); +#endif +} +#pragma clang diagnostic pop + +@end + +#if SD_MAC +static CVReturn DisplayLinkCallback(CVDisplayLinkRef displayLink, const CVTimeStamp *inNow, const CVTimeStamp *inOutputTime, CVOptionFlags flagsIn, CVOptionFlags *flagsOut, void *displayLinkContext) { + @autoreleasepool { + // CVDisplayLink callback is not on main queue + // Actually `SDWeakProxy` but not `SDDisplayLink` + SDDisplayLink *object = (__bridge SDDisplayLink *)displayLinkContext; + if (!object) return kCVReturnSuccess; + // CVDisplayLink does not use runloop, but we can provide similar behavior for modes + // May use `default` runloop to avoid extra callback when in `eventTracking` (mouse drag, scroll) or `modalPanel` (modal panel) + NSString *runloopMode = object.runloopMode; + if (![runloopMode isEqualToString:NSRunLoopCommonModes] && ![runloopMode isEqualToString:NSRunLoop.mainRunLoop.currentMode]) { + return kCVReturnSuccess; + } + CVTimeStamp outputTime = inOutputTime ? *inOutputTime : *inNow; + // `SDWeakProxy` is weak, so it's safe to dispatch to main queue without leak + dispatch_async(dispatch_get_main_queue(), ^{ + object.outputTime = outputTime; + [object displayLinkDidRefresh:(__bridge id)(displayLink)]; + }); + return kCVReturnSuccess; + } +} +#endif diff --git a/Pods/SDWebImage/SDWebImage/Private/SDFileAttributeHelper.h b/Pods/SDWebImage/SDWebImage/Private/SDFileAttributeHelper.h new file mode 100644 index 0000000..3ce6bad --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Private/SDFileAttributeHelper.h @@ -0,0 +1,19 @@ +// +// This file is from https://gist.github.com/zydeco/6292773 +// +// Created by Jesús A. Álvarez on 2008-12-17. +// Copyright 2008-2009 namedfork.net. All rights reserved. +// + +#import + +/// File Extended Attribute (xattr) helper methods +@interface SDFileAttributeHelper : NSObject + ++ (nullable NSArray *)extendedAttributeNamesAtPath:(nonnull NSString *)path traverseLink:(BOOL)follow error:(NSError * _Nullable * _Nullable)err; ++ (BOOL)hasExtendedAttribute:(nonnull NSString *)name atPath:(nonnull NSString *)path traverseLink:(BOOL)follow error:(NSError * _Nullable * _Nullable)err; ++ (nullable NSData *)extendedAttribute:(nonnull NSString *)name atPath:(nonnull NSString *)path traverseLink:(BOOL)follow error:(NSError * _Nullable * _Nullable)err; ++ (BOOL)setExtendedAttribute:(nonnull NSString *)name value:(nonnull NSData *)value atPath:(nonnull NSString *)path traverseLink:(BOOL)follow overwrite:(BOOL)overwrite error:(NSError * _Nullable * _Nullable)err; ++ (BOOL)removeExtendedAttribute:(nonnull NSString *)name atPath:(nonnull NSString *)path traverseLink:(BOOL)follow error:(NSError * _Nullable * _Nullable)err; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Private/SDFileAttributeHelper.m b/Pods/SDWebImage/SDWebImage/Private/SDFileAttributeHelper.m new file mode 100644 index 0000000..5122089 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Private/SDFileAttributeHelper.m @@ -0,0 +1,127 @@ +// +// This file is from https://gist.github.com/zydeco/6292773 +// +// Created by Jesús A. Álvarez on 2008-12-17. +// Copyright 2008-2009 namedfork.net. All rights reserved. +// + +#import "SDFileAttributeHelper.h" +#import + +@implementation SDFileAttributeHelper + ++ (NSArray*)extendedAttributeNamesAtPath:(NSString *)path traverseLink:(BOOL)follow error:(NSError **)err { + int flags = follow? 0 : XATTR_NOFOLLOW; + + // get size of name list + ssize_t nameBuffLen = listxattr([path fileSystemRepresentation], NULL, 0, flags); + if (nameBuffLen == -1) { + if (err) *err = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo: + @{ + @"error": [NSString stringWithUTF8String:strerror(errno)], + @"function": @"listxattr", + @":path": path, + @":traverseLink": @(follow) + } + ]; + return nil; + } else if (nameBuffLen == 0) return @[]; + + // get name list + NSMutableData *nameBuff = [NSMutableData dataWithLength:nameBuffLen]; + listxattr([path fileSystemRepresentation], [nameBuff mutableBytes], nameBuffLen, flags); + + // convert to array + NSMutableArray * names = [NSMutableArray arrayWithCapacity:5]; + char *nextName, *endOfNames = [nameBuff mutableBytes] + nameBuffLen; + for(nextName = [nameBuff mutableBytes]; nextName < endOfNames; nextName += 1+strlen(nextName)) + [names addObject:[NSString stringWithUTF8String:nextName]]; + return names.copy; +} + ++ (BOOL)hasExtendedAttribute:(NSString *)name atPath:(NSString *)path traverseLink:(BOOL)follow error:(NSError **)err { + int flags = follow? 0 : XATTR_NOFOLLOW; + + // get size of name list + ssize_t nameBuffLen = listxattr([path fileSystemRepresentation], NULL, 0, flags); + if (nameBuffLen == -1) { + if (err) *err = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo: + @{ + @"error": [NSString stringWithUTF8String:strerror(errno)], + @"function": @"listxattr", + @":path": path, + @":traverseLink": @(follow) + } + ]; + return NO; + } else if (nameBuffLen == 0) return NO; + + // get name list + NSMutableData *nameBuff = [NSMutableData dataWithLength:nameBuffLen]; + listxattr([path fileSystemRepresentation], [nameBuff mutableBytes], nameBuffLen, flags); + + // find our name + char *nextName, *endOfNames = [nameBuff mutableBytes] + nameBuffLen; + for(nextName = [nameBuff mutableBytes]; nextName < endOfNames; nextName += 1+strlen(nextName)) + if (strcmp(nextName, [name UTF8String]) == 0) return YES; + return NO; +} + ++ (NSData *)extendedAttribute:(NSString *)name atPath:(NSString *)path traverseLink:(BOOL)follow error:(NSError **)err { + int flags = follow? 0 : XATTR_NOFOLLOW; + // get length + ssize_t attrLen = getxattr([path fileSystemRepresentation], [name UTF8String], NULL, 0, 0, flags); + if (attrLen == -1) { + if (err) *err = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo: + @{ + @"error": [NSString stringWithUTF8String:strerror(errno)], + @"function": @"getxattr", + @":name": name, + @":path": path, + @":traverseLink": @(follow) + } + ]; + return nil; + } + + // get attribute data + NSMutableData *attrData = [NSMutableData dataWithLength:attrLen]; + getxattr([path fileSystemRepresentation], [name UTF8String], [attrData mutableBytes], attrLen, 0, flags); + return attrData; +} + ++ (BOOL)setExtendedAttribute:(NSString *)name value:(NSData *)value atPath:(NSString *)path traverseLink:(BOOL)follow overwrite:(BOOL)overwrite error:(NSError **)err { + int flags = (follow? 0 : XATTR_NOFOLLOW) | (overwrite? 0 : XATTR_CREATE); + if (0 == setxattr([path fileSystemRepresentation], [name UTF8String], [value bytes], [value length], 0, flags)) return YES; + // error + if (err) *err = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo: + @{ + @"error": [NSString stringWithUTF8String:strerror(errno)], + @"function": @"setxattr", + @":name": name, + @":value.length": @(value.length), + @":path": path, + @":traverseLink": @(follow), + @":overwrite": @(overwrite) + } + ]; + return NO; +} + ++ (BOOL)removeExtendedAttribute:(NSString *)name atPath:(NSString *)path traverseLink:(BOOL)follow error:(NSError **)err { + int flags = (follow? 0 : XATTR_NOFOLLOW); + if (0 == removexattr([path fileSystemRepresentation], [name UTF8String], flags)) return YES; + // error + if (err) *err = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo: + @{ + @"error": [NSString stringWithUTF8String:strerror(errno)], + @"function": @"removexattr", + @":name": name, + @":path": path, + @":traverseLink": @(follow) + } + ]; + return NO; +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Private/SDImageAssetManager.h b/Pods/SDWebImage/SDWebImage/Private/SDImageAssetManager.h new file mode 100644 index 0000000..88dee48 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Private/SDImageAssetManager.h @@ -0,0 +1,23 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" + +/// A Image-Asset manager to work like UIKit/AppKit's image cache behavior +/// Apple parse the Asset Catalog compiled file(`Assets.car`) by CoreUI.framework, however it's a private framework and there are no other ways to directly get the data. So we just process the normal bundle files :) +@interface SDImageAssetManager : NSObject + +@property (nonatomic, strong, nonnull) NSMapTable *imageTable; + ++ (nonnull instancetype)sharedAssetManager; +- (nullable NSString *)getPathForName:(nonnull NSString *)name bundle:(nonnull NSBundle *)bundle preferredScale:(nonnull CGFloat *)scale; +- (nullable UIImage *)imageForName:(nonnull NSString *)name; +- (void)storeImage:(nonnull UIImage *)image forName:(nonnull NSString *)name; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Private/SDImageAssetManager.m b/Pods/SDWebImage/SDWebImage/Private/SDImageAssetManager.m new file mode 100644 index 0000000..8ba3f96 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Private/SDImageAssetManager.m @@ -0,0 +1,153 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDImageAssetManager.h" +#import "SDInternalMacros.h" +#import "SDDeviceHelper.h" + +static NSArray *SDBundlePreferredScales(void) { + static NSArray *scales; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + CGFloat screenScale = SDDeviceHelper.screenScale; + if (screenScale <= 1) { + scales = @[@1,@2,@3]; + } else if (screenScale <= 2) { + scales = @[@2,@3,@1]; + } else { + scales = @[@3,@2,@1]; + } + }); + return scales; +} + +@implementation SDImageAssetManager { + SD_LOCK_DECLARE(_lock); +} + ++ (instancetype)sharedAssetManager { + static dispatch_once_t onceToken; + static SDImageAssetManager *assetManager; + dispatch_once(&onceToken, ^{ + assetManager = [[SDImageAssetManager alloc] init]; + }); + return assetManager; +} + +- (instancetype)init { + self = [super init]; + if (self) { + NSPointerFunctionsOptions valueOptions; +#if SD_MAC + // Apple says that NSImage use a weak reference to value + valueOptions = NSPointerFunctionsWeakMemory; +#else + // Apple says that UIImage use a strong reference to value + valueOptions = NSPointerFunctionsStrongMemory; +#endif + _imageTable = [NSMapTable mapTableWithKeyOptions:NSPointerFunctionsCopyIn valueOptions:valueOptions]; + SD_LOCK_INIT(_lock); +#if SD_UIKIT + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveMemoryWarning:) name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; +#endif + } + return self; +} + +- (void)dealloc { +#if SD_UIKIT + [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; +#endif +} + +- (void)didReceiveMemoryWarning:(NSNotification *)notification { + SD_LOCK(_lock); + [self.imageTable removeAllObjects]; + SD_UNLOCK(_lock); +} + +- (NSString *)getPathForName:(NSString *)name bundle:(NSBundle *)bundle preferredScale:(CGFloat *)scale { + NSParameterAssert(name); + NSParameterAssert(bundle); + NSString *path; + if (name.length == 0) { + return path; + } + if ([name hasSuffix:@"/"]) { + return path; + } + NSString *extension = name.pathExtension; + if (extension.length == 0) { + // If no extension, follow Apple's doc, check PNG format + extension = @"png"; + } + name = [name stringByDeletingPathExtension]; + + CGFloat providedScale = *scale; + NSArray *scales = SDBundlePreferredScales(); + + // Check if file name contains scale + for (size_t i = 0; i < scales.count; i++) { + NSNumber *scaleValue = scales[i]; + if ([name hasSuffix:[NSString stringWithFormat:@"@%@x", scaleValue]]) { + path = [bundle pathForResource:name ofType:extension]; + if (path) { + *scale = scaleValue.doubleValue; // override + return path; + } + } + } + + // Search with provided scale first + if (providedScale != 0) { + NSString *scaledName = [name stringByAppendingFormat:@"@%@x", @(providedScale)]; + path = [bundle pathForResource:scaledName ofType:extension]; + if (path) { + return path; + } + } + + // Search with preferred scale + for (size_t i = 0; i < scales.count; i++) { + NSNumber *scaleValue = scales[i]; + if (scaleValue.doubleValue == providedScale) { + // Ignore provided scale + continue; + } + NSString *scaledName = [name stringByAppendingFormat:@"@%@x", scaleValue]; + path = [bundle pathForResource:scaledName ofType:extension]; + if (path) { + *scale = scaleValue.doubleValue; // override + return path; + } + } + + // Search without scale + path = [bundle pathForResource:name ofType:extension]; + + return path; +} + +- (UIImage *)imageForName:(NSString *)name { + NSParameterAssert(name); + UIImage *image; + SD_LOCK(_lock); + image = [self.imageTable objectForKey:name]; + SD_UNLOCK(_lock); + return image; +} + +- (void)storeImage:(UIImage *)image forName:(NSString *)name { + NSParameterAssert(image); + NSParameterAssert(name); + SD_LOCK(_lock); + [self.imageTable setObject:image forKey:name]; + SD_UNLOCK(_lock); +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Private/SDImageCachesManagerOperation.h b/Pods/SDWebImage/SDWebImage/Private/SDImageCachesManagerOperation.h new file mode 100644 index 0000000..0debe6c --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Private/SDImageCachesManagerOperation.h @@ -0,0 +1,21 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" + +/// This is used for operation management, but not for operation queue execute +@interface SDImageCachesManagerOperation : NSOperation + +@property (nonatomic, assign, readonly) NSUInteger pendingCount; + +- (void)beginWithTotalCount:(NSUInteger)totalCount; +- (void)completeOne; +- (void)done; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Private/SDImageCachesManagerOperation.m b/Pods/SDWebImage/SDWebImage/Private/SDImageCachesManagerOperation.m new file mode 100644 index 0000000..1313b68 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Private/SDImageCachesManagerOperation.m @@ -0,0 +1,83 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDImageCachesManagerOperation.h" +#import "SDInternalMacros.h" + +@implementation SDImageCachesManagerOperation { + SD_LOCK_DECLARE(_pendingCountLock); +} + +@synthesize executing = _executing; +@synthesize finished = _finished; +@synthesize cancelled = _cancelled; +@synthesize pendingCount = _pendingCount; + +- (instancetype)init { + if (self = [super init]) { + SD_LOCK_INIT(_pendingCountLock); + _pendingCount = 0; + } + return self; +} + +- (void)beginWithTotalCount:(NSUInteger)totalCount { + self.executing = YES; + self.finished = NO; + _pendingCount = totalCount; +} + +- (NSUInteger)pendingCount { + SD_LOCK(_pendingCountLock); + NSUInteger pendingCount = _pendingCount; + SD_UNLOCK(_pendingCountLock); + return pendingCount; +} + +- (void)completeOne { + SD_LOCK(_pendingCountLock); + _pendingCount = _pendingCount > 0 ? _pendingCount - 1 : 0; + SD_UNLOCK(_pendingCountLock); +} + +- (void)cancel { + self.cancelled = YES; + [self reset]; +} + +- (void)done { + self.finished = YES; + self.executing = NO; + [self reset]; +} + +- (void)reset { + SD_LOCK(_pendingCountLock); + _pendingCount = 0; + SD_UNLOCK(_pendingCountLock); +} + +- (void)setFinished:(BOOL)finished { + [self willChangeValueForKey:@"isFinished"]; + _finished = finished; + [self didChangeValueForKey:@"isFinished"]; +} + +- (void)setExecuting:(BOOL)executing { + [self willChangeValueForKey:@"isExecuting"]; + _executing = executing; + [self didChangeValueForKey:@"isExecuting"]; +} + +- (void)setCancelled:(BOOL)cancelled { + [self willChangeValueForKey:@"isCancelled"]; + _cancelled = cancelled; + [self didChangeValueForKey:@"isCancelled"]; +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Private/SDImageFramePool.h b/Pods/SDWebImage/SDWebImage/Private/SDImageFramePool.h new file mode 100644 index 0000000..6fedc83 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Private/SDImageFramePool.h @@ -0,0 +1,40 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import +#import "SDWebImageCompat.h" +#import "SDImageCoder.h" + +NS_ASSUME_NONNULL_BEGIN + +/// A per-provider (provider means, AnimatedImage object) based frame pool, each player who use the same provider share the same frame buffer +@interface SDImageFramePool : NSObject + +/// Register and return back a frame pool, also increase reference count ++ (instancetype)registerProvider:(id)provider; +/// Unregister a frame pool, also decrease reference count, if zero dealloc the frame pool ++ (void)unregisterProvider:(id)provider; + +/// Prefetch the current frame, query using `frameAtIndex:` by caller to check whether finished. +- (void)prefetchFrameAtIndex:(NSUInteger)index; + +/// Control the max buffer count for current frame pool, used for RAM/CPU balance, default unlimited +@property (nonatomic, assign) NSUInteger maxBufferCount; +/// Control the max concurrent fetch queue operation count, used for CPU balance, default 1 +@property (nonatomic, assign) NSUInteger maxConcurrentCount; + +// Frame Operations +@property (nonatomic, readonly) NSUInteger currentFrameCount; +- (nullable UIImage *)frameAtIndex:(NSUInteger)index; +- (void)setFrame:(nullable UIImage *)frame atIndex:(NSUInteger)index; +- (void)removeFrameAtIndex:(NSUInteger)index; +- (void)removeAllFrames; + +NS_ASSUME_NONNULL_END + +@end diff --git a/Pods/SDWebImage/SDWebImage/Private/SDImageFramePool.m b/Pods/SDWebImage/SDWebImage/Private/SDImageFramePool.m new file mode 100644 index 0000000..3426f49 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Private/SDImageFramePool.m @@ -0,0 +1,168 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import "SDImageFramePool.h" +#import "SDInternalMacros.h" +#import "objc/runtime.h" + +@interface SDImageFramePool () + +@property (class, readonly) NSMapTable *providerFramePoolMap; + +@property (weak) id provider; +@property (atomic) NSUInteger registerCount; + +@property (nonatomic, strong) NSMutableDictionary *frameBuffer; +@property (nonatomic, strong) NSOperationQueue *fetchQueue; + +@end + +// Lock to ensure atomic behavior +SD_LOCK_DECLARE_STATIC(_providerFramePoolMapLock); + +@implementation SDImageFramePool + ++ (NSMapTable *)providerFramePoolMap { + static NSMapTable *providerFramePoolMap; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + // Key use `hash` && `isEqual:` + providerFramePoolMap = [NSMapTable mapTableWithKeyOptions:NSPointerFunctionsStrongMemory | NSPointerFunctionsObjectPersonality valueOptions:NSPointerFunctionsStrongMemory | NSPointerFunctionsObjectPointerPersonality]; + }); + return providerFramePoolMap; +} + +#pragma mark - Life Cycle +- (instancetype)init { + self = [super init]; + if (self) { + _frameBuffer = [NSMutableDictionary dictionary]; + _fetchQueue = [[NSOperationQueue alloc] init]; + _fetchQueue.maxConcurrentOperationCount = 1; + _fetchQueue.name = @"com.hackemist.SDImageFramePool.fetchQueue"; +#if SD_UIKIT + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveMemoryWarning:) name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; +#endif + } + return self; +} + +- (void)dealloc { +#if SD_UIKIT + [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; +#endif +} + +- (void)didReceiveMemoryWarning:(NSNotification *)notification { + [self removeAllFrames]; +} + ++ (void)initialize { + // Lock to ensure atomic behavior + SD_LOCK_INIT(_providerFramePoolMapLock); +} + ++ (instancetype)registerProvider:(id)provider { + // Lock to ensure atomic behavior + SD_LOCK(_providerFramePoolMapLock); + SDImageFramePool *framePool = [self.providerFramePoolMap objectForKey:provider]; + if (!framePool) { + framePool = [[SDImageFramePool alloc] init]; + framePool.provider = provider; + [self.providerFramePoolMap setObject:framePool forKey:provider]; + } + framePool.registerCount += 1; + SD_UNLOCK(_providerFramePoolMapLock); + return framePool; +} + ++ (void)unregisterProvider:(id)provider { + // Lock to ensure atomic behavior + SD_LOCK(_providerFramePoolMapLock); + SDImageFramePool *framePool = [self.providerFramePoolMap objectForKey:provider]; + if (!framePool) { + SD_UNLOCK(_providerFramePoolMapLock); + return; + } + framePool.registerCount -= 1; + if (framePool.registerCount == 0) { + [self.providerFramePoolMap removeObjectForKey:provider]; + } + SD_UNLOCK(_providerFramePoolMapLock); +} + +- (void)prefetchFrameAtIndex:(NSUInteger)index { + @synchronized (self) { + NSUInteger frameCount = self.frameBuffer.count; + if (frameCount > self.maxBufferCount) { + // Remove the frame buffer if need + // TODO, use LRU or better algorithm to detect which frames to clear + self.frameBuffer[@(index - 1)] = nil; + self.frameBuffer[@(index + 1)] = nil; + } + } + + if (self.fetchQueue.operationCount == 0) { + // Prefetch next frame in background queue + @weakify(self); + NSOperation *operation = [NSBlockOperation blockOperationWithBlock:^{ + @strongify(self); + if (!self) { + return; + } + id animatedProvider = self.provider; + if (!animatedProvider) { + return; + } + UIImage *frame = [animatedProvider animatedImageFrameAtIndex:index]; + + [self setFrame:frame atIndex:index]; + }]; + [self.fetchQueue addOperation:operation]; + } +} + +- (void)setMaxConcurrentCount:(NSUInteger)maxConcurrentCount { + self.fetchQueue.maxConcurrentOperationCount = maxConcurrentCount; +} + +- (NSUInteger)currentFrameCount { + NSUInteger frameCount = 0; + @synchronized (self) { + frameCount = self.frameBuffer.count; + } + return frameCount; +} + +- (void)setFrame:(UIImage *)frame atIndex:(NSUInteger)index { + @synchronized (self) { + self.frameBuffer[@(index)] = frame; + } +} + +- (UIImage *)frameAtIndex:(NSUInteger)index { + UIImage *frame; + @synchronized (self) { + frame = self.frameBuffer[@(index)]; + } + return frame; +} + +- (void)removeFrameAtIndex:(NSUInteger)index { + @synchronized (self) { + self.frameBuffer[@(index)] = nil; + } +} + +- (void)removeAllFrames { + @synchronized (self) { + [self.frameBuffer removeAllObjects]; + } +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Private/SDImageIOAnimatedCoderInternal.h b/Pods/SDWebImage/SDWebImage/Private/SDImageIOAnimatedCoderInternal.h new file mode 100644 index 0000000..d24091a --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Private/SDImageIOAnimatedCoderInternal.h @@ -0,0 +1,42 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import +#import +#import "SDImageIOAnimatedCoder.h" + +// Xcode 16 SDK contains HDR encoding API, but we still support Xcode 15 +#define SD_IMAGEIO_HDR_ENCODING (__IPHONE_OS_VERSION_MAX_ALLOWED >= 180000) + +// AVFileTypeHEIC/AVFileTypeHEIF is defined in AVFoundation via iOS 11, we use this without import AVFoundation +#define kSDUTTypeHEIC ((__bridge CFStringRef)@"public.heic") +#define kSDUTTypeHEIF ((__bridge CFStringRef)@"public.heif") +// HEIC Sequence (Animated Image) +#define kSDUTTypeHEICS ((__bridge CFStringRef)@"public.heics") +// kSDUTTypeWebP seems not defined in public UTI framework, Apple use the hardcode string, we define them :) +#define kSDUTTypeWebP ((__bridge CFStringRef)@"org.webmproject.webp") + +#define kSDUTTypeImage ((__bridge CFStringRef)@"public.image") +#define kSDUTTypeJPEG ((__bridge CFStringRef)@"public.jpeg") +#define kSDUTTypePNG ((__bridge CFStringRef)@"public.png") +#define kSDUTTypeTIFF ((__bridge CFStringRef)@"public.tiff") +#define kSDUTTypeSVG ((__bridge CFStringRef)@"public.svg-image") +#define kSDUTTypeGIF ((__bridge CFStringRef)@"com.compuserve.gif") +#define kSDUTTypePDF ((__bridge CFStringRef)@"com.adobe.pdf") +#define kSDUTTypeBMP ((__bridge CFStringRef)@"com.microsoft.bmp") +#define kSDUTTypeRAW ((__bridge CFStringRef)@"public.camera-raw-image") + +@interface SDImageIOAnimatedCoder () + ++ (NSTimeInterval)frameDurationAtIndex:(NSUInteger)index source:(nonnull CGImageSourceRef)source; ++ (NSUInteger)imageLoopCountWithSource:(nonnull CGImageSourceRef)source; ++ (nullable UIImage *)createFrameAtIndex:(NSUInteger)index source:(nonnull CGImageSourceRef)source scale:(CGFloat)scale preserveAspectRatio:(BOOL)preserveAspectRatio thumbnailSize:(CGSize)thumbnailSize lazyDecode:(BOOL)lazyDecode animatedImage:(BOOL)animatedImage decodeToHDR:(BOOL)decodeToHDR; ++ (BOOL)canEncodeToFormat:(SDImageFormat)format; ++ (BOOL)canDecodeFromFormat:(SDImageFormat)format; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Private/SDInternalMacros.h b/Pods/SDWebImage/SDWebImage/Private/SDInternalMacros.h new file mode 100644 index 0000000..c324ccc --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Private/SDInternalMacros.h @@ -0,0 +1,195 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import +#import +#import +#import "SDmetamacros.h" + +#define SD_USE_OS_UNFAIR_LOCK TARGET_OS_MACCATALYST ||\ + (__IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_10_0) ||\ + (__MAC_OS_X_VERSION_MIN_REQUIRED >= __MAC_10_12) ||\ + (__TV_OS_VERSION_MIN_REQUIRED >= __TVOS_10_0) ||\ + (__WATCH_OS_VERSION_MIN_REQUIRED >= __WATCHOS_3_0) + +#ifndef SD_LOCK_DECLARE +#if SD_USE_OS_UNFAIR_LOCK +#define SD_LOCK_DECLARE(lock) os_unfair_lock lock +#else +#define SD_LOCK_DECLARE(lock) os_unfair_lock lock API_AVAILABLE(ios(10.0), tvos(10), watchos(3), macos(10.12)); \ +OSSpinLock lock##_deprecated; +#endif +#endif + +#ifndef SD_LOCK_DECLARE_STATIC +#if SD_USE_OS_UNFAIR_LOCK +#define SD_LOCK_DECLARE_STATIC(lock) static os_unfair_lock lock +#else +#define SD_LOCK_DECLARE_STATIC(lock) static os_unfair_lock lock API_AVAILABLE(ios(10.0), tvos(10), watchos(3), macos(10.12)); \ +static OSSpinLock lock##_deprecated; +#endif +#endif + +#ifndef SD_LOCK_INIT +#if SD_USE_OS_UNFAIR_LOCK +#define SD_LOCK_INIT(lock) lock = OS_UNFAIR_LOCK_INIT +#else +#define SD_LOCK_INIT(lock) if (@available(iOS 10, tvOS 10, watchOS 3, macOS 10.12, *)) lock = OS_UNFAIR_LOCK_INIT; \ +else lock##_deprecated = OS_SPINLOCK_INIT; +#endif +#endif + +#ifndef SD_LOCK +#if SD_USE_OS_UNFAIR_LOCK +#define SD_LOCK(lock) os_unfair_lock_lock(&lock) +#else +#define SD_LOCK(lock) if (@available(iOS 10, tvOS 10, watchOS 3, macOS 10.12, *)) os_unfair_lock_lock(&lock); \ +else OSSpinLockLock(&lock##_deprecated); +#endif +#endif + +#ifndef SD_UNLOCK +#if SD_USE_OS_UNFAIR_LOCK +#define SD_UNLOCK(lock) os_unfair_lock_unlock(&lock) +#else +#define SD_UNLOCK(lock) if (@available(iOS 10, tvOS 10, watchOS 3, macOS 10.12, *)) os_unfair_lock_unlock(&lock); \ +else OSSpinLockUnlock(&lock##_deprecated); +#endif +#endif + +#ifndef SD_OPTIONS_CONTAINS +#define SD_OPTIONS_CONTAINS(options, value) (((options) & (value)) == (value)) +#endif + +#ifndef SD_CSTRING +#define SD_CSTRING(str) #str +#endif + +#ifndef SD_NSSTRING +#define SD_NSSTRING(str) @(SD_CSTRING(str)) +#endif + +#ifndef SD_SEL_SPI +#define SD_SEL_SPI(name) NSSelectorFromString([NSString stringWithFormat:@"_%@", SD_NSSTRING(name)]) +#endif + +FOUNDATION_EXPORT os_log_t sd_getDefaultLog(void); + +#ifndef SD_LOG +#define SD_LOG(_log, ...) if (@available(iOS 10.0, tvOS 10.0, macOS 10.12, watchOS 3.0, *)) os_log(sd_getDefaultLog(), _log, ##__VA_ARGS__); \ +else NSLog(@(_log), ##__VA_ARGS__); +#endif + +#ifndef weakify +#define weakify(...) \ +sd_keywordify \ +metamacro_foreach_cxt(sd_weakify_,, __weak, __VA_ARGS__) +#endif + +#ifndef strongify +#define strongify(...) \ +sd_keywordify \ +_Pragma("clang diagnostic push") \ +_Pragma("clang diagnostic ignored \"-Wshadow\"") \ +metamacro_foreach(sd_strongify_,, __VA_ARGS__) \ +_Pragma("clang diagnostic pop") +#endif + +#define sd_weakify_(INDEX, CONTEXT, VAR) \ +CONTEXT __typeof__(VAR) metamacro_concat(VAR, _weak_) = (VAR); + +#define sd_strongify_(INDEX, VAR) \ +__strong __typeof__(VAR) VAR = metamacro_concat(VAR, _weak_); + +#if DEBUG +#define sd_keywordify autoreleasepool {} +#else +#define sd_keywordify try {} @catch (...) {} +#endif + +#ifndef onExit +#define onExit \ +sd_keywordify \ +__strong sd_cleanupBlock_t metamacro_concat(sd_exitBlock_, __LINE__) __attribute__((cleanup(sd_executeCleanupBlock), unused)) = ^ +#endif + +typedef void (^sd_cleanupBlock_t)(void); + +#if defined(__cplusplus) +extern "C" { +#endif + void sd_executeCleanupBlock (__strong sd_cleanupBlock_t *block); +#if defined(__cplusplus) +} +#endif + +/** + * \@keypath allows compile-time verification of key paths. Given a real object + * receiver and key path: + * + * @code + +NSString *UTF8StringPath = @keypath(str.lowercaseString.UTF8String); +// => @"lowercaseString.UTF8String" + +NSString *versionPath = @keypath(NSObject, version); +// => @"version" + +NSString *lowercaseStringPath = @keypath(NSString.new, lowercaseString); +// => @"lowercaseString" + + * @endcode + * + * ... the macro returns an \c NSString containing all but the first path + * component or argument (e.g., @"lowercaseString.UTF8String", @"version"). + * + * In addition to simply creating a key path, this macro ensures that the key + * path is valid at compile-time (causing a syntax error if not), and supports + * refactoring, such that changing the name of the property will also update any + * uses of \@keypath. + */ +#define keypath(...) \ + _Pragma("clang diagnostic push") \ + _Pragma("clang diagnostic ignored \"-Warc-repeated-use-of-weak\"") \ + (NO).boolValue ? ((NSString * _Nonnull)nil) : ((NSString * _Nonnull)@(cStringKeypath(__VA_ARGS__))) \ + _Pragma("clang diagnostic pop") \ + +#define cStringKeypath(...) \ + metamacro_if_eq(1, metamacro_argcount(__VA_ARGS__))(keypath1(__VA_ARGS__))(keypath2(__VA_ARGS__)) + +#define keypath1(PATH) \ + (((void)(NO && ((void)PATH, NO)), \ + ({ char *__extobjckeypath__ = strchr(# PATH, '.'); NSCAssert(__extobjckeypath__, @"Provided key path is invalid."); __extobjckeypath__ + 1; }))) + +#define keypath2(OBJ, PATH) \ + (((void)(NO && ((void)OBJ.PATH, NO)), # PATH)) + +/** + * \@collectionKeypath allows compile-time verification of key paths across collections NSArray/NSSet etc. Given a real object + * receiver, collection object receiver and related keypaths: + * + * @code + + NSString *employeesFirstNamePath = @collectionKeypath(department.employees, Employee.new, firstName) + // => @"employees.firstName" + + NSString *employeesFirstNamePath = @collectionKeypath(Department.new, employees, Employee.new, firstName) + // => @"employees.firstName" + + * @endcode + * + */ +#define collectionKeypath(...) \ + metamacro_if_eq(3, metamacro_argcount(__VA_ARGS__))(collectionKeypath3(__VA_ARGS__))(collectionKeypath4(__VA_ARGS__)) + +#define collectionKeypath3(PATH, COLLECTION_OBJECT, COLLECTION_PATH) \ + (YES).boolValue ? (NSString * _Nonnull)@((const char * _Nonnull)[[NSString stringWithFormat:@"%s.%s", cStringKeypath(PATH), cStringKeypath(COLLECTION_OBJECT, COLLECTION_PATH)] UTF8String]) : (NSString * _Nonnull)nil + +#define collectionKeypath4(OBJ, PATH, COLLECTION_OBJECT, COLLECTION_PATH) \ + (YES).boolValue ? (NSString * _Nonnull)@((const char * _Nonnull)[[NSString stringWithFormat:@"%s.%s", cStringKeypath(OBJ, PATH), cStringKeypath(COLLECTION_OBJECT, COLLECTION_PATH)] UTF8String]) : (NSString * _Nonnull)nil diff --git a/Pods/SDWebImage/SDWebImage/Private/SDInternalMacros.m b/Pods/SDWebImage/SDWebImage/Private/SDInternalMacros.m new file mode 100644 index 0000000..939ba70 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Private/SDInternalMacros.m @@ -0,0 +1,22 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDInternalMacros.h" + +os_log_t sd_getDefaultLog(void) { + static dispatch_once_t onceToken; + static os_log_t log; + dispatch_once(&onceToken, ^{ + log = os_log_create("com.hackemist.SDWebImage", "Default"); + }); + return log; +} + +void sd_executeCleanupBlock (__strong sd_cleanupBlock_t *block) { + (*block)(); +} diff --git a/Pods/SDWebImage/SDWebImage/Private/SDWeakProxy.h b/Pods/SDWebImage/SDWebImage/Private/SDWeakProxy.h new file mode 100644 index 0000000..d92c682 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Private/SDWeakProxy.h @@ -0,0 +1,20 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" + +/// A weak proxy which forward all the message to the target +@interface SDWeakProxy : NSProxy + +@property (nonatomic, weak, readonly, nullable) id target; + +- (nonnull instancetype)initWithTarget:(nonnull id)target; ++ (nonnull instancetype)proxyWithTarget:(nonnull id)target; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Private/SDWeakProxy.m b/Pods/SDWebImage/SDWebImage/Private/SDWeakProxy.m new file mode 100644 index 0000000..19a4593 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Private/SDWeakProxy.m @@ -0,0 +1,79 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWeakProxy.h" + +@implementation SDWeakProxy + +- (instancetype)initWithTarget:(id)target { + _target = target; + return self; +} + ++ (instancetype)proxyWithTarget:(id)target { + return [[SDWeakProxy alloc] initWithTarget:target]; +} + +- (id)forwardingTargetForSelector:(SEL)selector { + return _target; +} + +- (void)forwardInvocation:(NSInvocation *)invocation { + void *null = NULL; + [invocation setReturnValue:&null]; +} + +- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector { + return [NSObject instanceMethodSignatureForSelector:@selector(init)]; +} + +- (BOOL)respondsToSelector:(SEL)aSelector { + return [_target respondsToSelector:aSelector]; +} + +- (BOOL)isEqual:(id)object { + return [_target isEqual:object]; +} + +- (NSUInteger)hash { + return [_target hash]; +} + +- (Class)superclass { + return [_target superclass]; +} + +- (Class)class { + return [_target class]; +} + +- (BOOL)isKindOfClass:(Class)aClass { + return [_target isKindOfClass:aClass]; +} + +- (BOOL)isMemberOfClass:(Class)aClass { + return [_target isMemberOfClass:aClass]; +} + +- (BOOL)conformsToProtocol:(Protocol *)aProtocol { + return [_target conformsToProtocol:aProtocol]; +} + +- (BOOL)isProxy { + return YES; +} + +- (NSString *)description { + return [_target description]; +} + +- (NSString *)debugDescription { + return [_target debugDescription]; +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/Private/SDWebImageTransitionInternal.h b/Pods/SDWebImage/SDWebImage/Private/SDWebImageTransitionInternal.h new file mode 100644 index 0000000..1b70649 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Private/SDWebImageTransitionInternal.h @@ -0,0 +1,19 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import "SDWebImageCompat.h" + +#if SD_MAC + +#import + +/// Helper method for Core Animation transition +FOUNDATION_EXPORT CAMediaTimingFunction * _Nullable SDTimingFunctionFromAnimationOptions(SDWebImageAnimationOptions options); +FOUNDATION_EXPORT CATransition * _Nullable SDTransitionFromAnimationOptions(SDWebImageAnimationOptions options); + +#endif diff --git a/Pods/SDWebImage/SDWebImage/Private/SDmetamacros.h b/Pods/SDWebImage/SDWebImage/Private/SDmetamacros.h new file mode 100644 index 0000000..dd90d99 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Private/SDmetamacros.h @@ -0,0 +1,667 @@ +/** + * Macros for metaprogramming + * ExtendedC + * + * Copyright (C) 2012 Justin Spahr-Summers + * Released under the MIT license + */ + +#ifndef EXTC_METAMACROS_H +#define EXTC_METAMACROS_H + + +/** + * Executes one or more expressions (which may have a void type, such as a call + * to a function that returns no value) and always returns true. + */ +#define metamacro_exprify(...) \ + ((__VA_ARGS__), true) + +/** + * Returns a string representation of VALUE after full macro expansion. + */ +#define metamacro_stringify(VALUE) \ + metamacro_stringify_(VALUE) + +/** + * Returns A and B concatenated after full macro expansion. + */ +#define metamacro_concat(A, B) \ + metamacro_concat_(A, B) + +/** + * Returns the Nth variadic argument (starting from zero). At least + * N + 1 variadic arguments must be given. N must be between zero and twenty, + * inclusive. + */ +#define metamacro_at(N, ...) \ + metamacro_concat(metamacro_at, N)(__VA_ARGS__) + +/** + * Returns the number of arguments (up to twenty) provided to the macro. At + * least one argument must be provided. + * + * Inspired by P99: http://p99.gforge.inria.fr + */ +#define metamacro_argcount(...) \ + metamacro_at(20, __VA_ARGS__, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1) + +/** + * Identical to #metamacro_foreach_cxt, except that no CONTEXT argument is + * given. Only the index and current argument will thus be passed to MACRO. + */ +#define metamacro_foreach(MACRO, SEP, ...) \ + metamacro_foreach_cxt(metamacro_foreach_iter, SEP, MACRO, __VA_ARGS__) + +/** + * For each consecutive variadic argument (up to twenty), MACRO is passed the + * zero-based index of the current argument, CONTEXT, and then the argument + * itself. The results of adjoining invocations of MACRO are then separated by + * SEP. + * + * Inspired by P99: http://p99.gforge.inria.fr + */ +#define metamacro_foreach_cxt(MACRO, SEP, CONTEXT, ...) \ + metamacro_concat(metamacro_foreach_cxt, metamacro_argcount(__VA_ARGS__))(MACRO, SEP, CONTEXT, __VA_ARGS__) + +/** + * Identical to #metamacro_foreach_cxt. This can be used when the former would + * fail due to recursive macro expansion. + */ +#define metamacro_foreach_cxt_recursive(MACRO, SEP, CONTEXT, ...) \ + metamacro_concat(metamacro_foreach_cxt_recursive, metamacro_argcount(__VA_ARGS__))(MACRO, SEP, CONTEXT, __VA_ARGS__) + +/** + * In consecutive order, appends each variadic argument (up to twenty) onto + * BASE. The resulting concatenations are then separated by SEP. + * + * This is primarily useful to manipulate a list of macro invocations into instead + * invoking a different, possibly related macro. + */ +#define metamacro_foreach_concat(BASE, SEP, ...) \ + metamacro_foreach_cxt(metamacro_foreach_concat_iter, SEP, BASE, __VA_ARGS__) + +/** + * Iterates COUNT times, each time invoking MACRO with the current index + * (starting at zero) and CONTEXT. The results of adjoining invocations of MACRO + * are then separated by SEP. + * + * COUNT must be an integer between zero and twenty, inclusive. + */ +#define metamacro_for_cxt(COUNT, MACRO, SEP, CONTEXT) \ + metamacro_concat(metamacro_for_cxt, COUNT)(MACRO, SEP, CONTEXT) + +/** + * Returns the first argument given. At least one argument must be provided. + * + * This is useful when implementing a variadic macro, where you may have only + * one variadic argument, but no way to retrieve it (for example, because \c ... + * always needs to match at least one argument). + * + * @code + +#define varmacro(...) \ + metamacro_head(__VA_ARGS__) + + * @endcode + */ +#define metamacro_head(...) \ + metamacro_head_(__VA_ARGS__, 0) + +/** + * Returns every argument except the first. At least two arguments must be + * provided. + */ +#define metamacro_tail(...) \ + metamacro_tail_(__VA_ARGS__) + +/** + * Returns the first N (up to twenty) variadic arguments as a new argument list. + * At least N variadic arguments must be provided. + */ +#define metamacro_take(N, ...) \ + metamacro_concat(metamacro_take, N)(__VA_ARGS__) + +/** + * Removes the first N (up to twenty) variadic arguments from the given argument + * list. At least N variadic arguments must be provided. + */ +#define metamacro_drop(N, ...) \ + metamacro_concat(metamacro_drop, N)(__VA_ARGS__) + +/** + * Decrements VAL, which must be a number between zero and twenty, inclusive. + * + * This is primarily useful when dealing with indexes and counts in + * metaprogramming. + */ +#define metamacro_dec(VAL) \ + metamacro_at(VAL, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19) + +/** + * Increments VAL, which must be a number between zero and twenty, inclusive. + * + * This is primarily useful when dealing with indexes and counts in + * metaprogramming. + */ +#define metamacro_inc(VAL) \ + metamacro_at(VAL, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21) + +/** + * If A is equal to B, the next argument list is expanded; otherwise, the + * argument list after that is expanded. A and B must be numbers between zero + * and twenty, inclusive. Additionally, B must be greater than or equal to A. + * + * @code + +// expands to true +metamacro_if_eq(0, 0)(true)(false) + +// expands to false +metamacro_if_eq(0, 1)(true)(false) + + * @endcode + * + * This is primarily useful when dealing with indexes and counts in + * metaprogramming. + */ +#define metamacro_if_eq(A, B) \ + metamacro_concat(metamacro_if_eq, A)(B) + +/** + * Identical to #metamacro_if_eq. This can be used when the former would fail + * due to recursive macro expansion. + */ +#define metamacro_if_eq_recursive(A, B) \ + metamacro_concat(metamacro_if_eq_recursive, A)(B) + +/** + * Returns 1 if N is an even number, or 0 otherwise. N must be between zero and + * twenty, inclusive. + * + * For the purposes of this test, zero is considered even. + */ +#define metamacro_is_even(N) \ + metamacro_at(N, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1) + +/** + * Returns the logical NOT of B, which must be the number zero or one. + */ +#define metamacro_not(B) \ + metamacro_at(B, 1, 0) + +// IMPLEMENTATION DETAILS FOLLOW! +// Do not write code that depends on anything below this line. +#define metamacro_stringify_(VALUE) # VALUE +#define metamacro_concat_(A, B) A ## B +#define metamacro_foreach_iter(INDEX, MACRO, ARG) MACRO(INDEX, ARG) +#define metamacro_head_(FIRST, ...) FIRST +#define metamacro_tail_(FIRST, ...) __VA_ARGS__ +#define metamacro_consume_(...) +#define metamacro_expand_(...) __VA_ARGS__ + +// implemented from scratch so that metamacro_concat() doesn't end up nesting +#define metamacro_foreach_concat_iter(INDEX, BASE, ARG) metamacro_foreach_concat_iter_(BASE, ARG) +#define metamacro_foreach_concat_iter_(BASE, ARG) BASE ## ARG + +// metamacro_at expansions +#define metamacro_at0(...) metamacro_head(__VA_ARGS__) +#define metamacro_at1(_0, ...) metamacro_head(__VA_ARGS__) +#define metamacro_at2(_0, _1, ...) metamacro_head(__VA_ARGS__) +#define metamacro_at3(_0, _1, _2, ...) metamacro_head(__VA_ARGS__) +#define metamacro_at4(_0, _1, _2, _3, ...) metamacro_head(__VA_ARGS__) +#define metamacro_at5(_0, _1, _2, _3, _4, ...) metamacro_head(__VA_ARGS__) +#define metamacro_at6(_0, _1, _2, _3, _4, _5, ...) metamacro_head(__VA_ARGS__) +#define metamacro_at7(_0, _1, _2, _3, _4, _5, _6, ...) metamacro_head(__VA_ARGS__) +#define metamacro_at8(_0, _1, _2, _3, _4, _5, _6, _7, ...) metamacro_head(__VA_ARGS__) +#define metamacro_at9(_0, _1, _2, _3, _4, _5, _6, _7, _8, ...) metamacro_head(__VA_ARGS__) +#define metamacro_at10(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, ...) metamacro_head(__VA_ARGS__) +#define metamacro_at11(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, ...) metamacro_head(__VA_ARGS__) +#define metamacro_at12(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, ...) metamacro_head(__VA_ARGS__) +#define metamacro_at13(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, ...) metamacro_head(__VA_ARGS__) +#define metamacro_at14(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, ...) metamacro_head(__VA_ARGS__) +#define metamacro_at15(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, ...) metamacro_head(__VA_ARGS__) +#define metamacro_at16(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, ...) metamacro_head(__VA_ARGS__) +#define metamacro_at17(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, ...) metamacro_head(__VA_ARGS__) +#define metamacro_at18(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, ...) metamacro_head(__VA_ARGS__) +#define metamacro_at19(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, ...) metamacro_head(__VA_ARGS__) +#define metamacro_at20(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, ...) metamacro_head(__VA_ARGS__) + +// metamacro_foreach_cxt expansions +#define metamacro_foreach_cxt0(MACRO, SEP, CONTEXT) +#define metamacro_foreach_cxt1(MACRO, SEP, CONTEXT, _0) MACRO(0, CONTEXT, _0) + +#define metamacro_foreach_cxt2(MACRO, SEP, CONTEXT, _0, _1) \ + metamacro_foreach_cxt1(MACRO, SEP, CONTEXT, _0) \ + SEP \ + MACRO(1, CONTEXT, _1) + +#define metamacro_foreach_cxt3(MACRO, SEP, CONTEXT, _0, _1, _2) \ + metamacro_foreach_cxt2(MACRO, SEP, CONTEXT, _0, _1) \ + SEP \ + MACRO(2, CONTEXT, _2) + +#define metamacro_foreach_cxt4(MACRO, SEP, CONTEXT, _0, _1, _2, _3) \ + metamacro_foreach_cxt3(MACRO, SEP, CONTEXT, _0, _1, _2) \ + SEP \ + MACRO(3, CONTEXT, _3) + +#define metamacro_foreach_cxt5(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4) \ + metamacro_foreach_cxt4(MACRO, SEP, CONTEXT, _0, _1, _2, _3) \ + SEP \ + MACRO(4, CONTEXT, _4) + +#define metamacro_foreach_cxt6(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5) \ + metamacro_foreach_cxt5(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4) \ + SEP \ + MACRO(5, CONTEXT, _5) + +#define metamacro_foreach_cxt7(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6) \ + metamacro_foreach_cxt6(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5) \ + SEP \ + MACRO(6, CONTEXT, _6) + +#define metamacro_foreach_cxt8(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7) \ + metamacro_foreach_cxt7(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6) \ + SEP \ + MACRO(7, CONTEXT, _7) + +#define metamacro_foreach_cxt9(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8) \ + metamacro_foreach_cxt8(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7) \ + SEP \ + MACRO(8, CONTEXT, _8) + +#define metamacro_foreach_cxt10(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9) \ + metamacro_foreach_cxt9(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8) \ + SEP \ + MACRO(9, CONTEXT, _9) + +#define metamacro_foreach_cxt11(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) \ + metamacro_foreach_cxt10(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9) \ + SEP \ + MACRO(10, CONTEXT, _10) + +#define metamacro_foreach_cxt12(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11) \ + metamacro_foreach_cxt11(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) \ + SEP \ + MACRO(11, CONTEXT, _11) + +#define metamacro_foreach_cxt13(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12) \ + metamacro_foreach_cxt12(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11) \ + SEP \ + MACRO(12, CONTEXT, _12) + +#define metamacro_foreach_cxt14(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13) \ + metamacro_foreach_cxt13(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12) \ + SEP \ + MACRO(13, CONTEXT, _13) + +#define metamacro_foreach_cxt15(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14) \ + metamacro_foreach_cxt14(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13) \ + SEP \ + MACRO(14, CONTEXT, _14) + +#define metamacro_foreach_cxt16(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15) \ + metamacro_foreach_cxt15(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14) \ + SEP \ + MACRO(15, CONTEXT, _15) + +#define metamacro_foreach_cxt17(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16) \ + metamacro_foreach_cxt16(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15) \ + SEP \ + MACRO(16, CONTEXT, _16) + +#define metamacro_foreach_cxt18(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17) \ + metamacro_foreach_cxt17(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16) \ + SEP \ + MACRO(17, CONTEXT, _17) + +#define metamacro_foreach_cxt19(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18) \ + metamacro_foreach_cxt18(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17) \ + SEP \ + MACRO(18, CONTEXT, _18) + +#define metamacro_foreach_cxt20(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19) \ + metamacro_foreach_cxt19(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18) \ + SEP \ + MACRO(19, CONTEXT, _19) + +// metamacro_foreach_cxt_recursive expansions +#define metamacro_foreach_cxt_recursive0(MACRO, SEP, CONTEXT) +#define metamacro_foreach_cxt_recursive1(MACRO, SEP, CONTEXT, _0) MACRO(0, CONTEXT, _0) + +#define metamacro_foreach_cxt_recursive2(MACRO, SEP, CONTEXT, _0, _1) \ + metamacro_foreach_cxt_recursive1(MACRO, SEP, CONTEXT, _0) \ + SEP \ + MACRO(1, CONTEXT, _1) + +#define metamacro_foreach_cxt_recursive3(MACRO, SEP, CONTEXT, _0, _1, _2) \ + metamacro_foreach_cxt_recursive2(MACRO, SEP, CONTEXT, _0, _1) \ + SEP \ + MACRO(2, CONTEXT, _2) + +#define metamacro_foreach_cxt_recursive4(MACRO, SEP, CONTEXT, _0, _1, _2, _3) \ + metamacro_foreach_cxt_recursive3(MACRO, SEP, CONTEXT, _0, _1, _2) \ + SEP \ + MACRO(3, CONTEXT, _3) + +#define metamacro_foreach_cxt_recursive5(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4) \ + metamacro_foreach_cxt_recursive4(MACRO, SEP, CONTEXT, _0, _1, _2, _3) \ + SEP \ + MACRO(4, CONTEXT, _4) + +#define metamacro_foreach_cxt_recursive6(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5) \ + metamacro_foreach_cxt_recursive5(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4) \ + SEP \ + MACRO(5, CONTEXT, _5) + +#define metamacro_foreach_cxt_recursive7(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6) \ + metamacro_foreach_cxt_recursive6(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5) \ + SEP \ + MACRO(6, CONTEXT, _6) + +#define metamacro_foreach_cxt_recursive8(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7) \ + metamacro_foreach_cxt_recursive7(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6) \ + SEP \ + MACRO(7, CONTEXT, _7) + +#define metamacro_foreach_cxt_recursive9(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8) \ + metamacro_foreach_cxt_recursive8(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7) \ + SEP \ + MACRO(8, CONTEXT, _8) + +#define metamacro_foreach_cxt_recursive10(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9) \ + metamacro_foreach_cxt_recursive9(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8) \ + SEP \ + MACRO(9, CONTEXT, _9) + +#define metamacro_foreach_cxt_recursive11(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) \ + metamacro_foreach_cxt_recursive10(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9) \ + SEP \ + MACRO(10, CONTEXT, _10) + +#define metamacro_foreach_cxt_recursive12(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11) \ + metamacro_foreach_cxt_recursive11(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) \ + SEP \ + MACRO(11, CONTEXT, _11) + +#define metamacro_foreach_cxt_recursive13(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12) \ + metamacro_foreach_cxt_recursive12(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11) \ + SEP \ + MACRO(12, CONTEXT, _12) + +#define metamacro_foreach_cxt_recursive14(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13) \ + metamacro_foreach_cxt_recursive13(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12) \ + SEP \ + MACRO(13, CONTEXT, _13) + +#define metamacro_foreach_cxt_recursive15(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14) \ + metamacro_foreach_cxt_recursive14(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13) \ + SEP \ + MACRO(14, CONTEXT, _14) + +#define metamacro_foreach_cxt_recursive16(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15) \ + metamacro_foreach_cxt_recursive15(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14) \ + SEP \ + MACRO(15, CONTEXT, _15) + +#define metamacro_foreach_cxt_recursive17(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16) \ + metamacro_foreach_cxt_recursive16(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15) \ + SEP \ + MACRO(16, CONTEXT, _16) + +#define metamacro_foreach_cxt_recursive18(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17) \ + metamacro_foreach_cxt_recursive17(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16) \ + SEP \ + MACRO(17, CONTEXT, _17) + +#define metamacro_foreach_cxt_recursive19(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18) \ + metamacro_foreach_cxt_recursive18(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17) \ + SEP \ + MACRO(18, CONTEXT, _18) + +#define metamacro_foreach_cxt_recursive20(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19) \ + metamacro_foreach_cxt_recursive19(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18) \ + SEP \ + MACRO(19, CONTEXT, _19) + +// metamacro_for_cxt expansions +#define metamacro_for_cxt0(MACRO, SEP, CONTEXT) +#define metamacro_for_cxt1(MACRO, SEP, CONTEXT) MACRO(0, CONTEXT) + +#define metamacro_for_cxt2(MACRO, SEP, CONTEXT) \ + metamacro_for_cxt1(MACRO, SEP, CONTEXT) \ + SEP \ + MACRO(1, CONTEXT) + +#define metamacro_for_cxt3(MACRO, SEP, CONTEXT) \ + metamacro_for_cxt2(MACRO, SEP, CONTEXT) \ + SEP \ + MACRO(2, CONTEXT) + +#define metamacro_for_cxt4(MACRO, SEP, CONTEXT) \ + metamacro_for_cxt3(MACRO, SEP, CONTEXT) \ + SEP \ + MACRO(3, CONTEXT) + +#define metamacro_for_cxt5(MACRO, SEP, CONTEXT) \ + metamacro_for_cxt4(MACRO, SEP, CONTEXT) \ + SEP \ + MACRO(4, CONTEXT) + +#define metamacro_for_cxt6(MACRO, SEP, CONTEXT) \ + metamacro_for_cxt5(MACRO, SEP, CONTEXT) \ + SEP \ + MACRO(5, CONTEXT) + +#define metamacro_for_cxt7(MACRO, SEP, CONTEXT) \ + metamacro_for_cxt6(MACRO, SEP, CONTEXT) \ + SEP \ + MACRO(6, CONTEXT) + +#define metamacro_for_cxt8(MACRO, SEP, CONTEXT) \ + metamacro_for_cxt7(MACRO, SEP, CONTEXT) \ + SEP \ + MACRO(7, CONTEXT) + +#define metamacro_for_cxt9(MACRO, SEP, CONTEXT) \ + metamacro_for_cxt8(MACRO, SEP, CONTEXT) \ + SEP \ + MACRO(8, CONTEXT) + +#define metamacro_for_cxt10(MACRO, SEP, CONTEXT) \ + metamacro_for_cxt9(MACRO, SEP, CONTEXT) \ + SEP \ + MACRO(9, CONTEXT) + +#define metamacro_for_cxt11(MACRO, SEP, CONTEXT) \ + metamacro_for_cxt10(MACRO, SEP, CONTEXT) \ + SEP \ + MACRO(10, CONTEXT) + +#define metamacro_for_cxt12(MACRO, SEP, CONTEXT) \ + metamacro_for_cxt11(MACRO, SEP, CONTEXT) \ + SEP \ + MACRO(11, CONTEXT) + +#define metamacro_for_cxt13(MACRO, SEP, CONTEXT) \ + metamacro_for_cxt12(MACRO, SEP, CONTEXT) \ + SEP \ + MACRO(12, CONTEXT) + +#define metamacro_for_cxt14(MACRO, SEP, CONTEXT) \ + metamacro_for_cxt13(MACRO, SEP, CONTEXT) \ + SEP \ + MACRO(13, CONTEXT) + +#define metamacro_for_cxt15(MACRO, SEP, CONTEXT) \ + metamacro_for_cxt14(MACRO, SEP, CONTEXT) \ + SEP \ + MACRO(14, CONTEXT) + +#define metamacro_for_cxt16(MACRO, SEP, CONTEXT) \ + metamacro_for_cxt15(MACRO, SEP, CONTEXT) \ + SEP \ + MACRO(15, CONTEXT) + +#define metamacro_for_cxt17(MACRO, SEP, CONTEXT) \ + metamacro_for_cxt16(MACRO, SEP, CONTEXT) \ + SEP \ + MACRO(16, CONTEXT) + +#define metamacro_for_cxt18(MACRO, SEP, CONTEXT) \ + metamacro_for_cxt17(MACRO, SEP, CONTEXT) \ + SEP \ + MACRO(17, CONTEXT) + +#define metamacro_for_cxt19(MACRO, SEP, CONTEXT) \ + metamacro_for_cxt18(MACRO, SEP, CONTEXT) \ + SEP \ + MACRO(18, CONTEXT) + +#define metamacro_for_cxt20(MACRO, SEP, CONTEXT) \ + metamacro_for_cxt19(MACRO, SEP, CONTEXT) \ + SEP \ + MACRO(19, CONTEXT) + +// metamacro_if_eq expansions +#define metamacro_if_eq0(VALUE) \ + metamacro_concat(metamacro_if_eq0_, VALUE) + +#define metamacro_if_eq0_0(...) __VA_ARGS__ metamacro_consume_ +#define metamacro_if_eq0_1(...) metamacro_expand_ +#define metamacro_if_eq0_2(...) metamacro_expand_ +#define metamacro_if_eq0_3(...) metamacro_expand_ +#define metamacro_if_eq0_4(...) metamacro_expand_ +#define metamacro_if_eq0_5(...) metamacro_expand_ +#define metamacro_if_eq0_6(...) metamacro_expand_ +#define metamacro_if_eq0_7(...) metamacro_expand_ +#define metamacro_if_eq0_8(...) metamacro_expand_ +#define metamacro_if_eq0_9(...) metamacro_expand_ +#define metamacro_if_eq0_10(...) metamacro_expand_ +#define metamacro_if_eq0_11(...) metamacro_expand_ +#define metamacro_if_eq0_12(...) metamacro_expand_ +#define metamacro_if_eq0_13(...) metamacro_expand_ +#define metamacro_if_eq0_14(...) metamacro_expand_ +#define metamacro_if_eq0_15(...) metamacro_expand_ +#define metamacro_if_eq0_16(...) metamacro_expand_ +#define metamacro_if_eq0_17(...) metamacro_expand_ +#define metamacro_if_eq0_18(...) metamacro_expand_ +#define metamacro_if_eq0_19(...) metamacro_expand_ +#define metamacro_if_eq0_20(...) metamacro_expand_ + +#define metamacro_if_eq1(VALUE) metamacro_if_eq0(metamacro_dec(VALUE)) +#define metamacro_if_eq2(VALUE) metamacro_if_eq1(metamacro_dec(VALUE)) +#define metamacro_if_eq3(VALUE) metamacro_if_eq2(metamacro_dec(VALUE)) +#define metamacro_if_eq4(VALUE) metamacro_if_eq3(metamacro_dec(VALUE)) +#define metamacro_if_eq5(VALUE) metamacro_if_eq4(metamacro_dec(VALUE)) +#define metamacro_if_eq6(VALUE) metamacro_if_eq5(metamacro_dec(VALUE)) +#define metamacro_if_eq7(VALUE) metamacro_if_eq6(metamacro_dec(VALUE)) +#define metamacro_if_eq8(VALUE) metamacro_if_eq7(metamacro_dec(VALUE)) +#define metamacro_if_eq9(VALUE) metamacro_if_eq8(metamacro_dec(VALUE)) +#define metamacro_if_eq10(VALUE) metamacro_if_eq9(metamacro_dec(VALUE)) +#define metamacro_if_eq11(VALUE) metamacro_if_eq10(metamacro_dec(VALUE)) +#define metamacro_if_eq12(VALUE) metamacro_if_eq11(metamacro_dec(VALUE)) +#define metamacro_if_eq13(VALUE) metamacro_if_eq12(metamacro_dec(VALUE)) +#define metamacro_if_eq14(VALUE) metamacro_if_eq13(metamacro_dec(VALUE)) +#define metamacro_if_eq15(VALUE) metamacro_if_eq14(metamacro_dec(VALUE)) +#define metamacro_if_eq16(VALUE) metamacro_if_eq15(metamacro_dec(VALUE)) +#define metamacro_if_eq17(VALUE) metamacro_if_eq16(metamacro_dec(VALUE)) +#define metamacro_if_eq18(VALUE) metamacro_if_eq17(metamacro_dec(VALUE)) +#define metamacro_if_eq19(VALUE) metamacro_if_eq18(metamacro_dec(VALUE)) +#define metamacro_if_eq20(VALUE) metamacro_if_eq19(metamacro_dec(VALUE)) + +// metamacro_if_eq_recursive expansions +#define metamacro_if_eq_recursive0(VALUE) \ + metamacro_concat(metamacro_if_eq_recursive0_, VALUE) + +#define metamacro_if_eq_recursive0_0(...) __VA_ARGS__ metamacro_consume_ +#define metamacro_if_eq_recursive0_1(...) metamacro_expand_ +#define metamacro_if_eq_recursive0_2(...) metamacro_expand_ +#define metamacro_if_eq_recursive0_3(...) metamacro_expand_ +#define metamacro_if_eq_recursive0_4(...) metamacro_expand_ +#define metamacro_if_eq_recursive0_5(...) metamacro_expand_ +#define metamacro_if_eq_recursive0_6(...) metamacro_expand_ +#define metamacro_if_eq_recursive0_7(...) metamacro_expand_ +#define metamacro_if_eq_recursive0_8(...) metamacro_expand_ +#define metamacro_if_eq_recursive0_9(...) metamacro_expand_ +#define metamacro_if_eq_recursive0_10(...) metamacro_expand_ +#define metamacro_if_eq_recursive0_11(...) metamacro_expand_ +#define metamacro_if_eq_recursive0_12(...) metamacro_expand_ +#define metamacro_if_eq_recursive0_13(...) metamacro_expand_ +#define metamacro_if_eq_recursive0_14(...) metamacro_expand_ +#define metamacro_if_eq_recursive0_15(...) metamacro_expand_ +#define metamacro_if_eq_recursive0_16(...) metamacro_expand_ +#define metamacro_if_eq_recursive0_17(...) metamacro_expand_ +#define metamacro_if_eq_recursive0_18(...) metamacro_expand_ +#define metamacro_if_eq_recursive0_19(...) metamacro_expand_ +#define metamacro_if_eq_recursive0_20(...) metamacro_expand_ + +#define metamacro_if_eq_recursive1(VALUE) metamacro_if_eq_recursive0(metamacro_dec(VALUE)) +#define metamacro_if_eq_recursive2(VALUE) metamacro_if_eq_recursive1(metamacro_dec(VALUE)) +#define metamacro_if_eq_recursive3(VALUE) metamacro_if_eq_recursive2(metamacro_dec(VALUE)) +#define metamacro_if_eq_recursive4(VALUE) metamacro_if_eq_recursive3(metamacro_dec(VALUE)) +#define metamacro_if_eq_recursive5(VALUE) metamacro_if_eq_recursive4(metamacro_dec(VALUE)) +#define metamacro_if_eq_recursive6(VALUE) metamacro_if_eq_recursive5(metamacro_dec(VALUE)) +#define metamacro_if_eq_recursive7(VALUE) metamacro_if_eq_recursive6(metamacro_dec(VALUE)) +#define metamacro_if_eq_recursive8(VALUE) metamacro_if_eq_recursive7(metamacro_dec(VALUE)) +#define metamacro_if_eq_recursive9(VALUE) metamacro_if_eq_recursive8(metamacro_dec(VALUE)) +#define metamacro_if_eq_recursive10(VALUE) metamacro_if_eq_recursive9(metamacro_dec(VALUE)) +#define metamacro_if_eq_recursive11(VALUE) metamacro_if_eq_recursive10(metamacro_dec(VALUE)) +#define metamacro_if_eq_recursive12(VALUE) metamacro_if_eq_recursive11(metamacro_dec(VALUE)) +#define metamacro_if_eq_recursive13(VALUE) metamacro_if_eq_recursive12(metamacro_dec(VALUE)) +#define metamacro_if_eq_recursive14(VALUE) metamacro_if_eq_recursive13(metamacro_dec(VALUE)) +#define metamacro_if_eq_recursive15(VALUE) metamacro_if_eq_recursive14(metamacro_dec(VALUE)) +#define metamacro_if_eq_recursive16(VALUE) metamacro_if_eq_recursive15(metamacro_dec(VALUE)) +#define metamacro_if_eq_recursive17(VALUE) metamacro_if_eq_recursive16(metamacro_dec(VALUE)) +#define metamacro_if_eq_recursive18(VALUE) metamacro_if_eq_recursive17(metamacro_dec(VALUE)) +#define metamacro_if_eq_recursive19(VALUE) metamacro_if_eq_recursive18(metamacro_dec(VALUE)) +#define metamacro_if_eq_recursive20(VALUE) metamacro_if_eq_recursive19(metamacro_dec(VALUE)) + +// metamacro_take expansions +#define metamacro_take0(...) +#define metamacro_take1(...) metamacro_head(__VA_ARGS__) +#define metamacro_take2(...) metamacro_head(__VA_ARGS__), metamacro_take1(metamacro_tail(__VA_ARGS__)) +#define metamacro_take3(...) metamacro_head(__VA_ARGS__), metamacro_take2(metamacro_tail(__VA_ARGS__)) +#define metamacro_take4(...) metamacro_head(__VA_ARGS__), metamacro_take3(metamacro_tail(__VA_ARGS__)) +#define metamacro_take5(...) metamacro_head(__VA_ARGS__), metamacro_take4(metamacro_tail(__VA_ARGS__)) +#define metamacro_take6(...) metamacro_head(__VA_ARGS__), metamacro_take5(metamacro_tail(__VA_ARGS__)) +#define metamacro_take7(...) metamacro_head(__VA_ARGS__), metamacro_take6(metamacro_tail(__VA_ARGS__)) +#define metamacro_take8(...) metamacro_head(__VA_ARGS__), metamacro_take7(metamacro_tail(__VA_ARGS__)) +#define metamacro_take9(...) metamacro_head(__VA_ARGS__), metamacro_take8(metamacro_tail(__VA_ARGS__)) +#define metamacro_take10(...) metamacro_head(__VA_ARGS__), metamacro_take9(metamacro_tail(__VA_ARGS__)) +#define metamacro_take11(...) metamacro_head(__VA_ARGS__), metamacro_take10(metamacro_tail(__VA_ARGS__)) +#define metamacro_take12(...) metamacro_head(__VA_ARGS__), metamacro_take11(metamacro_tail(__VA_ARGS__)) +#define metamacro_take13(...) metamacro_head(__VA_ARGS__), metamacro_take12(metamacro_tail(__VA_ARGS__)) +#define metamacro_take14(...) metamacro_head(__VA_ARGS__), metamacro_take13(metamacro_tail(__VA_ARGS__)) +#define metamacro_take15(...) metamacro_head(__VA_ARGS__), metamacro_take14(metamacro_tail(__VA_ARGS__)) +#define metamacro_take16(...) metamacro_head(__VA_ARGS__), metamacro_take15(metamacro_tail(__VA_ARGS__)) +#define metamacro_take17(...) metamacro_head(__VA_ARGS__), metamacro_take16(metamacro_tail(__VA_ARGS__)) +#define metamacro_take18(...) metamacro_head(__VA_ARGS__), metamacro_take17(metamacro_tail(__VA_ARGS__)) +#define metamacro_take19(...) metamacro_head(__VA_ARGS__), metamacro_take18(metamacro_tail(__VA_ARGS__)) +#define metamacro_take20(...) metamacro_head(__VA_ARGS__), metamacro_take19(metamacro_tail(__VA_ARGS__)) + +// metamacro_drop expansions +#define metamacro_drop0(...) __VA_ARGS__ +#define metamacro_drop1(...) metamacro_tail(__VA_ARGS__) +#define metamacro_drop2(...) metamacro_drop1(metamacro_tail(__VA_ARGS__)) +#define metamacro_drop3(...) metamacro_drop2(metamacro_tail(__VA_ARGS__)) +#define metamacro_drop4(...) metamacro_drop3(metamacro_tail(__VA_ARGS__)) +#define metamacro_drop5(...) metamacro_drop4(metamacro_tail(__VA_ARGS__)) +#define metamacro_drop6(...) metamacro_drop5(metamacro_tail(__VA_ARGS__)) +#define metamacro_drop7(...) metamacro_drop6(metamacro_tail(__VA_ARGS__)) +#define metamacro_drop8(...) metamacro_drop7(metamacro_tail(__VA_ARGS__)) +#define metamacro_drop9(...) metamacro_drop8(metamacro_tail(__VA_ARGS__)) +#define metamacro_drop10(...) metamacro_drop9(metamacro_tail(__VA_ARGS__)) +#define metamacro_drop11(...) metamacro_drop10(metamacro_tail(__VA_ARGS__)) +#define metamacro_drop12(...) metamacro_drop11(metamacro_tail(__VA_ARGS__)) +#define metamacro_drop13(...) metamacro_drop12(metamacro_tail(__VA_ARGS__)) +#define metamacro_drop14(...) metamacro_drop13(metamacro_tail(__VA_ARGS__)) +#define metamacro_drop15(...) metamacro_drop14(metamacro_tail(__VA_ARGS__)) +#define metamacro_drop16(...) metamacro_drop15(metamacro_tail(__VA_ARGS__)) +#define metamacro_drop17(...) metamacro_drop16(metamacro_tail(__VA_ARGS__)) +#define metamacro_drop18(...) metamacro_drop17(metamacro_tail(__VA_ARGS__)) +#define metamacro_drop19(...) metamacro_drop18(metamacro_tail(__VA_ARGS__)) +#define metamacro_drop20(...) metamacro_drop19(metamacro_tail(__VA_ARGS__)) + +#endif diff --git a/Pods/SDWebImage/SDWebImage/Private/UIColor+SDHexString.h b/Pods/SDWebImage/SDWebImage/Private/UIColor+SDHexString.h new file mode 100644 index 0000000..cf67186 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Private/UIColor+SDHexString.h @@ -0,0 +1,18 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +@interface UIColor (SDHexString) + +/** + Convenience way to get hex string from color. The output should always be 32-bit RGBA hex string like `#00000000`. + */ +@property (nonatomic, copy, readonly, nonnull) NSString *sd_hexString; + +@end diff --git a/Pods/SDWebImage/SDWebImage/Private/UIColor+SDHexString.m b/Pods/SDWebImage/SDWebImage/Private/UIColor+SDHexString.m new file mode 100644 index 0000000..7b43c41 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/Private/UIColor+SDHexString.m @@ -0,0 +1,42 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "UIColor+SDHexString.h" + +@implementation UIColor (SDHexString) + +- (NSString *)sd_hexString { + CGFloat red, green, blue, alpha; +#if SD_UIKIT + if (![self getRed:&red green:&green blue:&blue alpha:&alpha]) { + [self getWhite:&red alpha:&alpha]; + green = red; + blue = red; + } +#else + @try { + [self getRed:&red green:&green blue:&blue alpha:&alpha]; + } + @catch (NSException *exception) { + [self getWhite:&red alpha:&alpha]; + green = red; + blue = red; + } +#endif + + red = roundf(red * 255.f); + green = roundf(green * 255.f); + blue = roundf(blue * 255.f); + alpha = roundf(alpha * 255.f); + + uint hex = ((uint)alpha << 24) | ((uint)red << 16) | ((uint)green << 8) | ((uint)blue); + + return [NSString stringWithFormat:@"#%08x", hex]; +} + +@end diff --git a/Pods/SDWebImage/WebImage/PrivacyInfo.xcprivacy b/Pods/SDWebImage/WebImage/PrivacyInfo.xcprivacy new file mode 100644 index 0000000..276f761 --- /dev/null +++ b/Pods/SDWebImage/WebImage/PrivacyInfo.xcprivacy @@ -0,0 +1,23 @@ + + + + + NSPrivacyTracking + + NSPrivacyCollectedDataTypes + + NSPrivacyTrackingDomains + + NSPrivacyAccessedAPITypes + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategoryFileTimestamp + NSPrivacyAccessedAPITypeReasons + + C617.1 + + + + + diff --git a/Pods/SDWebImage/WebImage/SDWebImage.h b/Pods/SDWebImage/WebImage/SDWebImage.h new file mode 100644 index 0000000..6bc9de8 --- /dev/null +++ b/Pods/SDWebImage/WebImage/SDWebImage.h @@ -0,0 +1,91 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * (c) Florent Vilmart + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import + +//! Project version number for SDWebImage. +FOUNDATION_EXPORT double SDWebImageVersionNumber; + +//! Project version string for SDWebImage. +FOUNDATION_EXPORT const unsigned char SDWebImageVersionString[]; + +// In this header, you should import all the public headers of your framework using statements like #import + +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import + +// Mac +#if __has_include() +#import +#endif +#if __has_include() +#import +#endif +#if __has_include() +#import +#endif + +// MapKit +#if __has_include() +#import +#endif diff --git a/Pods/Target Support Files/AFNetworking/AFNetworking-Info.plist b/Pods/Target Support Files/AFNetworking/AFNetworking-Info.plist new file mode 100644 index 0000000..5ce460e --- /dev/null +++ b/Pods/Target Support Files/AFNetworking/AFNetworking-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + ${PODS_DEVELOPMENT_LANGUAGE} + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 4.0.1 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/AFNetworking/AFNetworking-dummy.m b/Pods/Target Support Files/AFNetworking/AFNetworking-dummy.m new file mode 100644 index 0000000..6a29cf8 --- /dev/null +++ b/Pods/Target Support Files/AFNetworking/AFNetworking-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_AFNetworking : NSObject +@end +@implementation PodsDummy_AFNetworking +@end diff --git a/Pods/Target Support Files/AFNetworking/AFNetworking-prefix.pch b/Pods/Target Support Files/AFNetworking/AFNetworking-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/Pods/Target Support Files/AFNetworking/AFNetworking-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Pods/Target Support Files/AFNetworking/AFNetworking-umbrella.h b/Pods/Target Support Files/AFNetworking/AFNetworking-umbrella.h new file mode 100644 index 0000000..dee8b6e --- /dev/null +++ b/Pods/Target Support Files/AFNetworking/AFNetworking-umbrella.h @@ -0,0 +1,34 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "AFNetworking.h" +#import "AFHTTPSessionManager.h" +#import "AFURLSessionManager.h" +#import "AFCompatibilityMacros.h" +#import "AFNetworkReachabilityManager.h" +#import "AFSecurityPolicy.h" +#import "AFURLRequestSerialization.h" +#import "AFURLResponseSerialization.h" +#import "AFAutoPurgingImageCache.h" +#import "AFImageDownloader.h" +#import "AFNetworkActivityIndicatorManager.h" +#import "UIActivityIndicatorView+AFNetworking.h" +#import "UIButton+AFNetworking.h" +#import "UIImageView+AFNetworking.h" +#import "UIKit+AFNetworking.h" +#import "UIProgressView+AFNetworking.h" +#import "UIRefreshControl+AFNetworking.h" +#import "WKWebView+AFNetworking.h" + +FOUNDATION_EXPORT double AFNetworkingVersionNumber; +FOUNDATION_EXPORT const unsigned char AFNetworkingVersionString[]; + diff --git a/Pods/Target Support Files/AFNetworking/AFNetworking.debug.xcconfig b/Pods/Target Support Files/AFNetworking/AFNetworking.debug.xcconfig new file mode 100644 index 0000000..1300513 --- /dev/null +++ b/Pods/Target Support Files/AFNetworking/AFNetworking.debug.xcconfig @@ -0,0 +1,12 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/AFNetworking +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_DEVELOPMENT_LANGUAGE = ${DEVELOPMENT_LANGUAGE} +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/AFNetworking +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = com.alamofire.AFNetworking +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Pods/Target Support Files/AFNetworking/AFNetworking.modulemap b/Pods/Target Support Files/AFNetworking/AFNetworking.modulemap new file mode 100644 index 0000000..5892cd3 --- /dev/null +++ b/Pods/Target Support Files/AFNetworking/AFNetworking.modulemap @@ -0,0 +1,6 @@ +framework module AFNetworking { + umbrella header "AFNetworking-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/AFNetworking/AFNetworking.release.xcconfig b/Pods/Target Support Files/AFNetworking/AFNetworking.release.xcconfig new file mode 100644 index 0000000..1300513 --- /dev/null +++ b/Pods/Target Support Files/AFNetworking/AFNetworking.release.xcconfig @@ -0,0 +1,12 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/AFNetworking +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_DEVELOPMENT_LANGUAGE = ${DEVELOPMENT_LANGUAGE} +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/AFNetworking +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = com.alamofire.AFNetworking +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Pods/Target Support Files/Bugly/Bugly.debug.xcconfig b/Pods/Target Support Files/Bugly/Bugly.debug.xcconfig new file mode 100644 index 0000000..2f525a0 --- /dev/null +++ b/Pods/Target Support Files/Bugly/Bugly.debug.xcconfig @@ -0,0 +1,14 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Bugly +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_ROOT}/Bugly" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +OTHER_LDFLAGS = $(inherited) -l"c++" -l"z" -framework "Security" -framework "SystemConfiguration" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_DEVELOPMENT_LANGUAGE = ${DEVELOPMENT_LANGUAGE} +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/Bugly +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Pods/Target Support Files/Bugly/Bugly.release.xcconfig b/Pods/Target Support Files/Bugly/Bugly.release.xcconfig new file mode 100644 index 0000000..2f525a0 --- /dev/null +++ b/Pods/Target Support Files/Bugly/Bugly.release.xcconfig @@ -0,0 +1,14 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Bugly +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_ROOT}/Bugly" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +OTHER_LDFLAGS = $(inherited) -l"c++" -l"z" -framework "Security" -framework "SystemConfiguration" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_DEVELOPMENT_LANGUAGE = ${DEVELOPMENT_LANGUAGE} +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/Bugly +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Pods/Target Support Files/MJExtension/MJExtension-Info.plist b/Pods/Target Support Files/MJExtension/MJExtension-Info.plist new file mode 100644 index 0000000..b2c5ee6 --- /dev/null +++ b/Pods/Target Support Files/MJExtension/MJExtension-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + ${PODS_DEVELOPMENT_LANGUAGE} + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 3.4.2 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/MJExtension/MJExtension-dummy.m b/Pods/Target Support Files/MJExtension/MJExtension-dummy.m new file mode 100644 index 0000000..79c234e --- /dev/null +++ b/Pods/Target Support Files/MJExtension/MJExtension-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_MJExtension : NSObject +@end +@implementation PodsDummy_MJExtension +@end diff --git a/Pods/Target Support Files/MJExtension/MJExtension-prefix.pch b/Pods/Target Support Files/MJExtension/MJExtension-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/Pods/Target Support Files/MJExtension/MJExtension-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Pods/Target Support Files/MJExtension/MJExtension-umbrella.h b/Pods/Target Support Files/MJExtension/MJExtension-umbrella.h new file mode 100644 index 0000000..47abcfd --- /dev/null +++ b/Pods/Target Support Files/MJExtension/MJExtension-umbrella.h @@ -0,0 +1,27 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "MJExtension.h" +#import "MJExtensionConst.h" +#import "MJFoundation.h" +#import "MJProperty.h" +#import "MJPropertyKey.h" +#import "MJPropertyType.h" +#import "NSObject+MJClass.h" +#import "NSObject+MJCoding.h" +#import "NSObject+MJKeyValue.h" +#import "NSObject+MJProperty.h" +#import "NSString+MJExtension.h" + +FOUNDATION_EXPORT double MJExtensionVersionNumber; +FOUNDATION_EXPORT const unsigned char MJExtensionVersionString[]; + diff --git a/Pods/Target Support Files/MJExtension/MJExtension.debug.xcconfig b/Pods/Target Support Files/MJExtension/MJExtension.debug.xcconfig new file mode 100644 index 0000000..7f94d90 --- /dev/null +++ b/Pods/Target Support Files/MJExtension/MJExtension.debug.xcconfig @@ -0,0 +1,12 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/MJExtension +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_DEVELOPMENT_LANGUAGE = ${DEVELOPMENT_LANGUAGE} +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/MJExtension +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Pods/Target Support Files/MJExtension/MJExtension.modulemap b/Pods/Target Support Files/MJExtension/MJExtension.modulemap new file mode 100644 index 0000000..921670b --- /dev/null +++ b/Pods/Target Support Files/MJExtension/MJExtension.modulemap @@ -0,0 +1,6 @@ +framework module MJExtension { + umbrella header "MJExtension-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/MJExtension/MJExtension.release.xcconfig b/Pods/Target Support Files/MJExtension/MJExtension.release.xcconfig new file mode 100644 index 0000000..7f94d90 --- /dev/null +++ b/Pods/Target Support Files/MJExtension/MJExtension.release.xcconfig @@ -0,0 +1,12 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/MJExtension +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_DEVELOPMENT_LANGUAGE = ${DEVELOPMENT_LANGUAGE} +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/MJExtension +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Pods/Target Support Files/MJExtension/ResourceBundle-MJExtension-MJExtension-Info.plist b/Pods/Target Support Files/MJExtension/ResourceBundle-MJExtension-MJExtension-Info.plist new file mode 100644 index 0000000..649dffa --- /dev/null +++ b/Pods/Target Support Files/MJExtension/ResourceBundle-MJExtension-MJExtension-Info.plist @@ -0,0 +1,24 @@ + + + + + CFBundleDevelopmentRegion + ${PODS_DEVELOPMENT_LANGUAGE} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + BNDL + CFBundleShortVersionString + 3.4.2 + CFBundleSignature + ???? + CFBundleVersion + 1 + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/MJRefresh/MJRefresh-Info.plist b/Pods/Target Support Files/MJRefresh/MJRefresh-Info.plist new file mode 100644 index 0000000..1b9a556 --- /dev/null +++ b/Pods/Target Support Files/MJRefresh/MJRefresh-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + ${PODS_DEVELOPMENT_LANGUAGE} + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 3.7.9 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/MJRefresh/MJRefresh-dummy.m b/Pods/Target Support Files/MJRefresh/MJRefresh-dummy.m new file mode 100644 index 0000000..d43259d --- /dev/null +++ b/Pods/Target Support Files/MJRefresh/MJRefresh-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_MJRefresh : NSObject +@end +@implementation PodsDummy_MJRefresh +@end diff --git a/Pods/Target Support Files/MJRefresh/MJRefresh-prefix.pch b/Pods/Target Support Files/MJRefresh/MJRefresh-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/Pods/Target Support Files/MJRefresh/MJRefresh-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Pods/Target Support Files/MJRefresh/MJRefresh-umbrella.h b/Pods/Target Support Files/MJRefresh/MJRefresh-umbrella.h new file mode 100644 index 0000000..7168200 --- /dev/null +++ b/Pods/Target Support Files/MJRefresh/MJRefresh-umbrella.h @@ -0,0 +1,41 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "MJRefreshAutoFooter.h" +#import "MJRefreshBackFooter.h" +#import "MJRefreshComponent.h" +#import "MJRefreshFooter.h" +#import "MJRefreshHeader.h" +#import "MJRefreshTrailer.h" +#import "MJRefreshAutoGifFooter.h" +#import "MJRefreshAutoNormalFooter.h" +#import "MJRefreshAutoStateFooter.h" +#import "MJRefreshBackGifFooter.h" +#import "MJRefreshBackNormalFooter.h" +#import "MJRefreshBackStateFooter.h" +#import "MJRefreshGifHeader.h" +#import "MJRefreshNormalHeader.h" +#import "MJRefreshStateHeader.h" +#import "MJRefreshNormalTrailer.h" +#import "MJRefreshStateTrailer.h" +#import "MJRefresh.h" +#import "MJRefreshConfig.h" +#import "MJRefreshConst.h" +#import "NSBundle+MJRefresh.h" +#import "UICollectionViewLayout+MJRefresh.h" +#import "UIScrollView+MJExtension.h" +#import "UIScrollView+MJRefresh.h" +#import "UIView+MJExtension.h" + +FOUNDATION_EXPORT double MJRefreshVersionNumber; +FOUNDATION_EXPORT const unsigned char MJRefreshVersionString[]; + diff --git a/Pods/Target Support Files/MJRefresh/MJRefresh.debug.xcconfig b/Pods/Target Support Files/MJRefresh/MJRefresh.debug.xcconfig new file mode 100644 index 0000000..68622eb --- /dev/null +++ b/Pods/Target Support Files/MJRefresh/MJRefresh.debug.xcconfig @@ -0,0 +1,12 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/MJRefresh +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_DEVELOPMENT_LANGUAGE = ${DEVELOPMENT_LANGUAGE} +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/MJRefresh +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Pods/Target Support Files/MJRefresh/MJRefresh.modulemap b/Pods/Target Support Files/MJRefresh/MJRefresh.modulemap new file mode 100644 index 0000000..ec3d85e --- /dev/null +++ b/Pods/Target Support Files/MJRefresh/MJRefresh.modulemap @@ -0,0 +1,6 @@ +framework module MJRefresh { + umbrella header "MJRefresh-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/MJRefresh/MJRefresh.release.xcconfig b/Pods/Target Support Files/MJRefresh/MJRefresh.release.xcconfig new file mode 100644 index 0000000..68622eb --- /dev/null +++ b/Pods/Target Support Files/MJRefresh/MJRefresh.release.xcconfig @@ -0,0 +1,12 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/MJRefresh +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_DEVELOPMENT_LANGUAGE = ${DEVELOPMENT_LANGUAGE} +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/MJRefresh +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Pods/Target Support Files/MJRefresh/ResourceBundle-MJRefresh.Privacy-MJRefresh-Info.plist b/Pods/Target Support Files/MJRefresh/ResourceBundle-MJRefresh.Privacy-MJRefresh-Info.plist new file mode 100644 index 0000000..84806d0 --- /dev/null +++ b/Pods/Target Support Files/MJRefresh/ResourceBundle-MJRefresh.Privacy-MJRefresh-Info.plist @@ -0,0 +1,24 @@ + + + + + CFBundleDevelopmentRegion + ${PODS_DEVELOPMENT_LANGUAGE} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + BNDL + CFBundleShortVersionString + 3.7.9 + CFBundleSignature + ???? + CFBundleVersion + 1 + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/Masonry/Masonry-Info.plist b/Pods/Target Support Files/Masonry/Masonry-Info.plist new file mode 100644 index 0000000..dc59427 --- /dev/null +++ b/Pods/Target Support Files/Masonry/Masonry-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + ${PODS_DEVELOPMENT_LANGUAGE} + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.1.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/Masonry/Masonry-dummy.m b/Pods/Target Support Files/Masonry/Masonry-dummy.m new file mode 100644 index 0000000..04001b1 --- /dev/null +++ b/Pods/Target Support Files/Masonry/Masonry-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Masonry : NSObject +@end +@implementation PodsDummy_Masonry +@end diff --git a/Pods/Target Support Files/Masonry/Masonry-prefix.pch b/Pods/Target Support Files/Masonry/Masonry-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/Pods/Target Support Files/Masonry/Masonry-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Pods/Target Support Files/Masonry/Masonry-umbrella.h b/Pods/Target Support Files/Masonry/Masonry-umbrella.h new file mode 100644 index 0000000..3fe9c4c --- /dev/null +++ b/Pods/Target Support Files/Masonry/Masonry-umbrella.h @@ -0,0 +1,31 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "MASCompositeConstraint.h" +#import "MASConstraint+Private.h" +#import "MASConstraint.h" +#import "MASConstraintMaker.h" +#import "MASLayoutConstraint.h" +#import "Masonry.h" +#import "MASUtilities.h" +#import "MASViewAttribute.h" +#import "MASViewConstraint.h" +#import "NSArray+MASAdditions.h" +#import "NSArray+MASShorthandAdditions.h" +#import "NSLayoutConstraint+MASDebugAdditions.h" +#import "View+MASAdditions.h" +#import "View+MASShorthandAdditions.h" +#import "ViewController+MASAdditions.h" + +FOUNDATION_EXPORT double MasonryVersionNumber; +FOUNDATION_EXPORT const unsigned char MasonryVersionString[]; + diff --git a/Pods/Target Support Files/Masonry/Masonry.debug.xcconfig b/Pods/Target Support Files/Masonry/Masonry.debug.xcconfig new file mode 100644 index 0000000..233437f --- /dev/null +++ b/Pods/Target Support Files/Masonry/Masonry.debug.xcconfig @@ -0,0 +1,13 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Masonry +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +OTHER_LDFLAGS = $(inherited) -framework "Foundation" -framework "UIKit" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_DEVELOPMENT_LANGUAGE = ${DEVELOPMENT_LANGUAGE} +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/Masonry +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Pods/Target Support Files/Masonry/Masonry.modulemap b/Pods/Target Support Files/Masonry/Masonry.modulemap new file mode 100644 index 0000000..06ec492 --- /dev/null +++ b/Pods/Target Support Files/Masonry/Masonry.modulemap @@ -0,0 +1,6 @@ +framework module Masonry { + umbrella header "Masonry-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/Masonry/Masonry.release.xcconfig b/Pods/Target Support Files/Masonry/Masonry.release.xcconfig new file mode 100644 index 0000000..233437f --- /dev/null +++ b/Pods/Target Support Files/Masonry/Masonry.release.xcconfig @@ -0,0 +1,13 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Masonry +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +OTHER_LDFLAGS = $(inherited) -framework "Foundation" -framework "UIKit" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_DEVELOPMENT_LANGUAGE = ${DEVELOPMENT_LANGUAGE} +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/Masonry +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Pods/Target Support Files/Pods-CustomKeyboard/Pods-CustomKeyboard-Info.plist b/Pods/Target Support Files/Pods-CustomKeyboard/Pods-CustomKeyboard-Info.plist new file mode 100644 index 0000000..19cf209 --- /dev/null +++ b/Pods/Target Support Files/Pods-CustomKeyboard/Pods-CustomKeyboard-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + ${PODS_DEVELOPMENT_LANGUAGE} + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/Pods-CustomKeyboard/Pods-CustomKeyboard-acknowledgements.markdown b/Pods/Target Support Files/Pods-CustomKeyboard/Pods-CustomKeyboard-acknowledgements.markdown new file mode 100644 index 0000000..102af75 --- /dev/null +++ b/Pods/Target Support Files/Pods-CustomKeyboard/Pods-CustomKeyboard-acknowledgements.markdown @@ -0,0 +1,3 @@ +# Acknowledgements +This application makes use of the following third party libraries: +Generated by CocoaPods - https://cocoapods.org diff --git a/Pods/Target Support Files/Pods-CustomKeyboard/Pods-CustomKeyboard-acknowledgements.plist b/Pods/Target Support Files/Pods-CustomKeyboard/Pods-CustomKeyboard-acknowledgements.plist new file mode 100644 index 0000000..7acbad1 --- /dev/null +++ b/Pods/Target Support Files/Pods-CustomKeyboard/Pods-CustomKeyboard-acknowledgements.plist @@ -0,0 +1,29 @@ + + + + + PreferenceSpecifiers + + + FooterText + This application makes use of the following third party libraries: + Title + Acknowledgements + Type + PSGroupSpecifier + + + FooterText + Generated by CocoaPods - https://cocoapods.org + Title + + Type + PSGroupSpecifier + + + StringsTable + Acknowledgements + Title + Acknowledgements + + diff --git a/Pods/Target Support Files/Pods-CustomKeyboard/Pods-CustomKeyboard-dummy.m b/Pods/Target Support Files/Pods-CustomKeyboard/Pods-CustomKeyboard-dummy.m new file mode 100644 index 0000000..0a87d54 --- /dev/null +++ b/Pods/Target Support Files/Pods-CustomKeyboard/Pods-CustomKeyboard-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods_CustomKeyboard : NSObject +@end +@implementation PodsDummy_Pods_CustomKeyboard +@end diff --git a/Pods/Target Support Files/Pods-CustomKeyboard/Pods-CustomKeyboard-umbrella.h b/Pods/Target Support Files/Pods-CustomKeyboard/Pods-CustomKeyboard-umbrella.h new file mode 100644 index 0000000..6a3b6f0 --- /dev/null +++ b/Pods/Target Support Files/Pods-CustomKeyboard/Pods-CustomKeyboard-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double Pods_CustomKeyboardVersionNumber; +FOUNDATION_EXPORT const unsigned char Pods_CustomKeyboardVersionString[]; + diff --git a/Pods/Target Support Files/Pods-CustomKeyboard/Pods-CustomKeyboard.debug.xcconfig b/Pods/Target Support Files/Pods-CustomKeyboard/Pods-CustomKeyboard.debug.xcconfig new file mode 100644 index 0000000..26f2c77 --- /dev/null +++ b/Pods/Target Support Files/Pods-CustomKeyboard/Pods-CustomKeyboard.debug.xcconfig @@ -0,0 +1,8 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Pods/Target Support Files/Pods-CustomKeyboard/Pods-CustomKeyboard.modulemap b/Pods/Target Support Files/Pods-CustomKeyboard/Pods-CustomKeyboard.modulemap new file mode 100644 index 0000000..f35382d --- /dev/null +++ b/Pods/Target Support Files/Pods-CustomKeyboard/Pods-CustomKeyboard.modulemap @@ -0,0 +1,6 @@ +framework module Pods_CustomKeyboard { + umbrella header "Pods-CustomKeyboard-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/Pods-CustomKeyboard/Pods-CustomKeyboard.release.xcconfig b/Pods/Target Support Files/Pods-CustomKeyboard/Pods-CustomKeyboard.release.xcconfig new file mode 100644 index 0000000..26f2c77 --- /dev/null +++ b/Pods/Target Support Files/Pods-CustomKeyboard/Pods-CustomKeyboard.release.xcconfig @@ -0,0 +1,8 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Pods/Target Support Files/Pods-keyBoard/Pods-keyBoard-Info.plist b/Pods/Target Support Files/Pods-keyBoard/Pods-keyBoard-Info.plist new file mode 100644 index 0000000..19cf209 --- /dev/null +++ b/Pods/Target Support Files/Pods-keyBoard/Pods-keyBoard-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + ${PODS_DEVELOPMENT_LANGUAGE} + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/Pods-keyBoard/Pods-keyBoard-acknowledgements.markdown b/Pods/Target Support Files/Pods-keyBoard/Pods-keyBoard-acknowledgements.markdown new file mode 100644 index 0000000..7de4a89 --- /dev/null +++ b/Pods/Target Support Files/Pods-keyBoard/Pods-keyBoard-acknowledgements.markdown @@ -0,0 +1,123 @@ +# Acknowledgements +This application makes use of the following third party libraries: + +## AFNetworking + +Copyright (c) 2011-2020 Alamofire Software Foundation (http://alamofire.org/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +## Bugly + +Copyright (C) 2017 Tencent Bugly, Inc. All rights reserved. + + +## MJExtension + +Copyright (c) 2013-2019 MJExtension (https://github.com/CoderMJLee/MJExtension) + +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. + + +## MJRefresh + +Copyright (c) 2013-2015 MJRefresh (https://github.com/CoderMJLee/MJRefresh) + +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. + + +## Masonry + +Copyright (c) 2011-2012 Masonry Team - https://github.com/Masonry + +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. + +## SDWebImage + +Copyright (c) 2009-2020 Olivier Poitrey rs@dailymotion.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. + + +Generated by CocoaPods - https://cocoapods.org diff --git a/Pods/Target Support Files/Pods-keyBoard/Pods-keyBoard-acknowledgements.plist b/Pods/Target Support Files/Pods-keyBoard/Pods-keyBoard-acknowledgements.plist new file mode 100644 index 0000000..fd6aa88 --- /dev/null +++ b/Pods/Target Support Files/Pods-keyBoard/Pods-keyBoard-acknowledgements.plist @@ -0,0 +1,185 @@ + + + + + PreferenceSpecifiers + + + FooterText + This application makes use of the following third party libraries: + Title + Acknowledgements + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2011-2020 Alamofire Software Foundation (http://alamofire.org/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + License + MIT + Title + AFNetworking + Type + PSGroupSpecifier + + + FooterText + Copyright (C) 2017 Tencent Bugly, Inc. All rights reserved. + + License + Copyright + Title + Bugly + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2013-2019 MJExtension (https://github.com/CoderMJLee/MJExtension) + +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. + + License + MIT + Title + MJExtension + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2013-2015 MJRefresh (https://github.com/CoderMJLee/MJRefresh) + +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. + + License + MIT + Title + MJRefresh + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2011-2012 Masonry Team - https://github.com/Masonry + +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. + License + MIT + Title + Masonry + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2009-2020 Olivier Poitrey rs@dailymotion.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. + + + License + MIT + Title + SDWebImage + Type + PSGroupSpecifier + + + FooterText + Generated by CocoaPods - https://cocoapods.org + Title + + Type + PSGroupSpecifier + + + StringsTable + Acknowledgements + Title + Acknowledgements + + diff --git a/Pods/Target Support Files/Pods-keyBoard/Pods-keyBoard-dummy.m b/Pods/Target Support Files/Pods-keyBoard/Pods-keyBoard-dummy.m new file mode 100644 index 0000000..ed7e07f --- /dev/null +++ b/Pods/Target Support Files/Pods-keyBoard/Pods-keyBoard-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods_keyBoard : NSObject +@end +@implementation PodsDummy_Pods_keyBoard +@end diff --git a/Pods/Target Support Files/Pods-keyBoard/Pods-keyBoard-frameworks-Debug-input-files.xcfilelist b/Pods/Target Support Files/Pods-keyBoard/Pods-keyBoard-frameworks-Debug-input-files.xcfilelist new file mode 100644 index 0000000..06b5aa0 --- /dev/null +++ b/Pods/Target Support Files/Pods-keyBoard/Pods-keyBoard-frameworks-Debug-input-files.xcfilelist @@ -0,0 +1,6 @@ +${PODS_ROOT}/Target Support Files/Pods-keyBoard/Pods-keyBoard-frameworks.sh +${BUILT_PRODUCTS_DIR}/AFNetworking/AFNetworking.framework +${BUILT_PRODUCTS_DIR}/MJExtension/MJExtension.framework +${BUILT_PRODUCTS_DIR}/MJRefresh/MJRefresh.framework +${BUILT_PRODUCTS_DIR}/Masonry/Masonry.framework +${BUILT_PRODUCTS_DIR}/SDWebImage/SDWebImage.framework \ No newline at end of file diff --git a/Pods/Target Support Files/Pods-keyBoard/Pods-keyBoard-frameworks-Debug-output-files.xcfilelist b/Pods/Target Support Files/Pods-keyBoard/Pods-keyBoard-frameworks-Debug-output-files.xcfilelist new file mode 100644 index 0000000..66a1534 --- /dev/null +++ b/Pods/Target Support Files/Pods-keyBoard/Pods-keyBoard-frameworks-Debug-output-files.xcfilelist @@ -0,0 +1,5 @@ +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/AFNetworking.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/MJExtension.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/MJRefresh.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Masonry.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SDWebImage.framework \ No newline at end of file diff --git a/Pods/Target Support Files/Pods-keyBoard/Pods-keyBoard-frameworks-Release-input-files.xcfilelist b/Pods/Target Support Files/Pods-keyBoard/Pods-keyBoard-frameworks-Release-input-files.xcfilelist new file mode 100644 index 0000000..06b5aa0 --- /dev/null +++ b/Pods/Target Support Files/Pods-keyBoard/Pods-keyBoard-frameworks-Release-input-files.xcfilelist @@ -0,0 +1,6 @@ +${PODS_ROOT}/Target Support Files/Pods-keyBoard/Pods-keyBoard-frameworks.sh +${BUILT_PRODUCTS_DIR}/AFNetworking/AFNetworking.framework +${BUILT_PRODUCTS_DIR}/MJExtension/MJExtension.framework +${BUILT_PRODUCTS_DIR}/MJRefresh/MJRefresh.framework +${BUILT_PRODUCTS_DIR}/Masonry/Masonry.framework +${BUILT_PRODUCTS_DIR}/SDWebImage/SDWebImage.framework \ No newline at end of file diff --git a/Pods/Target Support Files/Pods-keyBoard/Pods-keyBoard-frameworks-Release-output-files.xcfilelist b/Pods/Target Support Files/Pods-keyBoard/Pods-keyBoard-frameworks-Release-output-files.xcfilelist new file mode 100644 index 0000000..66a1534 --- /dev/null +++ b/Pods/Target Support Files/Pods-keyBoard/Pods-keyBoard-frameworks-Release-output-files.xcfilelist @@ -0,0 +1,5 @@ +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/AFNetworking.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/MJExtension.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/MJRefresh.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Masonry.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SDWebImage.framework \ No newline at end of file diff --git a/Pods/Target Support Files/Pods-keyBoard/Pods-keyBoard-frameworks.sh b/Pods/Target Support Files/Pods-keyBoard/Pods-keyBoard-frameworks.sh new file mode 100755 index 0000000..b731e30 --- /dev/null +++ b/Pods/Target Support Files/Pods-keyBoard/Pods-keyBoard-frameworks.sh @@ -0,0 +1,194 @@ +#!/bin/sh +set -e +set -u +set -o pipefail + +function on_error { + echo "$(realpath -mq "${0}"):$1: error: Unexpected failure" +} +trap 'on_error $LINENO' ERR + +if [ -z ${FRAMEWORKS_FOLDER_PATH+x} ]; then + # If FRAMEWORKS_FOLDER_PATH is not set, then there's nowhere for us to copy + # frameworks to, so exit 0 (signalling the script phase was successful). + exit 0 +fi + +echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" +mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + +COCOAPODS_PARALLEL_CODE_SIGN="${COCOAPODS_PARALLEL_CODE_SIGN:-false}" +SWIFT_STDLIB_PATH="${TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" +BCSYMBOLMAP_DIR="BCSymbolMaps" + + +# This protects against multiple targets copying the same framework dependency at the same time. The solution +# was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html +RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") + +# Copies and strips a vendored framework +install_framework() +{ + if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then + local source="${BUILT_PRODUCTS_DIR}/$1" + elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then + local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" + elif [ -r "$1" ]; then + local source="$1" + fi + + local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + + if [ -L "${source}" ]; then + echo "Symlinked..." + source="$(readlink -f "${source}")" + fi + + if [ -d "${source}/${BCSYMBOLMAP_DIR}" ]; then + # Locate and install any .bcsymbolmaps if present, and remove them from the .framework before the framework is copied + find "${source}/${BCSYMBOLMAP_DIR}" -name "*.bcsymbolmap"|while read f; do + echo "Installing $f" + install_bcsymbolmap "$f" "$destination" + rm "$f" + done + rmdir "${source}/${BCSYMBOLMAP_DIR}" + fi + + # Use filter instead of exclude so missing patterns don't throw errors. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" + + local basename + basename="$(basename -s .framework "$1")" + binary="${destination}/${basename}.framework/${basename}" + + if ! [ -r "$binary" ]; then + binary="${destination}/${basename}" + elif [ -L "${binary}" ]; then + echo "Destination binary is symlinked..." + dirname="$(dirname "${binary}")" + binary="${dirname}/$(readlink "${binary}")" + fi + + # Strip invalid architectures so "fat" simulator / device frameworks work on device + if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then + strip_invalid_archs "$binary" + fi + + # Resign the code if required by the build settings to avoid unstable apps + code_sign_if_enabled "${destination}/$(basename "$1")" + + # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. + if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then + local swift_runtime_libs + swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u) + for lib in $swift_runtime_libs; do + echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" + rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" + code_sign_if_enabled "${destination}/${lib}" + done + fi +} +# Copies and strips a vendored dSYM +install_dsym() { + local source="$1" + warn_missing_arch=${2:-true} + if [ -r "$source" ]; then + # Copy the dSYM into the targets temp dir. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DERIVED_FILES_DIR}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DERIVED_FILES_DIR}" + + local basename + basename="$(basename -s .dSYM "$source")" + binary_name="$(ls "$source/Contents/Resources/DWARF")" + binary="${DERIVED_FILES_DIR}/${basename}.dSYM/Contents/Resources/DWARF/${binary_name}" + + # Strip invalid architectures from the dSYM. + if [[ "$(file "$binary")" == *"Mach-O "*"dSYM companion"* ]]; then + strip_invalid_archs "$binary" "$warn_missing_arch" + fi + if [[ $STRIP_BINARY_RETVAL == 0 ]]; then + # Move the stripped file into its final destination. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.dSYM" "${DWARF_DSYM_FOLDER_PATH}" + else + # The dSYM was not stripped at all, in this case touch a fake folder so the input/output paths from Xcode do not reexecute this script because the file is missing. + mkdir -p "${DWARF_DSYM_FOLDER_PATH}" + touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.dSYM" + fi + fi +} + +# Used as a return value for each invocation of `strip_invalid_archs` function. +STRIP_BINARY_RETVAL=0 + +# Strip invalid architectures +strip_invalid_archs() { + binary="$1" + warn_missing_arch=${2:-true} + # Get architectures for current target binary + binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)" + # Intersect them with the architectures we are building for + intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)" + # If there are no archs supported by this binary then warn the user + if [[ -z "$intersected_archs" ]]; then + if [[ "$warn_missing_arch" == "true" ]]; then + echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)." + fi + STRIP_BINARY_RETVAL=1 + return + fi + stripped="" + for arch in $binary_archs; do + if ! [[ "${ARCHS}" == *"$arch"* ]]; then + # Strip non-valid architectures in-place + lipo -remove "$arch" -output "$binary" "$binary" + stripped="$stripped $arch" + fi + done + if [[ "$stripped" ]]; then + echo "Stripped $binary of architectures:$stripped" + fi + STRIP_BINARY_RETVAL=0 +} + +# Copies the bcsymbolmap files of a vendored framework +install_bcsymbolmap() { + local bcsymbolmap_path="$1" + local destination="${BUILT_PRODUCTS_DIR}" + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}" +} + +# Signs a framework with the provided identity +code_sign_if_enabled() { + if [ -n "${EXPANDED_CODE_SIGN_IDENTITY:-}" -a "${CODE_SIGNING_REQUIRED:-}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then + # Use the current code_sign_identity + echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" + local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS:-} --preserve-metadata=identifier,entitlements '$1'" + + if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then + code_sign_cmd="$code_sign_cmd &" + fi + echo "$code_sign_cmd" + eval "$code_sign_cmd" + fi +} + +if [[ "$CONFIGURATION" == "Debug" ]]; then + install_framework "${BUILT_PRODUCTS_DIR}/AFNetworking/AFNetworking.framework" + install_framework "${BUILT_PRODUCTS_DIR}/MJExtension/MJExtension.framework" + install_framework "${BUILT_PRODUCTS_DIR}/MJRefresh/MJRefresh.framework" + install_framework "${BUILT_PRODUCTS_DIR}/Masonry/Masonry.framework" + install_framework "${BUILT_PRODUCTS_DIR}/SDWebImage/SDWebImage.framework" +fi +if [[ "$CONFIGURATION" == "Release" ]]; then + install_framework "${BUILT_PRODUCTS_DIR}/AFNetworking/AFNetworking.framework" + install_framework "${BUILT_PRODUCTS_DIR}/MJExtension/MJExtension.framework" + install_framework "${BUILT_PRODUCTS_DIR}/MJRefresh/MJRefresh.framework" + install_framework "${BUILT_PRODUCTS_DIR}/Masonry/Masonry.framework" + install_framework "${BUILT_PRODUCTS_DIR}/SDWebImage/SDWebImage.framework" +fi +if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then + wait +fi diff --git a/Pods/Target Support Files/Pods-keyBoard/Pods-keyBoard-umbrella.h b/Pods/Target Support Files/Pods-keyBoard/Pods-keyBoard-umbrella.h new file mode 100644 index 0000000..3c72a0b --- /dev/null +++ b/Pods/Target Support Files/Pods-keyBoard/Pods-keyBoard-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double Pods_keyBoardVersionNumber; +FOUNDATION_EXPORT const unsigned char Pods_keyBoardVersionString[]; + diff --git a/Pods/Target Support Files/Pods-keyBoard/Pods-keyBoard.debug.xcconfig b/Pods/Target Support Files/Pods-keyBoard/Pods-keyBoard.debug.xcconfig new file mode 100644 index 0000000..2e2ca3c --- /dev/null +++ b/Pods/Target Support Files/Pods-keyBoard/Pods-keyBoard.debug.xcconfig @@ -0,0 +1,13 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/AFNetworking" "${PODS_CONFIGURATION_BUILD_DIR}/MJExtension" "${PODS_CONFIGURATION_BUILD_DIR}/MJRefresh" "${PODS_CONFIGURATION_BUILD_DIR}/Masonry" "${PODS_CONFIGURATION_BUILD_DIR}/SDWebImage" "${PODS_ROOT}/Bugly" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/AFNetworking/AFNetworking.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/MJExtension/MJExtension.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/MJRefresh/MJRefresh.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Masonry/Masonry.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/SDWebImage/SDWebImage.framework/Headers" +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +OTHER_LDFLAGS = $(inherited) -ObjC -l"c++" -l"z" -framework "AFNetworking" -framework "Bugly" -framework "Foundation" -framework "ImageIO" -framework "MJExtension" -framework "MJRefresh" -framework "Masonry" -framework "SDWebImage" -framework "Security" -framework "SystemConfiguration" -framework "UIKit" +OTHER_MODULE_VERIFIER_FLAGS = $(inherited) "-F${PODS_CONFIGURATION_BUILD_DIR}/AFNetworking" "-F${PODS_CONFIGURATION_BUILD_DIR}/Bugly" "-F${PODS_CONFIGURATION_BUILD_DIR}/MJExtension" "-F${PODS_CONFIGURATION_BUILD_DIR}/MJRefresh" "-F${PODS_CONFIGURATION_BUILD_DIR}/Masonry" "-F${PODS_CONFIGURATION_BUILD_DIR}/SDWebImage" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Pods/Target Support Files/Pods-keyBoard/Pods-keyBoard.modulemap b/Pods/Target Support Files/Pods-keyBoard/Pods-keyBoard.modulemap new file mode 100644 index 0000000..9af1393 --- /dev/null +++ b/Pods/Target Support Files/Pods-keyBoard/Pods-keyBoard.modulemap @@ -0,0 +1,6 @@ +framework module Pods_keyBoard { + umbrella header "Pods-keyBoard-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/Pods-keyBoard/Pods-keyBoard.release.xcconfig b/Pods/Target Support Files/Pods-keyBoard/Pods-keyBoard.release.xcconfig new file mode 100644 index 0000000..2e2ca3c --- /dev/null +++ b/Pods/Target Support Files/Pods-keyBoard/Pods-keyBoard.release.xcconfig @@ -0,0 +1,13 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/AFNetworking" "${PODS_CONFIGURATION_BUILD_DIR}/MJExtension" "${PODS_CONFIGURATION_BUILD_DIR}/MJRefresh" "${PODS_CONFIGURATION_BUILD_DIR}/Masonry" "${PODS_CONFIGURATION_BUILD_DIR}/SDWebImage" "${PODS_ROOT}/Bugly" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/AFNetworking/AFNetworking.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/MJExtension/MJExtension.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/MJRefresh/MJRefresh.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Masonry/Masonry.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/SDWebImage/SDWebImage.framework/Headers" +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +OTHER_LDFLAGS = $(inherited) -ObjC -l"c++" -l"z" -framework "AFNetworking" -framework "Bugly" -framework "Foundation" -framework "ImageIO" -framework "MJExtension" -framework "MJRefresh" -framework "Masonry" -framework "SDWebImage" -framework "Security" -framework "SystemConfiguration" -framework "UIKit" +OTHER_MODULE_VERIFIER_FLAGS = $(inherited) "-F${PODS_CONFIGURATION_BUILD_DIR}/AFNetworking" "-F${PODS_CONFIGURATION_BUILD_DIR}/Bugly" "-F${PODS_CONFIGURATION_BUILD_DIR}/MJExtension" "-F${PODS_CONFIGURATION_BUILD_DIR}/MJRefresh" "-F${PODS_CONFIGURATION_BUILD_DIR}/Masonry" "-F${PODS_CONFIGURATION_BUILD_DIR}/SDWebImage" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Pods/Target Support Files/SDWebImage/ResourceBundle-SDWebImage-SDWebImage-Info.plist b/Pods/Target Support Files/SDWebImage/ResourceBundle-SDWebImage-SDWebImage-Info.plist new file mode 100644 index 0000000..1cdf1dd --- /dev/null +++ b/Pods/Target Support Files/SDWebImage/ResourceBundle-SDWebImage-SDWebImage-Info.plist @@ -0,0 +1,24 @@ + + + + + CFBundleDevelopmentRegion + ${PODS_DEVELOPMENT_LANGUAGE} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + BNDL + CFBundleShortVersionString + 5.21.1 + CFBundleSignature + ???? + CFBundleVersion + 1 + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/SDWebImage/SDWebImage-Info.plist b/Pods/Target Support Files/SDWebImage/SDWebImage-Info.plist new file mode 100644 index 0000000..c853b7b --- /dev/null +++ b/Pods/Target Support Files/SDWebImage/SDWebImage-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + ${PODS_DEVELOPMENT_LANGUAGE} + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 5.21.1 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/SDWebImage/SDWebImage-dummy.m b/Pods/Target Support Files/SDWebImage/SDWebImage-dummy.m new file mode 100644 index 0000000..86d2b5f --- /dev/null +++ b/Pods/Target Support Files/SDWebImage/SDWebImage-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_SDWebImage : NSObject +@end +@implementation PodsDummy_SDWebImage +@end diff --git a/Pods/Target Support Files/SDWebImage/SDWebImage-prefix.pch b/Pods/Target Support Files/SDWebImage/SDWebImage-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/Pods/Target Support Files/SDWebImage/SDWebImage-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Pods/Target Support Files/SDWebImage/SDWebImage-umbrella.h b/Pods/Target Support Files/SDWebImage/SDWebImage-umbrella.h new file mode 100644 index 0000000..29eecfd --- /dev/null +++ b/Pods/Target Support Files/SDWebImage/SDWebImage-umbrella.h @@ -0,0 +1,77 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "NSButton+WebCache.h" +#import "NSData+ImageContentType.h" +#import "NSImage+Compatibility.h" +#import "SDAnimatedImage.h" +#import "SDAnimatedImagePlayer.h" +#import "SDAnimatedImageRep.h" +#import "SDAnimatedImageView+WebCache.h" +#import "SDAnimatedImageView.h" +#import "SDCallbackQueue.h" +#import "SDDiskCache.h" +#import "SDGraphicsImageRenderer.h" +#import "SDImageAPNGCoder.h" +#import "SDImageAWebPCoder.h" +#import "SDImageCache.h" +#import "SDImageCacheConfig.h" +#import "SDImageCacheDefine.h" +#import "SDImageCachesManager.h" +#import "SDImageCoder.h" +#import "SDImageCoderHelper.h" +#import "SDImageCodersManager.h" +#import "SDImageFrame.h" +#import "SDImageGIFCoder.h" +#import "SDImageGraphics.h" +#import "SDImageHEICCoder.h" +#import "SDImageIOAnimatedCoder.h" +#import "SDImageIOCoder.h" +#import "SDImageLoader.h" +#import "SDImageLoadersManager.h" +#import "SDImageTransformer.h" +#import "SDMemoryCache.h" +#import "SDWebImageCacheKeyFilter.h" +#import "SDWebImageCacheSerializer.h" +#import "SDWebImageCompat.h" +#import "SDWebImageDefine.h" +#import "SDWebImageDownloader.h" +#import "SDWebImageDownloaderConfig.h" +#import "SDWebImageDownloaderDecryptor.h" +#import "SDWebImageDownloaderOperation.h" +#import "SDWebImageDownloaderRequestModifier.h" +#import "SDWebImageDownloaderResponseModifier.h" +#import "SDWebImageError.h" +#import "SDWebImageIndicator.h" +#import "SDWebImageManager.h" +#import "SDWebImageOperation.h" +#import "SDWebImageOptionsProcessor.h" +#import "SDWebImagePrefetcher.h" +#import "SDWebImageTransition.h" +#import "UIButton+WebCache.h" +#import "UIImage+ExtendedCacheData.h" +#import "UIImage+ForceDecode.h" +#import "UIImage+GIF.h" +#import "UIImage+MemoryCacheCost.h" +#import "UIImage+Metadata.h" +#import "UIImage+MultiFormat.h" +#import "UIImage+Transform.h" +#import "UIImageView+HighlightedWebCache.h" +#import "UIImageView+WebCache.h" +#import "UIView+WebCache.h" +#import "UIView+WebCacheOperation.h" +#import "UIView+WebCacheState.h" +#import "SDWebImage.h" + +FOUNDATION_EXPORT double SDWebImageVersionNumber; +FOUNDATION_EXPORT const unsigned char SDWebImageVersionString[]; + diff --git a/Pods/Target Support Files/SDWebImage/SDWebImage.debug.xcconfig b/Pods/Target Support Files/SDWebImage/SDWebImage.debug.xcconfig new file mode 100644 index 0000000..aefe779 --- /dev/null +++ b/Pods/Target Support Files/SDWebImage/SDWebImage.debug.xcconfig @@ -0,0 +1,15 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/SDWebImage +DERIVE_MACCATALYST_PRODUCT_BUNDLE_IDENTIFIER = NO +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +OTHER_LDFLAGS = $(inherited) -framework "ImageIO" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_DEVELOPMENT_LANGUAGE = ${DEVELOPMENT_LANGUAGE} +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/SDWebImage +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +SUPPORTS_MACCATALYST = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Pods/Target Support Files/SDWebImage/SDWebImage.modulemap b/Pods/Target Support Files/SDWebImage/SDWebImage.modulemap new file mode 100644 index 0000000..91545be --- /dev/null +++ b/Pods/Target Support Files/SDWebImage/SDWebImage.modulemap @@ -0,0 +1,6 @@ +framework module SDWebImage { + umbrella header "SDWebImage-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/SDWebImage/SDWebImage.release.xcconfig b/Pods/Target Support Files/SDWebImage/SDWebImage.release.xcconfig new file mode 100644 index 0000000..aefe779 --- /dev/null +++ b/Pods/Target Support Files/SDWebImage/SDWebImage.release.xcconfig @@ -0,0 +1,15 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/SDWebImage +DERIVE_MACCATALYST_PRODUCT_BUNDLE_IDENTIFIER = NO +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +OTHER_LDFLAGS = $(inherited) -framework "ImageIO" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_DEVELOPMENT_LANGUAGE = ${DEVELOPMENT_LANGUAGE} +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/SDWebImage +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +SUPPORTS_MACCATALYST = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/keyBoard.xcodeproj/project.pbxproj b/keyBoard.xcodeproj/project.pbxproj index 6e6eccc..1f59212 100644 --- a/keyBoard.xcodeproj/project.pbxproj +++ b/keyBoard.xcodeproj/project.pbxproj @@ -17,6 +17,20 @@ 04C6EACE2EAF87020089C901 /* CustomKeyboard.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = 04C6EAC62EAF87020089C901 /* CustomKeyboard.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; 04C6EAD82EAF870B0089C901 /* KeyboardViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 04C6EAD62EAF870B0089C901 /* KeyboardViewController.m */; }; 04C6EADD2EAF8CEB0089C901 /* KBToolBar.m in Sources */ = {isa = PBXBuildFile; fileRef = 04C6EADC2EAF8CEB0089C901 /* KBToolBar.m */; }; + 04FC95582EAFAF51007BD342 /* MASConstraintMaker.m in Sources */ = {isa = PBXBuildFile; fileRef = 04FC954B2EAFAF51007BD342 /* MASConstraintMaker.m */; }; + 04FC95592EAFAF51007BD342 /* MASViewConstraint.m in Sources */ = {isa = PBXBuildFile; fileRef = 04FC95532EAFAF51007BD342 /* MASViewConstraint.m */; }; + 04FC955A2EAFAF51007BD342 /* MASViewAttribute.m in Sources */ = {isa = PBXBuildFile; fileRef = 04FC95542EAFAF51007BD342 /* MASViewAttribute.m */; }; + 04FC955B2EAFAF51007BD342 /* NSArray+MASAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = 04FC954D2EAFAF51007BD342 /* NSArray+MASAdditions.m */; }; + 04FC955C2EAFAF51007BD342 /* View+MASAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = 04FC954E2EAFAF51007BD342 /* View+MASAdditions.m */; }; + 04FC955D2EAFAF51007BD342 /* MASCompositeConstraint.m in Sources */ = {isa = PBXBuildFile; fileRef = 04FC954A2EAFAF51007BD342 /* MASCompositeConstraint.m */; }; + 04FC955E2EAFAF51007BD342 /* MASConstraint.m in Sources */ = {isa = PBXBuildFile; fileRef = 04FC95512EAFAF51007BD342 /* MASConstraint.m */; }; + 04FC955F2EAFAF51007BD342 /* NSLayoutConstraint+MASDebugAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = 04FC953D2EAFAF51007BD342 /* NSLayoutConstraint+MASDebugAdditions.m */; }; + 04FC95602EAFAF51007BD342 /* MASLayoutConstraint.m in Sources */ = {isa = PBXBuildFile; fileRef = 04FC954C2EAFAF51007BD342 /* MASLayoutConstraint.m */; }; + 04FC95612EAFAF51007BD342 /* ViewController+MASAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = 04FC95462EAFAF51007BD342 /* ViewController+MASAdditions.m */; }; + 04FC95622EAFAF51007BD342 /* LICENSE in Resources */ = {isa = PBXBuildFile; fileRef = 04FC953B2EAFAF51007BD342 /* LICENSE */; }; + 04FC95632EAFAF51007BD342 /* README.md in Resources */ = {isa = PBXBuildFile; fileRef = 04FC95562EAFAF51007BD342 /* README.md */; }; + 7A36414DFDA5BEC9B7D2E318 /* Pods_CustomKeyboard.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2C1092FB2B452F95B15D4263 /* Pods_CustomKeyboard.framework */; }; + ECC9EE02174D86E8D792472F /* Pods_keyBoard.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 967065BB5230E43F293B3AF9 /* Pods_keyBoard.framework */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -62,7 +76,41 @@ 04C6EADE2EAF8D680089C901 /* PrefixHeader.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = PrefixHeader.pch; sourceTree = ""; }; 04C6EAE02EAF940F0089C901 /* KBPermissionViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = KBPermissionViewController.h; sourceTree = ""; }; 04C6EAE12EAF940F0089C901 /* KBPermissionViewController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = KBPermissionViewController.m; sourceTree = ""; }; + 04FC953A2EAFAE56007BD342 /* KeyBoardPrefixHeader.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = KeyBoardPrefixHeader.pch; sourceTree = ""; }; + 04FC953B2EAFAF51007BD342 /* LICENSE */ = {isa = PBXFileReference; lastKnownFileType = text; path = LICENSE; sourceTree = ""; }; + 04FC953C2EAFAF51007BD342 /* MASCompositeConstraint.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MASCompositeConstraint.h; sourceTree = ""; }; + 04FC953D2EAFAF51007BD342 /* NSLayoutConstraint+MASDebugAdditions.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = "NSLayoutConstraint+MASDebugAdditions.m"; sourceTree = ""; }; + 04FC953E2EAFAF51007BD342 /* MASConstraint+Private.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "MASConstraint+Private.h"; sourceTree = ""; }; + 04FC953F2EAFAF51007BD342 /* MASLayoutConstraint.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MASLayoutConstraint.h; sourceTree = ""; }; + 04FC95402EAFAF51007BD342 /* NSArray+MASShorthandAdditions.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "NSArray+MASShorthandAdditions.h"; sourceTree = ""; }; + 04FC95412EAFAF51007BD342 /* MASConstraintMaker.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MASConstraintMaker.h; sourceTree = ""; }; + 04FC95422EAFAF51007BD342 /* View+MASAdditions.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "View+MASAdditions.h"; sourceTree = ""; }; + 04FC95432EAFAF51007BD342 /* NSArray+MASAdditions.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "NSArray+MASAdditions.h"; sourceTree = ""; }; + 04FC95442EAFAF51007BD342 /* MASUtilities.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MASUtilities.h; sourceTree = ""; }; + 04FC95452EAFAF51007BD342 /* MASViewAttribute.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MASViewAttribute.h; sourceTree = ""; }; + 04FC95462EAFAF51007BD342 /* ViewController+MASAdditions.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = "ViewController+MASAdditions.m"; sourceTree = ""; }; + 04FC95472EAFAF51007BD342 /* MASViewConstraint.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MASViewConstraint.h; sourceTree = ""; }; + 04FC95482EAFAF51007BD342 /* MASConstraint.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MASConstraint.h; sourceTree = ""; }; + 04FC95492EAFAF51007BD342 /* NSLayoutConstraint+MASDebugAdditions.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "NSLayoutConstraint+MASDebugAdditions.h"; sourceTree = ""; }; + 04FC954A2EAFAF51007BD342 /* MASCompositeConstraint.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MASCompositeConstraint.m; sourceTree = ""; }; + 04FC954B2EAFAF51007BD342 /* MASConstraintMaker.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MASConstraintMaker.m; sourceTree = ""; }; + 04FC954C2EAFAF51007BD342 /* MASLayoutConstraint.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MASLayoutConstraint.m; sourceTree = ""; }; + 04FC954D2EAFAF51007BD342 /* NSArray+MASAdditions.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = "NSArray+MASAdditions.m"; sourceTree = ""; }; + 04FC954E2EAFAF51007BD342 /* View+MASAdditions.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = "View+MASAdditions.m"; sourceTree = ""; }; + 04FC954F2EAFAF51007BD342 /* View+MASShorthandAdditions.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "View+MASShorthandAdditions.h"; sourceTree = ""; }; + 04FC95502EAFAF51007BD342 /* Masonry.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = Masonry.h; sourceTree = ""; }; + 04FC95512EAFAF51007BD342 /* MASConstraint.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MASConstraint.m; sourceTree = ""; }; + 04FC95522EAFAF51007BD342 /* ViewController+MASAdditions.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "ViewController+MASAdditions.h"; sourceTree = ""; }; + 04FC95532EAFAF51007BD342 /* MASViewConstraint.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MASViewConstraint.m; sourceTree = ""; }; + 04FC95542EAFAF51007BD342 /* MASViewAttribute.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MASViewAttribute.m; sourceTree = ""; }; + 04FC95562EAFAF51007BD342 /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; + 2C1092FB2B452F95B15D4263 /* Pods_CustomKeyboard.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_CustomKeyboard.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 51FE7C4C42C2255B3C1C4128 /* Pods-keyBoard.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-keyBoard.release.xcconfig"; path = "Target Support Files/Pods-keyBoard/Pods-keyBoard.release.xcconfig"; sourceTree = ""; }; 727EC7532EAF848B00B36487 /* keyBoard.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = keyBoard.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 967065BB5230E43F293B3AF9 /* Pods_keyBoard.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_keyBoard.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + B12EC429812407B9F0E67565 /* Pods-CustomKeyboard.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-CustomKeyboard.release.xcconfig"; path = "Target Support Files/Pods-CustomKeyboard/Pods-CustomKeyboard.release.xcconfig"; sourceTree = ""; }; + B8CA018AB878499327504AAD /* Pods-CustomKeyboard.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-CustomKeyboard.debug.xcconfig"; path = "Target Support Files/Pods-CustomKeyboard/Pods-CustomKeyboard.debug.xcconfig"; sourceTree = ""; }; + F67DDBD716E4E616D8CC2C9C /* Pods-keyBoard.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-keyBoard.debug.xcconfig"; path = "Target Support Files/Pods-keyBoard/Pods-keyBoard.debug.xcconfig"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -70,6 +118,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 7A36414DFDA5BEC9B7D2E318 /* Pods_CustomKeyboard.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -77,6 +126,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + ECC9EE02174D86E8D792472F /* Pods_keyBoard.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -96,6 +146,7 @@ 04C6EAB42EAF86530089C901 /* Main.storyboard */, 04C6EAB72EAF86530089C901 /* ViewController.h */, 04C6EAB82EAF86530089C901 /* ViewController.m */, + 04FC953A2EAFAE56007BD342 /* KeyBoardPrefixHeader.pch */, ); path = keyBoard; sourceTree = ""; @@ -107,6 +158,7 @@ 04C6EAD42EAF870B0089C901 /* Info.plist */, 04C6EAD52EAF870B0089C901 /* KeyboardViewController.h */, 04C6EAD62EAF870B0089C901 /* KeyboardViewController.m */, + 04FC95572EAFAF51007BD342 /* Masonry */, 04C6EADE2EAF8D680089C901 /* PrefixHeader.pch */, ); path = CustomKeyboard; @@ -130,12 +182,76 @@ path = VC; sourceTree = ""; }; + 04FC95552EAFAF51007BD342 /* Masonry */ = { + isa = PBXGroup; + children = ( + 04FC953C2EAFAF51007BD342 /* MASCompositeConstraint.h */, + 04FC953D2EAFAF51007BD342 /* NSLayoutConstraint+MASDebugAdditions.m */, + 04FC953E2EAFAF51007BD342 /* MASConstraint+Private.h */, + 04FC953F2EAFAF51007BD342 /* MASLayoutConstraint.h */, + 04FC95402EAFAF51007BD342 /* NSArray+MASShorthandAdditions.h */, + 04FC95412EAFAF51007BD342 /* MASConstraintMaker.h */, + 04FC95422EAFAF51007BD342 /* View+MASAdditions.h */, + 04FC95432EAFAF51007BD342 /* NSArray+MASAdditions.h */, + 04FC95442EAFAF51007BD342 /* MASUtilities.h */, + 04FC95452EAFAF51007BD342 /* MASViewAttribute.h */, + 04FC95462EAFAF51007BD342 /* ViewController+MASAdditions.m */, + 04FC95472EAFAF51007BD342 /* MASViewConstraint.h */, + 04FC95482EAFAF51007BD342 /* MASConstraint.h */, + 04FC95492EAFAF51007BD342 /* NSLayoutConstraint+MASDebugAdditions.h */, + 04FC954A2EAFAF51007BD342 /* MASCompositeConstraint.m */, + 04FC954B2EAFAF51007BD342 /* MASConstraintMaker.m */, + 04FC954C2EAFAF51007BD342 /* MASLayoutConstraint.m */, + 04FC954D2EAFAF51007BD342 /* NSArray+MASAdditions.m */, + 04FC954E2EAFAF51007BD342 /* View+MASAdditions.m */, + 04FC954F2EAFAF51007BD342 /* View+MASShorthandAdditions.h */, + 04FC95502EAFAF51007BD342 /* Masonry.h */, + 04FC95512EAFAF51007BD342 /* MASConstraint.m */, + 04FC95522EAFAF51007BD342 /* ViewController+MASAdditions.h */, + 04FC95532EAFAF51007BD342 /* MASViewConstraint.m */, + 04FC95542EAFAF51007BD342 /* MASViewAttribute.m */, + ); + path = Masonry; + sourceTree = ""; + }; + 04FC95572EAFAF51007BD342 /* Masonry */ = { + isa = PBXGroup; + children = ( + 04FC953B2EAFAF51007BD342 /* LICENSE */, + 04FC95552EAFAF51007BD342 /* Masonry */, + 04FC95562EAFAF51007BD342 /* README.md */, + ); + path = Masonry; + sourceTree = ""; + }; + 2C53A0856097DCFBE7B55649 /* Pods */ = { + isa = PBXGroup; + children = ( + B8CA018AB878499327504AAD /* Pods-CustomKeyboard.debug.xcconfig */, + B12EC429812407B9F0E67565 /* Pods-CustomKeyboard.release.xcconfig */, + F67DDBD716E4E616D8CC2C9C /* Pods-keyBoard.debug.xcconfig */, + 51FE7C4C42C2255B3C1C4128 /* Pods-keyBoard.release.xcconfig */, + ); + path = Pods; + sourceTree = ""; + }; + 6E26572F95DCFDA6A6644133 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 2C1092FB2B452F95B15D4263 /* Pods_CustomKeyboard.framework */, + 967065BB5230E43F293B3AF9 /* Pods_keyBoard.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; 727EC74A2EAF848B00B36487 = { isa = PBXGroup; children = ( 04C6EAB92EAF86530089C901 /* keyBoard */, 04C6EAD72EAF870B0089C901 /* CustomKeyboard */, 727EC7542EAF848B00B36487 /* Products */, + 2C53A0856097DCFBE7B55649 /* Pods */, + 6E26572F95DCFDA6A6644133 /* Frameworks */, ); sourceTree = ""; }; @@ -155,6 +271,7 @@ isa = PBXNativeTarget; buildConfigurationList = 04C6EAD02EAF87020089C901 /* Build configuration list for PBXNativeTarget "CustomKeyboard" */; buildPhases = ( + 0BE37DFD7038DA85EFB69DAC /* [CP] Check Pods Manifest.lock */, 04C6EAC22EAF87020089C901 /* Sources */, 04C6EAC32EAF87020089C901 /* Frameworks */, 04C6EAC42EAF87020089C901 /* Resources */, @@ -164,8 +281,6 @@ dependencies = ( ); name = CustomKeyboard; - packageProductDependencies = ( - ); productName = CustomKeyboard; productReference = 04C6EAC62EAF87020089C901 /* CustomKeyboard.appex */; productType = "com.apple.product-type.app-extension"; @@ -174,10 +289,12 @@ isa = PBXNativeTarget; buildConfigurationList = 727EC76B2EAF848C00B36487 /* Build configuration list for PBXNativeTarget "keyBoard" */; buildPhases = ( + 83BB87118E085DDFDE4FDC7F /* [CP] Check Pods Manifest.lock */, 727EC74F2EAF848B00B36487 /* Sources */, 727EC7502EAF848B00B36487 /* Frameworks */, 727EC7512EAF848B00B36487 /* Resources */, 04C6EAD32EAF87020089C901 /* Embed Foundation Extensions */, + 6463F367119C0796ECC157BE /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); @@ -185,8 +302,6 @@ 04C6EACD2EAF87020089C901 /* PBXTargetDependency */, ); name = keyBoard; - packageProductDependencies = ( - ); productName = keyBoard; productReference = 727EC7532EAF848B00B36487 /* keyBoard.app */; productType = "com.apple.product-type.application"; @@ -234,6 +349,8 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( + 04FC95622EAFAF51007BD342 /* LICENSE in Resources */, + 04FC95632EAFAF51007BD342 /* README.md in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -249,6 +366,74 @@ }; /* End PBXResourcesBuildPhase section */ +/* Begin PBXShellScriptBuildPhase section */ + 0BE37DFD7038DA85EFB69DAC /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-CustomKeyboard-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + 6463F367119C0796ECC157BE /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-keyBoard/Pods-keyBoard-frameworks-${CONFIGURATION}-input-files.xcfilelist", + ); + inputPaths = ( + ); + name = "[CP] Embed Pods Frameworks"; + outputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-keyBoard/Pods-keyBoard-frameworks-${CONFIGURATION}-output-files.xcfilelist", + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-keyBoard/Pods-keyBoard-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + 83BB87118E085DDFDE4FDC7F /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-keyBoard-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + /* Begin PBXSourcesBuildPhase section */ 04C6EAC22EAF87020089C901 /* Sources */ = { isa = PBXSourcesBuildPhase; @@ -256,6 +441,16 @@ files = ( 04C6EADD2EAF8CEB0089C901 /* KBToolBar.m in Sources */, 04C6EAD82EAF870B0089C901 /* KeyboardViewController.m in Sources */, + 04FC95582EAFAF51007BD342 /* MASConstraintMaker.m in Sources */, + 04FC95592EAFAF51007BD342 /* MASViewConstraint.m in Sources */, + 04FC955A2EAFAF51007BD342 /* MASViewAttribute.m in Sources */, + 04FC955B2EAFAF51007BD342 /* NSArray+MASAdditions.m in Sources */, + 04FC955C2EAFAF51007BD342 /* View+MASAdditions.m in Sources */, + 04FC955D2EAFAF51007BD342 /* MASCompositeConstraint.m in Sources */, + 04FC955E2EAFAF51007BD342 /* MASConstraint.m in Sources */, + 04FC955F2EAFAF51007BD342 /* NSLayoutConstraint+MASDebugAdditions.m in Sources */, + 04FC95602EAFAF51007BD342 /* MASLayoutConstraint.m in Sources */, + 04FC95612EAFAF51007BD342 /* ViewController+MASAdditions.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -302,10 +497,12 @@ /* Begin XCBuildConfiguration section */ 04C6EAD12EAF87020089C901 /* Debug */ = { isa = XCBuildConfiguration; + baseConfigurationReference = B8CA018AB878499327504AAD /* Pods-CustomKeyboard.debug.xcconfig */; buildSettings = { CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; DEVELOPMENT_TEAM = TN6HHV45BB; + ENABLE_USER_SCRIPT_SANDBOXING = NO; GCC_PREFIX_HEADER = CustomKeyboard/PrefixHeader.pch; GENERATE_INFOPLIST_FILE = YES; INFOPLIST_FILE = CustomKeyboard/Info.plist; @@ -328,10 +525,12 @@ }; 04C6EAD22EAF87020089C901 /* Release */ = { isa = XCBuildConfiguration; + baseConfigurationReference = B12EC429812407B9F0E67565 /* Pods-CustomKeyboard.release.xcconfig */; buildSettings = { CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; DEVELOPMENT_TEAM = TN6HHV45BB; + ENABLE_USER_SCRIPT_SANDBOXING = NO; GCC_PREFIX_HEADER = CustomKeyboard/PrefixHeader.pch; GENERATE_INFOPLIST_FILE = YES; INFOPLIST_FILE = CustomKeyboard/Info.plist; @@ -354,12 +553,14 @@ }; 727EC76C2EAF848C00B36487 /* Debug */ = { isa = XCBuildConfiguration; + baseConfigurationReference = F67DDBD716E4E616D8CC2C9C /* Pods-keyBoard.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; DEVELOPMENT_TEAM = TN6HHV45BB; + GCC_PREFIX_HEADER = keyBoard/KeyBoardPrefixHeader.pch; GENERATE_INFOPLIST_FILE = YES; INFOPLIST_FILE = keyBoard/Info.plist; INFOPLIST_KEY_CFBundleDisplayName = "我的输入法"; @@ -384,12 +585,14 @@ }; 727EC76D2EAF848C00B36487 /* Release */ = { isa = XCBuildConfiguration; + baseConfigurationReference = 51FE7C4C42C2255B3C1C4128 /* Pods-keyBoard.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; DEVELOPMENT_TEAM = TN6HHV45BB; + GCC_PREFIX_HEADER = keyBoard/KeyBoardPrefixHeader.pch; GENERATE_INFOPLIST_FILE = YES; INFOPLIST_FILE = keyBoard/Info.plist; INFOPLIST_KEY_CFBundleDisplayName = "我的输入法"; @@ -450,7 +653,7 @@ DEVELOPMENT_TEAM = CBD35U2N52; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; - ENABLE_USER_SCRIPT_SANDBOXING = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; GCC_C_LANGUAGE_STANDARD = gnu17; GCC_DYNAMIC_NO_PIC = NO; GCC_NO_COMMON_BLOCKS = YES; @@ -512,7 +715,7 @@ DEVELOPMENT_TEAM = CBD35U2N52; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_USER_SCRIPT_SANDBOXING = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; GCC_C_LANGUAGE_STANDARD = gnu17; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; diff --git a/keyBoard.xcodeproj/xcshareddata/xcschemes/CustomKeyboard.xcscheme b/keyBoard.xcodeproj/xcshareddata/xcschemes/CustomKeyboard.xcscheme new file mode 100644 index 0000000..802d93f --- /dev/null +++ b/keyBoard.xcodeproj/xcshareddata/xcschemes/CustomKeyboard.xcscheme @@ -0,0 +1,97 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/keyBoard.xcodeproj/xcshareddata/xcschemes/keyBoard.xcscheme b/keyBoard.xcodeproj/xcshareddata/xcschemes/keyBoard.xcscheme new file mode 100644 index 0000000..4b87720 --- /dev/null +++ b/keyBoard.xcodeproj/xcshareddata/xcschemes/keyBoard.xcscheme @@ -0,0 +1,90 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/keyBoard.xcworkspace/contents.xcworkspacedata b/keyBoard.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..f47d31f --- /dev/null +++ b/keyBoard.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/keyBoard/AppDelegate.m b/keyBoard/AppDelegate.m index 13d92e0..08e0a65 100644 --- a/keyBoard/AppDelegate.m +++ b/keyBoard/AppDelegate.m @@ -8,7 +8,8 @@ #import "AppDelegate.h" #import "ViewController.h" #import "KBPermissionViewController.h" - +#import +#import static NSString * const kKBKeyboardExtensionBundleId = @"com.keyBoard.CustomKeyboard"; static BOOL KBIsKeyboardEnabled(void) { for (UITextInputMode *mode in [UITextInputMode activeInputModes]) { @@ -37,24 +38,15 @@ static BOOL KBIsKeyboardEnabled(void) { [self.window makeKeyAndVisible]; ViewController *vc = [[ViewController alloc] init]; self.window.rootViewController = vc; - -// [[NSNotificationCenter defaultCenter] addObserver:self -// selector:@selector(applicationDidBecomeActiveNotification:) -// name:UIApplicationDidBecomeActiveNotification -// object:nil]; - + /// 获取网络权限 + [self getNetJudge]; + [Bugly startWithAppId:BuglyId]; + /// 判断获取键盘权限 dispatch_async(dispatch_get_main_queue(), ^{ [self kb_presentPermissionIfNeeded]; }); return YES; } -// -//#pragma mark - Active notifications -// -//- (void)applicationDidBecomeActiveNotification:(NSNotification *)note -//{ -// [self kb_presentPermissionIfNeeded]; -//} #pragma mark - Permission presentation @@ -87,4 +79,20 @@ static BOOL KBIsKeyboardEnabled(void) { } } + + +-(void)getNetJudge { + AFNetworkReachabilityManager *netManager = [AFNetworkReachabilityManager sharedManager]; + [netManager startMonitoring]; + [netManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status){ + if (status == AFNetworkReachabilityStatusReachableViaWiFi){ +// [PublicObj saveNetReachability:@"wifi"]; + }else if (status == AFNetworkReachabilityStatusReachableViaWWAN){ +// [PublicObj saveNetReachability:@"wwan"]; + }else{ +// [PublicObj saveNetReachability:@"unknown"]; + } + }]; +} + @end diff --git a/keyBoard/KeyBoardPrefixHeader.pch b/keyBoard/KeyBoardPrefixHeader.pch new file mode 100644 index 0000000..0842fc8 --- /dev/null +++ b/keyBoard/KeyBoardPrefixHeader.pch @@ -0,0 +1,21 @@ +// +// KeyBoardPrefixHeader.pch +// keyBoard +// +// Created by Mac on 2025/10/27. +// + +#ifndef KeyBoardPrefixHeader_pch +#define KeyBoardPrefixHeader_pch + + +//Bugly +#define BuglyId @"5736ce7a19" + + +/// 三方 +#import + + + +#endif /* KeyBoardPrefixHeader_pch */ diff --git a/keyBoard/ViewController.m b/keyBoard/ViewController.m index 46187c3..d974212 100644 --- a/keyBoard/ViewController.m +++ b/keyBoard/ViewController.m @@ -6,7 +6,6 @@ // #import "ViewController.h" - @interface ViewController () @property (nonatomic, strong) UITextView *textView; @end