├── .gitignore ├── LICENSE ├── Podfile ├── Podfile.lock ├── Pods ├── AFNetworking │ ├── AFNetworking │ │ ├── AFCompatibilityMacros.h │ │ ├── AFHTTPSessionManager.h │ │ ├── AFHTTPSessionManager.m │ │ ├── AFNetworkReachabilityManager.h │ │ ├── AFNetworkReachabilityManager.m │ │ ├── AFNetworking.h │ │ ├── AFSecurityPolicy.h │ │ ├── AFSecurityPolicy.m │ │ ├── AFURLRequestSerialization.h │ │ ├── AFURLRequestSerialization.m │ │ ├── AFURLResponseSerialization.h │ │ ├── AFURLResponseSerialization.m │ │ ├── AFURLSessionManager.h │ │ └── AFURLSessionManager.m │ ├── LICENSE │ ├── README.md │ └── UIKit+AFNetworking │ │ ├── AFAutoPurgingImageCache.h │ │ ├── AFAutoPurgingImageCache.m │ │ ├── AFImageDownloader.h │ │ ├── AFImageDownloader.m │ │ ├── AFNetworkActivityIndicatorManager.h │ │ ├── AFNetworkActivityIndicatorManager.m │ │ ├── UIActivityIndicatorView+AFNetworking.h │ │ ├── UIActivityIndicatorView+AFNetworking.m │ │ ├── UIButton+AFNetworking.h │ │ ├── UIButton+AFNetworking.m │ │ ├── UIImage+AFNetworking.h │ │ ├── UIImageView+AFNetworking.h │ │ ├── UIImageView+AFNetworking.m │ │ ├── UIKit+AFNetworking.h │ │ ├── UIProgressView+AFNetworking.h │ │ ├── UIProgressView+AFNetworking.m │ │ ├── UIRefreshControl+AFNetworking.h │ │ ├── UIRefreshControl+AFNetworking.m │ │ ├── UIWebView+AFNetworking.h │ │ └── UIWebView+AFNetworking.m ├── Headers │ ├── Private │ │ ├── AFNetworking │ │ │ ├── AFAutoPurgingImageCache.h │ │ │ ├── AFCompatibilityMacros.h │ │ │ ├── AFHTTPSessionManager.h │ │ │ ├── AFImageDownloader.h │ │ │ ├── AFNetworkActivityIndicatorManager.h │ │ │ ├── AFNetworkReachabilityManager.h │ │ │ ├── AFNetworking.h │ │ │ ├── AFSecurityPolicy.h │ │ │ ├── AFURLRequestSerialization.h │ │ │ ├── AFURLResponseSerialization.h │ │ │ ├── AFURLSessionManager.h │ │ │ ├── UIActivityIndicatorView+AFNetworking.h │ │ │ ├── UIButton+AFNetworking.h │ │ │ ├── UIImage+AFNetworking.h │ │ │ ├── UIImageView+AFNetworking.h │ │ │ ├── UIKit+AFNetworking.h │ │ │ ├── UIProgressView+AFNetworking.h │ │ │ ├── UIRefreshControl+AFNetworking.h │ │ │ └── UIWebView+AFNetworking.h │ │ └── YYCache │ │ │ ├── YYCache.h │ │ │ ├── YYDiskCache.h │ │ │ ├── YYKVStorage.h │ │ │ └── YYMemoryCache.h │ └── Public │ │ ├── AFNetworking │ │ ├── AFAutoPurgingImageCache.h │ │ ├── AFCompatibilityMacros.h │ │ ├── AFHTTPSessionManager.h │ │ ├── AFImageDownloader.h │ │ ├── AFNetworkActivityIndicatorManager.h │ │ ├── AFNetworkReachabilityManager.h │ │ ├── AFNetworking.h │ │ ├── AFSecurityPolicy.h │ │ ├── AFURLRequestSerialization.h │ │ ├── AFURLResponseSerialization.h │ │ ├── AFURLSessionManager.h │ │ ├── UIActivityIndicatorView+AFNetworking.h │ │ ├── UIButton+AFNetworking.h │ │ ├── UIImage+AFNetworking.h │ │ ├── UIImageView+AFNetworking.h │ │ ├── UIKit+AFNetworking.h │ │ ├── UIProgressView+AFNetworking.h │ │ ├── UIRefreshControl+AFNetworking.h │ │ └── UIWebView+AFNetworking.h │ │ └── YYCache │ │ ├── YYCache.h │ │ ├── YYDiskCache.h │ │ ├── YYKVStorage.h │ │ └── YYMemoryCache.h ├── Manifest.lock ├── Pods.xcodeproj │ └── project.pbxproj ├── Target Support Files │ ├── AFNetworking │ │ ├── AFNetworking-dummy.m │ │ ├── AFNetworking-prefix.pch │ │ └── AFNetworking.xcconfig │ ├── Pods-YBNetworkDemo │ │ ├── Pods-YBNetworkDemo-acknowledgements.markdown │ │ ├── Pods-YBNetworkDemo-acknowledgements.plist │ │ ├── Pods-YBNetworkDemo-dummy.m │ │ ├── Pods-YBNetworkDemo-frameworks.sh │ │ ├── Pods-YBNetworkDemo-resources.sh │ │ ├── Pods-YBNetworkDemo.debug.xcconfig │ │ └── Pods-YBNetworkDemo.release.xcconfig │ └── YYCache │ │ ├── YYCache-dummy.m │ │ ├── YYCache-prefix.pch │ │ └── YYCache.xcconfig └── YYCache │ ├── LICENSE │ ├── README.md │ └── YYCache │ ├── YYCache.h │ ├── YYCache.m │ ├── YYDiskCache.h │ ├── YYDiskCache.m │ ├── YYKVStorage.h │ ├── YYKVStorage.m │ ├── YYMemoryCache.h │ └── YYMemoryCache.m ├── README.md ├── YBNetwork.podspec ├── YBNetwork ├── Cache │ ├── YBNetworkCache+Internal.h │ ├── YBNetworkCache.h │ └── YBNetworkCache.m ├── Manger │ ├── YBBaseRequest+Internal.h │ ├── YBNetworkManager.h │ └── YBNetworkManager.m ├── Response │ ├── YBNetworkResponse.h │ └── YBNetworkResponse.m ├── YBBaseRequest.h ├── YBBaseRequest.m └── YBNetworkDefine.h ├── YBNetworkDemo.xcodeproj ├── project.pbxproj └── project.xcworkspace │ ├── contents.xcworkspacedata │ └── xcshareddata │ └── IDEWorkspaceChecks.plist ├── YBNetworkDemo.xcworkspace ├── contents.xcworkspacedata └── xcshareddata │ └── IDEWorkspaceChecks.plist └── YBNetworkDemo ├── AppDelegate.h ├── AppDelegate.m ├── Assets.xcassets ├── AppIcon.appiconset │ └── Contents.json └── Contents.json ├── Base.lproj ├── LaunchScreen.storyboard └── Main.storyboard ├── Info.plist ├── TestCase ├── APITeams │ ├── DefaultServerRequest.h │ ├── DefaultServerRequest.m │ ├── OtherServerRequest.h │ └── OtherServerRequest.m ├── TestViewController.h ├── TestViewController.m └── 为响应对象拓展属性 │ ├── YBNetworkResponse+YBCustom.h │ └── YBNetworkResponse+YBCustom.m ├── ViewController.h ├── ViewController.m └── main.m /.gitignore: -------------------------------------------------------------------------------- 1 | # Xcode 2 | # 3 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore 4 | 5 | ## Build generated 6 | build/ 7 | DerivedData/ 8 | 9 | ## Various settings 10 | *.pbxuser 11 | !default.pbxuser 12 | *.mode1v3 13 | !default.mode1v3 14 | *.mode2v3 15 | !default.mode2v3 16 | *.perspectivev3 17 | !default.perspectivev3 18 | xcuserdata/ 19 | 20 | ## Other 21 | *.moved-aside 22 | *.xccheckout 23 | *.xcscmblueprint 24 | 25 | ## Obj-C/Swift specific 26 | *.hmap 27 | *.ipa 28 | *.dSYM.zip 29 | *.dSYM 30 | 31 | # CocoaPods 32 | # 33 | # We recommend against adding the Pods directory to your .gitignore. However 34 | # you should judge for yourself, the pros and cons are mentioned at: 35 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control 36 | # 37 | # Pods/ 38 | 39 | # Carthage 40 | # 41 | # Add this line if you want to avoid checking in source code from Carthage dependencies. 42 | # Carthage/Checkouts 43 | 44 | Carthage/Build 45 | 46 | # fastlane 47 | # 48 | # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the 49 | # screenshots whenever they are needed. 50 | # For more information about the recommended setup visit: 51 | # https://docs.fastlane.tools/best-practices/source-control/#source-control 52 | 53 | fastlane/report.xml 54 | fastlane/Preview.html 55 | fastlane/screenshots/**/*.png 56 | fastlane/test_output 57 | 58 | # Code Injection 59 | # 60 | # After new code Injection tools there's a generated folder /iOSInjectionProject 61 | # https://github.com/johnno1962/injectionforxcode 62 | 63 | iOSInjectionProject/ 64 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 杨波 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Podfile: -------------------------------------------------------------------------------- 1 | platform:ios, '8.0' 2 | target 'YBNetworkDemo' do 3 | 4 | pod 'AFNetworking', '~> 3.2.1' 5 | pod 'YYCache', '~> 1.0.4' 6 | 7 | end 8 | -------------------------------------------------------------------------------- /Podfile.lock: -------------------------------------------------------------------------------- 1 | PODS: 2 | - AFNetworking (3.2.1): 3 | - AFNetworking/NSURLSession (= 3.2.1) 4 | - AFNetworking/Reachability (= 3.2.1) 5 | - AFNetworking/Security (= 3.2.1) 6 | - AFNetworking/Serialization (= 3.2.1) 7 | - AFNetworking/UIKit (= 3.2.1) 8 | - AFNetworking/NSURLSession (3.2.1): 9 | - AFNetworking/Reachability 10 | - AFNetworking/Security 11 | - AFNetworking/Serialization 12 | - AFNetworking/Reachability (3.2.1) 13 | - AFNetworking/Security (3.2.1) 14 | - AFNetworking/Serialization (3.2.1) 15 | - AFNetworking/UIKit (3.2.1): 16 | - AFNetworking/NSURLSession 17 | - YYCache (1.0.4) 18 | 19 | DEPENDENCIES: 20 | - AFNetworking (~> 3.2.1) 21 | - YYCache (~> 1.0.4) 22 | 23 | SPEC REPOS: 24 | https://github.com/cocoapods/specs.git: 25 | - AFNetworking 26 | - YYCache 27 | 28 | SPEC CHECKSUMS: 29 | AFNetworking: b6f891fdfaed196b46c7a83cf209e09697b94057 30 | YYCache: 8105b6638f5e849296c71f331ff83891a4942952 31 | 32 | PODFILE CHECKSUM: cf44b36011f0dc3371dc54820b015cffc9c73bce 33 | 34 | COCOAPODS: 1.5.3 35 | -------------------------------------------------------------------------------- /Pods/AFNetworking/AFNetworking/AFCompatibilityMacros.h: -------------------------------------------------------------------------------- 1 | // AFCompatibilityMacros.h 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #ifndef AFCompatibilityMacros_h 23 | #define AFCompatibilityMacros_h 24 | 25 | #ifdef API_UNAVAILABLE 26 | #define AF_API_UNAVAILABLE(x) API_UNAVAILABLE(x) 27 | #else 28 | #define AF_API_UNAVAILABLE(x) 29 | #endif // API_UNAVAILABLE 30 | 31 | #if __has_warning("-Wunguarded-availability-new") 32 | #define AF_CAN_USE_AT_AVAILABLE 1 33 | #else 34 | #define AF_CAN_USE_AT_AVAILABLE 0 35 | #endif 36 | 37 | #endif /* AFCompatibilityMacros_h */ 38 | -------------------------------------------------------------------------------- /Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.h: -------------------------------------------------------------------------------- 1 | // AFNetworkReachabilityManager.h 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | 24 | #if !TARGET_OS_WATCH 25 | #import 26 | 27 | typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) { 28 | AFNetworkReachabilityStatusUnknown = -1, 29 | AFNetworkReachabilityStatusNotReachable = 0, 30 | AFNetworkReachabilityStatusReachableViaWWAN = 1, 31 | AFNetworkReachabilityStatusReachableViaWiFi = 2, 32 | }; 33 | 34 | NS_ASSUME_NONNULL_BEGIN 35 | 36 | /** 37 | `AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces. 38 | 39 | 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. 40 | 41 | See Apple's Reachability Sample Code ( https://developer.apple.com/library/ios/samplecode/reachability/ ) 42 | 43 | @warning Instances of `AFNetworkReachabilityManager` must be started with `-startMonitoring` before reachability status can be determined. 44 | */ 45 | @interface AFNetworkReachabilityManager : NSObject 46 | 47 | /** 48 | The current network reachability status. 49 | */ 50 | @property (readonly, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus; 51 | 52 | /** 53 | Whether or not the network is currently reachable. 54 | */ 55 | @property (readonly, nonatomic, assign, getter = isReachable) BOOL reachable; 56 | 57 | /** 58 | Whether or not the network is currently reachable via WWAN. 59 | */ 60 | @property (readonly, nonatomic, assign, getter = isReachableViaWWAN) BOOL reachableViaWWAN; 61 | 62 | /** 63 | Whether or not the network is currently reachable via WiFi. 64 | */ 65 | @property (readonly, nonatomic, assign, getter = isReachableViaWiFi) BOOL reachableViaWiFi; 66 | 67 | ///--------------------- 68 | /// @name Initialization 69 | ///--------------------- 70 | 71 | /** 72 | Returns the shared network reachability manager. 73 | */ 74 | + (instancetype)sharedManager; 75 | 76 | /** 77 | Creates and returns a network reachability manager with the default socket address. 78 | 79 | @return An initialized network reachability manager, actively monitoring the default socket address. 80 | */ 81 | + (instancetype)manager; 82 | 83 | /** 84 | Creates and returns a network reachability manager for the specified domain. 85 | 86 | @param domain The domain used to evaluate network reachability. 87 | 88 | @return An initialized network reachability manager, actively monitoring the specified domain. 89 | */ 90 | + (instancetype)managerForDomain:(NSString *)domain; 91 | 92 | /** 93 | Creates and returns a network reachability manager for the socket address. 94 | 95 | @param address The socket address (`sockaddr_in6`) used to evaluate network reachability. 96 | 97 | @return An initialized network reachability manager, actively monitoring the specified socket address. 98 | */ 99 | + (instancetype)managerForAddress:(const void *)address; 100 | 101 | /** 102 | Initializes an instance of a network reachability manager from the specified reachability object. 103 | 104 | @param reachability The reachability object to monitor. 105 | 106 | @return An initialized network reachability manager, actively monitoring the specified reachability. 107 | */ 108 | - (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability NS_DESIGNATED_INITIALIZER; 109 | 110 | /** 111 | * Unavailable initializer 112 | */ 113 | + (instancetype)new NS_UNAVAILABLE; 114 | 115 | /** 116 | * Unavailable initializer 117 | */ 118 | - (instancetype)init NS_UNAVAILABLE; 119 | 120 | ///-------------------------------------------------- 121 | /// @name Starting & Stopping Reachability Monitoring 122 | ///-------------------------------------------------- 123 | 124 | /** 125 | Starts monitoring for changes in network reachability status. 126 | */ 127 | - (void)startMonitoring; 128 | 129 | /** 130 | Stops monitoring for changes in network reachability status. 131 | */ 132 | - (void)stopMonitoring; 133 | 134 | ///------------------------------------------------- 135 | /// @name Getting Localized Reachability Description 136 | ///------------------------------------------------- 137 | 138 | /** 139 | Returns a localized string representation of the current network reachability status. 140 | */ 141 | - (NSString *)localizedNetworkReachabilityStatusString; 142 | 143 | ///--------------------------------------------------- 144 | /// @name Setting Network Reachability Change Callback 145 | ///--------------------------------------------------- 146 | 147 | /** 148 | Sets a callback to be executed when the network availability of the `baseURL` host changes. 149 | 150 | @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`. 151 | */ 152 | - (void)setReachabilityStatusChangeBlock:(nullable void (^)(AFNetworkReachabilityStatus status))block; 153 | 154 | @end 155 | 156 | ///---------------- 157 | /// @name Constants 158 | ///---------------- 159 | 160 | /** 161 | ## Network Reachability 162 | 163 | The following constants are provided by `AFNetworkReachabilityManager` as possible network reachability statuses. 164 | 165 | enum { 166 | AFNetworkReachabilityStatusUnknown, 167 | AFNetworkReachabilityStatusNotReachable, 168 | AFNetworkReachabilityStatusReachableViaWWAN, 169 | AFNetworkReachabilityStatusReachableViaWiFi, 170 | } 171 | 172 | `AFNetworkReachabilityStatusUnknown` 173 | The `baseURL` host reachability is not known. 174 | 175 | `AFNetworkReachabilityStatusNotReachable` 176 | The `baseURL` host cannot be reached. 177 | 178 | `AFNetworkReachabilityStatusReachableViaWWAN` 179 | The `baseURL` host can be reached via a cellular connection, such as EDGE or GPRS. 180 | 181 | `AFNetworkReachabilityStatusReachableViaWiFi` 182 | The `baseURL` host can be reached via a Wi-Fi connection. 183 | 184 | ### Keys for Notification UserInfo Dictionary 185 | 186 | Strings that are used as keys in a `userInfo` dictionary in a network reachability status change notification. 187 | 188 | `AFNetworkingReachabilityNotificationStatusItem` 189 | A key in the userInfo dictionary in a `AFNetworkingReachabilityDidChangeNotification` notification. 190 | The corresponding value is an `NSNumber` object representing the `AFNetworkReachabilityStatus` value for the current reachability status. 191 | */ 192 | 193 | ///-------------------- 194 | /// @name Notifications 195 | ///-------------------- 196 | 197 | /** 198 | Posted when network reachability changes. 199 | 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. 200 | 201 | @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`). 202 | */ 203 | FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityDidChangeNotification; 204 | FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityNotificationStatusItem; 205 | 206 | ///-------------------- 207 | /// @name Functions 208 | ///-------------------- 209 | 210 | /** 211 | Returns a localized string representation of an `AFNetworkReachabilityStatus` value. 212 | */ 213 | FOUNDATION_EXPORT NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status); 214 | 215 | NS_ASSUME_NONNULL_END 216 | #endif 217 | -------------------------------------------------------------------------------- /Pods/AFNetworking/AFNetworking/AFNetworking.h: -------------------------------------------------------------------------------- 1 | // AFNetworking.h 2 | // 3 | // Copyright (c) 2013 AFNetworking (http://afnetworking.com/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import 24 | #import 25 | #import 26 | 27 | #ifndef _AFNETWORKING_ 28 | #define _AFNETWORKING_ 29 | 30 | #import "AFURLRequestSerialization.h" 31 | #import "AFURLResponseSerialization.h" 32 | #import "AFSecurityPolicy.h" 33 | 34 | #if !TARGET_OS_WATCH 35 | #import "AFNetworkReachabilityManager.h" 36 | #endif 37 | 38 | #import "AFURLSessionManager.h" 39 | #import "AFHTTPSessionManager.h" 40 | 41 | #endif /* _AFNETWORKING_ */ 42 | -------------------------------------------------------------------------------- /Pods/AFNetworking/AFNetworking/AFSecurityPolicy.h: -------------------------------------------------------------------------------- 1 | // AFSecurityPolicy.h 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | #import 24 | 25 | typedef NS_ENUM(NSUInteger, AFSSLPinningMode) { 26 | AFSSLPinningModeNone, 27 | AFSSLPinningModePublicKey, 28 | AFSSLPinningModeCertificate, 29 | }; 30 | 31 | /** 32 | `AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections. 33 | 34 | 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. 35 | */ 36 | 37 | NS_ASSUME_NONNULL_BEGIN 38 | 39 | @interface AFSecurityPolicy : NSObject 40 | 41 | /** 42 | The criteria by which server trust should be evaluated against the pinned SSL certificates. Defaults to `AFSSLPinningModeNone`. 43 | */ 44 | @property (readonly, nonatomic, assign) AFSSLPinningMode SSLPinningMode; 45 | 46 | /** 47 | The certificates used to evaluate server trust according to the SSL pinning mode. 48 | 49 | By default, this property is set to any (`.cer`) certificates included in the target compiling AFNetworking. Note that if you are using AFNetworking as embedded framework, no certificates will be pinned by default. Use `certificatesInBundle` to load certificates from your target, and then create a new policy by calling `policyWithPinningMode:withPinnedCertificates`. 50 | 51 | Note that if pinning is enabled, `evaluateServerTrust:forDomain:` will return true if any pinned certificate matches. 52 | */ 53 | @property (nonatomic, strong, nullable) NSSet *pinnedCertificates; 54 | 55 | /** 56 | Whether or not to trust servers with an invalid or expired SSL certificates. Defaults to `NO`. 57 | */ 58 | @property (nonatomic, assign) BOOL allowInvalidCertificates; 59 | 60 | /** 61 | Whether or not to validate the domain name in the certificate's CN field. Defaults to `YES`. 62 | */ 63 | @property (nonatomic, assign) BOOL validatesDomainName; 64 | 65 | ///----------------------------------------- 66 | /// @name Getting Certificates from the Bundle 67 | ///----------------------------------------- 68 | 69 | /** 70 | 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`. 71 | 72 | @return The certificates included in the given bundle. 73 | */ 74 | + (NSSet *)certificatesInBundle:(NSBundle *)bundle; 75 | 76 | ///----------------------------------------- 77 | /// @name Getting Specific Security Policies 78 | ///----------------------------------------- 79 | 80 | /** 81 | 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. 82 | 83 | @return The default security policy. 84 | */ 85 | + (instancetype)defaultPolicy; 86 | 87 | ///--------------------- 88 | /// @name Initialization 89 | ///--------------------- 90 | 91 | /** 92 | Creates and returns a security policy with the specified pinning mode. 93 | 94 | @param pinningMode The SSL pinning mode. 95 | 96 | @return A new security policy. 97 | */ 98 | + (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode; 99 | 100 | /** 101 | Creates and returns a security policy with the specified pinning mode. 102 | 103 | @param pinningMode The SSL pinning mode. 104 | @param pinnedCertificates The certificates to pin against. 105 | 106 | @return A new security policy. 107 | */ 108 | + (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet *)pinnedCertificates; 109 | 110 | ///------------------------------ 111 | /// @name Evaluating Server Trust 112 | ///------------------------------ 113 | 114 | /** 115 | Whether or not the specified server trust should be accepted, based on the security policy. 116 | 117 | This method should be used when responding to an authentication challenge from a server. 118 | 119 | @param serverTrust The X.509 certificate trust of the server. 120 | @param domain The domain of serverTrust. If `nil`, the domain will not be validated. 121 | 122 | @return Whether or not to trust the server. 123 | */ 124 | - (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust 125 | forDomain:(nullable NSString *)domain; 126 | 127 | @end 128 | 129 | NS_ASSUME_NONNULL_END 130 | 131 | ///---------------- 132 | /// @name Constants 133 | ///---------------- 134 | 135 | /** 136 | ## SSL Pinning Modes 137 | 138 | The following constants are provided by `AFSSLPinningMode` as possible SSL pinning modes. 139 | 140 | enum { 141 | AFSSLPinningModeNone, 142 | AFSSLPinningModePublicKey, 143 | AFSSLPinningModeCertificate, 144 | } 145 | 146 | `AFSSLPinningModeNone` 147 | Do not used pinned certificates to validate servers. 148 | 149 | `AFSSLPinningModePublicKey` 150 | Validate host certificates against public keys of pinned certificates. 151 | 152 | `AFSSLPinningModeCertificate` 153 | Validate host certificates against pinned certificates. 154 | */ 155 | -------------------------------------------------------------------------------- /Pods/AFNetworking/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2011-2016 Alamofire Software Foundation (http://alamofire.org/) 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in 11 | all copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | THE SOFTWARE. 20 | -------------------------------------------------------------------------------- /Pods/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.h: -------------------------------------------------------------------------------- 1 | // AFAutoPurgingImageCache.h 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | #import 24 | 25 | #if TARGET_OS_IOS || TARGET_OS_TV 26 | #import 27 | 28 | NS_ASSUME_NONNULL_BEGIN 29 | 30 | /** 31 | The `AFImageCache` protocol defines a set of APIs for adding, removing and fetching images from a cache synchronously. 32 | */ 33 | @protocol AFImageCache 34 | 35 | /** 36 | Adds the image to the cache with the given identifier. 37 | 38 | @param image The image to cache. 39 | @param identifier The unique identifier for the image in the cache. 40 | */ 41 | - (void)addImage:(UIImage *)image withIdentifier:(NSString *)identifier; 42 | 43 | /** 44 | Removes the image from the cache matching the given identifier. 45 | 46 | @param identifier The unique identifier for the image in the cache. 47 | 48 | @return A BOOL indicating whether or not the image was removed from the cache. 49 | */ 50 | - (BOOL)removeImageWithIdentifier:(NSString *)identifier; 51 | 52 | /** 53 | Removes all images from the cache. 54 | 55 | @return A BOOL indicating whether or not all images were removed from the cache. 56 | */ 57 | - (BOOL)removeAllImages; 58 | 59 | /** 60 | Returns the image in the cache associated with the given identifier. 61 | 62 | @param identifier The unique identifier for the image in the cache. 63 | 64 | @return An image for the matching identifier, or nil. 65 | */ 66 | - (nullable UIImage *)imageWithIdentifier:(NSString *)identifier; 67 | @end 68 | 69 | 70 | /** 71 | 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. 72 | */ 73 | @protocol AFImageRequestCache 74 | 75 | /** 76 | Asks if the image should be cached using an identifier created from the request and additional identifier. 77 | 78 | @param image The image to be cached. 79 | @param request The unique URL request identifing the image asset. 80 | @param identifier The additional identifier to apply to the URL request to identify the image. 81 | 82 | @return A BOOL indicating whether or not the image should be added to the cache. YES will cache, NO will prevent caching. 83 | */ 84 | - (BOOL)shouldCacheImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier; 85 | 86 | /** 87 | Adds the image to the cache using an identifier created from the request and additional identifier. 88 | 89 | @param image The image to cache. 90 | @param request The unique URL request identifing the image asset. 91 | @param identifier The additional identifier to apply to the URL request to identify the image. 92 | */ 93 | - (void)addImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier; 94 | 95 | /** 96 | Removes the image from the cache using an identifier created from the request and additional identifier. 97 | 98 | @param request The unique URL request identifing the image asset. 99 | @param identifier The additional identifier to apply to the URL request to identify the image. 100 | 101 | @return A BOOL indicating whether or not all images were removed from the cache. 102 | */ 103 | - (BOOL)removeImageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier; 104 | 105 | /** 106 | Returns the image from the cache associated with an identifier created from the request and additional identifier. 107 | 108 | @param request The unique URL request identifing the image asset. 109 | @param identifier The additional identifier to apply to the URL request to identify the image. 110 | 111 | @return An image for the matching request and identifier, or nil. 112 | */ 113 | - (nullable UIImage *)imageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier; 114 | 115 | @end 116 | 117 | /** 118 | 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. 119 | */ 120 | @interface AFAutoPurgingImageCache : NSObject 121 | 122 | /** 123 | The total memory capacity of the cache in bytes. 124 | */ 125 | @property (nonatomic, assign) UInt64 memoryCapacity; 126 | 127 | /** 128 | The preferred memory usage after purge in bytes. During a purge, images will be purged until the memory capacity drops below this limit. 129 | */ 130 | @property (nonatomic, assign) UInt64 preferredMemoryUsageAfterPurge; 131 | 132 | /** 133 | The current total memory usage in bytes of all images stored within the cache. 134 | */ 135 | @property (nonatomic, assign, readonly) UInt64 memoryUsage; 136 | 137 | /** 138 | 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`. 139 | 140 | @return The new `AutoPurgingImageCache` instance. 141 | */ 142 | - (instancetype)init; 143 | 144 | /** 145 | Initialies the `AutoPurgingImageCache` instance with the given memory capacity and preferred memory usage 146 | after purge limit. 147 | 148 | @param memoryCapacity The total memory capacity of the cache in bytes. 149 | @param preferredMemoryCapacity The preferred memory usage after purge in bytes. 150 | 151 | @return The new `AutoPurgingImageCache` instance. 152 | */ 153 | - (instancetype)initWithMemoryCapacity:(UInt64)memoryCapacity preferredMemoryCapacity:(UInt64)preferredMemoryCapacity; 154 | 155 | @end 156 | 157 | NS_ASSUME_NONNULL_END 158 | 159 | #endif 160 | 161 | -------------------------------------------------------------------------------- /Pods/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.m: -------------------------------------------------------------------------------- 1 | // AFAutoPurgingImageCache.m 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | 24 | #if TARGET_OS_IOS || TARGET_OS_TV 25 | 26 | #import "AFAutoPurgingImageCache.h" 27 | 28 | @interface AFCachedImage : NSObject 29 | 30 | @property (nonatomic, strong) UIImage *image; 31 | @property (nonatomic, strong) NSString *identifier; 32 | @property (nonatomic, assign) UInt64 totalBytes; 33 | @property (nonatomic, strong) NSDate *lastAccessDate; 34 | @property (nonatomic, assign) UInt64 currentMemoryUsage; 35 | 36 | @end 37 | 38 | @implementation AFCachedImage 39 | 40 | -(instancetype)initWithImage:(UIImage *)image identifier:(NSString *)identifier { 41 | if (self = [self init]) { 42 | self.image = image; 43 | self.identifier = identifier; 44 | 45 | CGSize imageSize = CGSizeMake(image.size.width * image.scale, image.size.height * image.scale); 46 | CGFloat bytesPerPixel = 4.0; 47 | CGFloat bytesPerSize = imageSize.width * imageSize.height; 48 | self.totalBytes = (UInt64)bytesPerPixel * (UInt64)bytesPerSize; 49 | self.lastAccessDate = [NSDate date]; 50 | } 51 | return self; 52 | } 53 | 54 | - (UIImage*)accessImage { 55 | self.lastAccessDate = [NSDate date]; 56 | return self.image; 57 | } 58 | 59 | - (NSString *)description { 60 | NSString *descriptionString = [NSString stringWithFormat:@"Idenfitier: %@ lastAccessDate: %@ ", self.identifier, self.lastAccessDate]; 61 | return descriptionString; 62 | 63 | } 64 | 65 | @end 66 | 67 | @interface AFAutoPurgingImageCache () 68 | @property (nonatomic, strong) NSMutableDictionary *cachedImages; 69 | @property (nonatomic, assign) UInt64 currentMemoryUsage; 70 | @property (nonatomic, strong) dispatch_queue_t synchronizationQueue; 71 | @end 72 | 73 | @implementation AFAutoPurgingImageCache 74 | 75 | - (instancetype)init { 76 | return [self initWithMemoryCapacity:100 * 1024 * 1024 preferredMemoryCapacity:60 * 1024 * 1024]; 77 | } 78 | 79 | - (instancetype)initWithMemoryCapacity:(UInt64)memoryCapacity preferredMemoryCapacity:(UInt64)preferredMemoryCapacity { 80 | if (self = [super init]) { 81 | self.memoryCapacity = memoryCapacity; 82 | self.preferredMemoryUsageAfterPurge = preferredMemoryCapacity; 83 | self.cachedImages = [[NSMutableDictionary alloc] init]; 84 | 85 | NSString *queueName = [NSString stringWithFormat:@"com.alamofire.autopurgingimagecache-%@", [[NSUUID UUID] UUIDString]]; 86 | self.synchronizationQueue = dispatch_queue_create([queueName cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_CONCURRENT); 87 | 88 | [[NSNotificationCenter defaultCenter] 89 | addObserver:self 90 | selector:@selector(removeAllImages) 91 | name:UIApplicationDidReceiveMemoryWarningNotification 92 | object:nil]; 93 | 94 | } 95 | return self; 96 | } 97 | 98 | - (void)dealloc { 99 | [[NSNotificationCenter defaultCenter] removeObserver:self]; 100 | } 101 | 102 | - (UInt64)memoryUsage { 103 | __block UInt64 result = 0; 104 | dispatch_sync(self.synchronizationQueue, ^{ 105 | result = self.currentMemoryUsage; 106 | }); 107 | return result; 108 | } 109 | 110 | - (void)addImage:(UIImage *)image withIdentifier:(NSString *)identifier { 111 | dispatch_barrier_async(self.synchronizationQueue, ^{ 112 | AFCachedImage *cacheImage = [[AFCachedImage alloc] initWithImage:image identifier:identifier]; 113 | 114 | AFCachedImage *previousCachedImage = self.cachedImages[identifier]; 115 | if (previousCachedImage != nil) { 116 | self.currentMemoryUsage -= previousCachedImage.totalBytes; 117 | } 118 | 119 | self.cachedImages[identifier] = cacheImage; 120 | self.currentMemoryUsage += cacheImage.totalBytes; 121 | }); 122 | 123 | dispatch_barrier_async(self.synchronizationQueue, ^{ 124 | if (self.currentMemoryUsage > self.memoryCapacity) { 125 | UInt64 bytesToPurge = self.currentMemoryUsage - self.preferredMemoryUsageAfterPurge; 126 | NSMutableArray *sortedImages = [NSMutableArray arrayWithArray:self.cachedImages.allValues]; 127 | NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"lastAccessDate" 128 | ascending:YES]; 129 | [sortedImages sortUsingDescriptors:@[sortDescriptor]]; 130 | 131 | UInt64 bytesPurged = 0; 132 | 133 | for (AFCachedImage *cachedImage in sortedImages) { 134 | [self.cachedImages removeObjectForKey:cachedImage.identifier]; 135 | bytesPurged += cachedImage.totalBytes; 136 | if (bytesPurged >= bytesToPurge) { 137 | break ; 138 | } 139 | } 140 | self.currentMemoryUsage -= bytesPurged; 141 | } 142 | }); 143 | } 144 | 145 | - (BOOL)removeImageWithIdentifier:(NSString *)identifier { 146 | __block BOOL removed = NO; 147 | dispatch_barrier_sync(self.synchronizationQueue, ^{ 148 | AFCachedImage *cachedImage = self.cachedImages[identifier]; 149 | if (cachedImage != nil) { 150 | [self.cachedImages removeObjectForKey:identifier]; 151 | self.currentMemoryUsage -= cachedImage.totalBytes; 152 | removed = YES; 153 | } 154 | }); 155 | return removed; 156 | } 157 | 158 | - (BOOL)removeAllImages { 159 | __block BOOL removed = NO; 160 | dispatch_barrier_sync(self.synchronizationQueue, ^{ 161 | if (self.cachedImages.count > 0) { 162 | [self.cachedImages removeAllObjects]; 163 | self.currentMemoryUsage = 0; 164 | removed = YES; 165 | } 166 | }); 167 | return removed; 168 | } 169 | 170 | - (nullable UIImage *)imageWithIdentifier:(NSString *)identifier { 171 | __block UIImage *image = nil; 172 | dispatch_sync(self.synchronizationQueue, ^{ 173 | AFCachedImage *cachedImage = self.cachedImages[identifier]; 174 | image = [cachedImage accessImage]; 175 | }); 176 | return image; 177 | } 178 | 179 | - (void)addImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier { 180 | [self addImage:image withIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]]; 181 | } 182 | 183 | - (BOOL)removeImageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier { 184 | return [self removeImageWithIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]]; 185 | } 186 | 187 | - (nullable UIImage *)imageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier { 188 | return [self imageWithIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]]; 189 | } 190 | 191 | - (NSString *)imageCacheKeyFromURLRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)additionalIdentifier { 192 | NSString *key = request.URL.absoluteString; 193 | if (additionalIdentifier != nil) { 194 | key = [key stringByAppendingString:additionalIdentifier]; 195 | } 196 | return key; 197 | } 198 | 199 | - (BOOL)shouldCacheImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier { 200 | return YES; 201 | } 202 | 203 | @end 204 | 205 | #endif 206 | -------------------------------------------------------------------------------- /Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h: -------------------------------------------------------------------------------- 1 | // AFNetworkActivityIndicatorManager.h 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | 24 | #import 25 | 26 | #if TARGET_OS_IOS 27 | 28 | #import 29 | 30 | NS_ASSUME_NONNULL_BEGIN 31 | 32 | /** 33 | `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. 34 | 35 | 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: 36 | 37 | [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES]; 38 | 39 | 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. 40 | 41 | See the Apple Human Interface Guidelines section about the Network Activity Indicator for more information: 42 | http://developer.apple.com/library/iOS/#documentation/UserExperience/Conceptual/MobileHIG/UIElementGuidelines/UIElementGuidelines.html#//apple_ref/doc/uid/TP40006556-CH13-SW44 43 | */ 44 | NS_EXTENSION_UNAVAILABLE_IOS("Use view controller based solutions where appropriate instead.") 45 | @interface AFNetworkActivityIndicatorManager : NSObject 46 | 47 | /** 48 | A Boolean value indicating whether the manager is enabled. 49 | 50 | If YES, the manager will change status bar network activity indicator according to network operation notifications it receives. The default value is NO. 51 | */ 52 | @property (nonatomic, assign, getter = isEnabled) BOOL enabled; 53 | 54 | /** 55 | A Boolean value indicating whether the network activity indicator manager is currently active. 56 | */ 57 | @property (readonly, nonatomic, assign, getter=isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible; 58 | 59 | /** 60 | 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. 61 | 62 | Apple's HIG describes the following: 63 | 64 | > 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. 65 | 66 | */ 67 | @property (nonatomic, assign) NSTimeInterval activationDelay; 68 | 69 | /** 70 | 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. 71 | */ 72 | 73 | @property (nonatomic, assign) NSTimeInterval completionDelay; 74 | 75 | /** 76 | Returns the shared network activity indicator manager object for the system. 77 | 78 | @return The systemwide network activity indicator manager. 79 | */ 80 | + (instancetype)sharedManager; 81 | 82 | /** 83 | Increments the number of active network requests. If this number was zero before incrementing, this will start animating the status bar network activity indicator. 84 | */ 85 | - (void)incrementActivityCount; 86 | 87 | /** 88 | Decrements the number of active network requests. If this number becomes zero after decrementing, this will stop animating the status bar network activity indicator. 89 | */ 90 | - (void)decrementActivityCount; 91 | 92 | /** 93 | 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. 94 | 95 | @param block A block to be executed when the network activity indicator status changes. 96 | */ 97 | - (void)setNetworkingActivityActionWithBlock:(nullable void (^)(BOOL networkActivityIndicatorVisible))block; 98 | 99 | @end 100 | 101 | NS_ASSUME_NONNULL_END 102 | 103 | #endif 104 | -------------------------------------------------------------------------------- /Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h: -------------------------------------------------------------------------------- 1 | // UIActivityIndicatorView+AFNetworking.h 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | 24 | #import 25 | 26 | #if TARGET_OS_IOS || TARGET_OS_TV 27 | 28 | #import 29 | 30 | /** 31 | 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. 32 | */ 33 | @interface UIActivityIndicatorView (AFNetworking) 34 | 35 | ///---------------------------------- 36 | /// @name Animating for Session Tasks 37 | ///---------------------------------- 38 | 39 | /** 40 | Binds the animating state to the state of the specified task. 41 | 42 | @param task The task. If `nil`, automatic updating from any previously specified operation will be disabled. 43 | */ 44 | - (void)setAnimatingWithStateOfTask:(nullable NSURLSessionTask *)task; 45 | 46 | @end 47 | 48 | #endif 49 | -------------------------------------------------------------------------------- /Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m: -------------------------------------------------------------------------------- 1 | // UIActivityIndicatorView+AFNetworking.m 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import "UIActivityIndicatorView+AFNetworking.h" 23 | #import 24 | 25 | #if TARGET_OS_IOS || TARGET_OS_TV 26 | 27 | #import "AFURLSessionManager.h" 28 | 29 | @interface AFActivityIndicatorViewNotificationObserver : NSObject 30 | @property (readonly, nonatomic, weak) UIActivityIndicatorView *activityIndicatorView; 31 | - (instancetype)initWithActivityIndicatorView:(UIActivityIndicatorView *)activityIndicatorView; 32 | 33 | - (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task; 34 | 35 | @end 36 | 37 | @implementation UIActivityIndicatorView (AFNetworking) 38 | 39 | - (AFActivityIndicatorViewNotificationObserver *)af_notificationObserver { 40 | AFActivityIndicatorViewNotificationObserver *notificationObserver = objc_getAssociatedObject(self, @selector(af_notificationObserver)); 41 | if (notificationObserver == nil) { 42 | notificationObserver = [[AFActivityIndicatorViewNotificationObserver alloc] initWithActivityIndicatorView:self]; 43 | objc_setAssociatedObject(self, @selector(af_notificationObserver), notificationObserver, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 44 | } 45 | return notificationObserver; 46 | } 47 | 48 | - (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task { 49 | [[self af_notificationObserver] setAnimatingWithStateOfTask:task]; 50 | } 51 | 52 | @end 53 | 54 | @implementation AFActivityIndicatorViewNotificationObserver 55 | 56 | - (instancetype)initWithActivityIndicatorView:(UIActivityIndicatorView *)activityIndicatorView 57 | { 58 | self = [super init]; 59 | if (self) { 60 | _activityIndicatorView = activityIndicatorView; 61 | } 62 | return self; 63 | } 64 | 65 | - (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task { 66 | NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; 67 | 68 | [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; 69 | [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; 70 | [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; 71 | 72 | if (task) { 73 | if (task.state != NSURLSessionTaskStateCompleted) { 74 | UIActivityIndicatorView *activityIndicatorView = self.activityIndicatorView; 75 | if (task.state == NSURLSessionTaskStateRunning) { 76 | [activityIndicatorView startAnimating]; 77 | } else { 78 | [activityIndicatorView stopAnimating]; 79 | } 80 | 81 | [notificationCenter addObserver:self selector:@selector(af_startAnimating) name:AFNetworkingTaskDidResumeNotification object:task]; 82 | [notificationCenter addObserver:self selector:@selector(af_stopAnimating) name:AFNetworkingTaskDidCompleteNotification object:task]; 83 | [notificationCenter addObserver:self selector:@selector(af_stopAnimating) name:AFNetworkingTaskDidSuspendNotification object:task]; 84 | } 85 | } 86 | } 87 | 88 | #pragma mark - 89 | 90 | - (void)af_startAnimating { 91 | dispatch_async(dispatch_get_main_queue(), ^{ 92 | [self.activityIndicatorView startAnimating]; 93 | }); 94 | } 95 | 96 | - (void)af_stopAnimating { 97 | dispatch_async(dispatch_get_main_queue(), ^{ 98 | [self.activityIndicatorView stopAnimating]; 99 | }); 100 | } 101 | 102 | #pragma mark - 103 | 104 | - (void)dealloc { 105 | NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; 106 | 107 | [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; 108 | [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; 109 | [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; 110 | } 111 | 112 | @end 113 | 114 | #endif 115 | -------------------------------------------------------------------------------- /Pods/AFNetworking/UIKit+AFNetworking/UIImage+AFNetworking.h: -------------------------------------------------------------------------------- 1 | // 2 | // UIImage+AFNetworking.h 3 | // 4 | // 5 | // Created by Paulo Ferreira on 08/07/15. 6 | // 7 | // Permission is hereby granted, free of charge, to any person obtaining a copy 8 | // of this software and associated documentation files (the "Software"), to deal 9 | // in the Software without restriction, including without limitation the rights 10 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 11 | // copies of the Software, and to permit persons to whom the Software is 12 | // furnished to do so, subject to the following conditions: 13 | // 14 | // The above copyright notice and this permission notice shall be included in 15 | // all copies or substantial portions of the Software. 16 | // 17 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 18 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 20 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 21 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 23 | // THE SOFTWARE. 24 | 25 | #if TARGET_OS_IOS || TARGET_OS_TV 26 | 27 | #import 28 | 29 | @interface UIImage (AFNetworking) 30 | 31 | + (UIImage*) safeImageWithData:(NSData*)data; 32 | 33 | @end 34 | 35 | #endif 36 | -------------------------------------------------------------------------------- /Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h: -------------------------------------------------------------------------------- 1 | // UIImageView+AFNetworking.h 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | 24 | #import 25 | 26 | #if TARGET_OS_IOS || TARGET_OS_TV 27 | 28 | #import 29 | 30 | NS_ASSUME_NONNULL_BEGIN 31 | 32 | @class AFImageDownloader; 33 | 34 | /** 35 | 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. 36 | */ 37 | @interface UIImageView (AFNetworking) 38 | 39 | ///------------------------------------ 40 | /// @name Accessing the Image Downloader 41 | ///------------------------------------ 42 | 43 | /** 44 | Set the shared image downloader used to download images. 45 | 46 | @param imageDownloader The shared image downloader used to download images. 47 | */ 48 | + (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader; 49 | 50 | /** 51 | The shared image downloader used to download images. 52 | */ 53 | + (AFImageDownloader *)sharedImageDownloader; 54 | 55 | ///-------------------- 56 | /// @name Setting Image 57 | ///-------------------- 58 | 59 | /** 60 | 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. 61 | 62 | 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. 63 | 64 | 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:` 65 | 66 | @param url The URL used for the image request. 67 | */ 68 | - (void)setImageWithURL:(NSURL *)url; 69 | 70 | /** 71 | 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. 72 | 73 | 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. 74 | 75 | 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:` 76 | 77 | @param url The URL used for the image request. 78 | @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. 79 | */ 80 | - (void)setImageWithURL:(NSURL *)url 81 | placeholderImage:(nullable UIImage *)placeholderImage; 82 | 83 | /** 84 | 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. 85 | 86 | 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. 87 | 88 | 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. 89 | 90 | @param urlRequest The URL request used for the image request. 91 | @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. 92 | @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`. 93 | @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. 94 | */ 95 | - (void)setImageWithURLRequest:(NSURLRequest *)urlRequest 96 | placeholderImage:(nullable UIImage *)placeholderImage 97 | success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success 98 | failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; 99 | 100 | /** 101 | Cancels any executing image operation for the receiver, if one exists. 102 | */ 103 | - (void)cancelImageDownloadTask; 104 | 105 | @end 106 | 107 | NS_ASSUME_NONNULL_END 108 | 109 | #endif 110 | -------------------------------------------------------------------------------- /Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.m: -------------------------------------------------------------------------------- 1 | // UIImageView+AFNetworking.m 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import "UIImageView+AFNetworking.h" 23 | 24 | #import 25 | 26 | #if TARGET_OS_IOS || TARGET_OS_TV 27 | 28 | #import "AFImageDownloader.h" 29 | 30 | @interface UIImageView (_AFNetworking) 31 | @property (readwrite, nonatomic, strong, setter = af_setActiveImageDownloadReceipt:) AFImageDownloadReceipt *af_activeImageDownloadReceipt; 32 | @end 33 | 34 | @implementation UIImageView (_AFNetworking) 35 | 36 | - (AFImageDownloadReceipt *)af_activeImageDownloadReceipt { 37 | return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, @selector(af_activeImageDownloadReceipt)); 38 | } 39 | 40 | - (void)af_setActiveImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt { 41 | objc_setAssociatedObject(self, @selector(af_activeImageDownloadReceipt), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 42 | } 43 | 44 | @end 45 | 46 | #pragma mark - 47 | 48 | @implementation UIImageView (AFNetworking) 49 | 50 | + (AFImageDownloader *)sharedImageDownloader { 51 | return objc_getAssociatedObject(self, @selector(sharedImageDownloader)) ?: [AFImageDownloader defaultInstance]; 52 | } 53 | 54 | + (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader { 55 | objc_setAssociatedObject(self, @selector(sharedImageDownloader), imageDownloader, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 56 | } 57 | 58 | #pragma mark - 59 | 60 | - (void)setImageWithURL:(NSURL *)url { 61 | [self setImageWithURL:url placeholderImage:nil]; 62 | } 63 | 64 | - (void)setImageWithURL:(NSURL *)url 65 | placeholderImage:(UIImage *)placeholderImage 66 | { 67 | NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 68 | [request addValue:@"image/*" forHTTPHeaderField:@"Accept"]; 69 | 70 | [self setImageWithURLRequest:request placeholderImage:placeholderImage success:nil failure:nil]; 71 | } 72 | 73 | - (void)setImageWithURLRequest:(NSURLRequest *)urlRequest 74 | placeholderImage:(UIImage *)placeholderImage 75 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success 76 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure 77 | { 78 | 79 | if ([urlRequest URL] == nil) { 80 | self.image = placeholderImage; 81 | if (failure) { 82 | NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorBadURL userInfo:nil]; 83 | failure(urlRequest, nil, error); 84 | } 85 | return; 86 | } 87 | 88 | if ([self isActiveTaskURLEqualToURLRequest:urlRequest]){ 89 | return; 90 | } 91 | 92 | [self cancelImageDownloadTask]; 93 | 94 | AFImageDownloader *downloader = [[self class] sharedImageDownloader]; 95 | id imageCache = downloader.imageCache; 96 | 97 | //Use the image from the image cache if it exists 98 | UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil]; 99 | if (cachedImage) { 100 | if (success) { 101 | success(urlRequest, nil, cachedImage); 102 | } else { 103 | self.image = cachedImage; 104 | } 105 | [self clearActiveDownloadInformation]; 106 | } else { 107 | if (placeholderImage) { 108 | self.image = placeholderImage; 109 | } 110 | 111 | __weak __typeof(self)weakSelf = self; 112 | NSUUID *downloadID = [NSUUID UUID]; 113 | AFImageDownloadReceipt *receipt; 114 | receipt = [downloader 115 | downloadImageForURLRequest:urlRequest 116 | withReceiptID:downloadID 117 | success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { 118 | __strong __typeof(weakSelf)strongSelf = weakSelf; 119 | if ([strongSelf.af_activeImageDownloadReceipt.receiptID isEqual:downloadID]) { 120 | if (success) { 121 | success(request, response, responseObject); 122 | } else if(responseObject) { 123 | strongSelf.image = responseObject; 124 | } 125 | [strongSelf clearActiveDownloadInformation]; 126 | } 127 | 128 | } 129 | failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) { 130 | __strong __typeof(weakSelf)strongSelf = weakSelf; 131 | if ([strongSelf.af_activeImageDownloadReceipt.receiptID isEqual:downloadID]) { 132 | if (failure) { 133 | failure(request, response, error); 134 | } 135 | [strongSelf clearActiveDownloadInformation]; 136 | } 137 | }]; 138 | 139 | self.af_activeImageDownloadReceipt = receipt; 140 | } 141 | } 142 | 143 | - (void)cancelImageDownloadTask { 144 | if (self.af_activeImageDownloadReceipt != nil) { 145 | [[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:self.af_activeImageDownloadReceipt]; 146 | [self clearActiveDownloadInformation]; 147 | } 148 | } 149 | 150 | - (void)clearActiveDownloadInformation { 151 | self.af_activeImageDownloadReceipt = nil; 152 | } 153 | 154 | - (BOOL)isActiveTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest { 155 | return [self.af_activeImageDownloadReceipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString]; 156 | } 157 | 158 | @end 159 | 160 | #endif 161 | -------------------------------------------------------------------------------- /Pods/AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h: -------------------------------------------------------------------------------- 1 | // UIKit+AFNetworking.h 2 | // 3 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #if TARGET_OS_IOS || TARGET_OS_TV 24 | #import 25 | 26 | #ifndef _UIKIT_AFNETWORKING_ 27 | #define _UIKIT_AFNETWORKING_ 28 | 29 | #if TARGET_OS_IOS 30 | #import "AFAutoPurgingImageCache.h" 31 | #import "AFImageDownloader.h" 32 | #import "AFNetworkActivityIndicatorManager.h" 33 | #import "UIRefreshControl+AFNetworking.h" 34 | #import "UIWebView+AFNetworking.h" 35 | #endif 36 | 37 | #import "UIActivityIndicatorView+AFNetworking.h" 38 | #import "UIButton+AFNetworking.h" 39 | #import "UIImageView+AFNetworking.h" 40 | #import "UIProgressView+AFNetworking.h" 41 | #endif /* _UIKIT_AFNETWORKING_ */ 42 | #endif 43 | -------------------------------------------------------------------------------- /Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h: -------------------------------------------------------------------------------- 1 | // UIProgressView+AFNetworking.h 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | 24 | #import 25 | 26 | #if TARGET_OS_IOS || TARGET_OS_TV 27 | 28 | #import 29 | 30 | NS_ASSUME_NONNULL_BEGIN 31 | 32 | 33 | /** 34 | 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. 35 | */ 36 | @interface UIProgressView (AFNetworking) 37 | 38 | ///------------------------------------ 39 | /// @name Setting Session Task Progress 40 | ///------------------------------------ 41 | 42 | /** 43 | Binds the progress to the upload progress of the specified session task. 44 | 45 | @param task The session task. 46 | @param animated `YES` if the change should be animated, `NO` if the change should happen immediately. 47 | */ 48 | - (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task 49 | animated:(BOOL)animated; 50 | 51 | /** 52 | Binds the progress to the download progress of the specified session task. 53 | 54 | @param task The session task. 55 | @param animated `YES` if the change should be animated, `NO` if the change should happen immediately. 56 | */ 57 | - (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task 58 | animated:(BOOL)animated; 59 | 60 | @end 61 | 62 | NS_ASSUME_NONNULL_END 63 | 64 | #endif 65 | -------------------------------------------------------------------------------- /Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.m: -------------------------------------------------------------------------------- 1 | // UIProgressView+AFNetworking.m 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import "UIProgressView+AFNetworking.h" 23 | 24 | #import 25 | 26 | #if TARGET_OS_IOS || TARGET_OS_TV 27 | 28 | #import "AFURLSessionManager.h" 29 | 30 | static void * AFTaskCountOfBytesSentContext = &AFTaskCountOfBytesSentContext; 31 | static void * AFTaskCountOfBytesReceivedContext = &AFTaskCountOfBytesReceivedContext; 32 | 33 | #pragma mark - 34 | 35 | @implementation UIProgressView (AFNetworking) 36 | 37 | - (BOOL)af_uploadProgressAnimated { 38 | return [(NSNumber *)objc_getAssociatedObject(self, @selector(af_uploadProgressAnimated)) boolValue]; 39 | } 40 | 41 | - (void)af_setUploadProgressAnimated:(BOOL)animated { 42 | objc_setAssociatedObject(self, @selector(af_uploadProgressAnimated), @(animated), OBJC_ASSOCIATION_RETAIN_NONATOMIC); 43 | } 44 | 45 | - (BOOL)af_downloadProgressAnimated { 46 | return [(NSNumber *)objc_getAssociatedObject(self, @selector(af_downloadProgressAnimated)) boolValue]; 47 | } 48 | 49 | - (void)af_setDownloadProgressAnimated:(BOOL)animated { 50 | objc_setAssociatedObject(self, @selector(af_downloadProgressAnimated), @(animated), OBJC_ASSOCIATION_RETAIN_NONATOMIC); 51 | } 52 | 53 | #pragma mark - 54 | 55 | - (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task 56 | animated:(BOOL)animated 57 | { 58 | if (task.state == NSURLSessionTaskStateCompleted) { 59 | return; 60 | } 61 | 62 | [task addObserver:self forKeyPath:@"state" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesSentContext]; 63 | [task addObserver:self forKeyPath:@"countOfBytesSent" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesSentContext]; 64 | 65 | [self af_setUploadProgressAnimated:animated]; 66 | } 67 | 68 | - (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task 69 | animated:(BOOL)animated 70 | { 71 | if (task.state == NSURLSessionTaskStateCompleted) { 72 | return; 73 | } 74 | 75 | [task addObserver:self forKeyPath:@"state" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext]; 76 | [task addObserver:self forKeyPath:@"countOfBytesReceived" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext]; 77 | 78 | [self af_setDownloadProgressAnimated:animated]; 79 | } 80 | 81 | #pragma mark - NSKeyValueObserving 82 | 83 | - (void)observeValueForKeyPath:(NSString *)keyPath 84 | ofObject:(id)object 85 | change:(__unused NSDictionary *)change 86 | context:(void *)context 87 | { 88 | if (context == AFTaskCountOfBytesSentContext || context == AFTaskCountOfBytesReceivedContext) { 89 | if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesSent))]) { 90 | if ([object countOfBytesExpectedToSend] > 0) { 91 | dispatch_async(dispatch_get_main_queue(), ^{ 92 | [self setProgress:[object countOfBytesSent] / ([object countOfBytesExpectedToSend] * 1.0f) animated:self.af_uploadProgressAnimated]; 93 | }); 94 | } 95 | } 96 | 97 | if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesReceived))]) { 98 | if ([object countOfBytesExpectedToReceive] > 0) { 99 | dispatch_async(dispatch_get_main_queue(), ^{ 100 | [self setProgress:[object countOfBytesReceived] / ([object countOfBytesExpectedToReceive] * 1.0f) animated:self.af_downloadProgressAnimated]; 101 | }); 102 | } 103 | } 104 | 105 | if ([keyPath isEqualToString:NSStringFromSelector(@selector(state))]) { 106 | if ([(NSURLSessionTask *)object state] == NSURLSessionTaskStateCompleted) { 107 | @try { 108 | [object removeObserver:self forKeyPath:NSStringFromSelector(@selector(state))]; 109 | 110 | if (context == AFTaskCountOfBytesSentContext) { 111 | [object removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesSent))]; 112 | } 113 | 114 | if (context == AFTaskCountOfBytesReceivedContext) { 115 | [object removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesReceived))]; 116 | } 117 | } 118 | @catch (NSException * __unused exception) {} 119 | } 120 | } 121 | } 122 | } 123 | 124 | @end 125 | 126 | #endif 127 | -------------------------------------------------------------------------------- /Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h: -------------------------------------------------------------------------------- 1 | // UIRefreshControl+AFNetworking.m 2 | // 3 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import 24 | 25 | #import 26 | 27 | #if TARGET_OS_IOS 28 | 29 | #import 30 | 31 | NS_ASSUME_NONNULL_BEGIN 32 | 33 | /** 34 | 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. 35 | */ 36 | @interface UIRefreshControl (AFNetworking) 37 | 38 | ///----------------------------------- 39 | /// @name Refreshing for Session Tasks 40 | ///----------------------------------- 41 | 42 | /** 43 | Binds the refreshing state to the state of the specified task. 44 | 45 | @param task The task. If `nil`, automatic updating from any previously specified operation will be disabled. 46 | */ 47 | - (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task; 48 | 49 | @end 50 | 51 | NS_ASSUME_NONNULL_END 52 | 53 | #endif 54 | -------------------------------------------------------------------------------- /Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.m: -------------------------------------------------------------------------------- 1 | // UIRefreshControl+AFNetworking.m 2 | // 3 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import "UIRefreshControl+AFNetworking.h" 24 | #import 25 | 26 | #if TARGET_OS_IOS 27 | 28 | #import "AFURLSessionManager.h" 29 | 30 | @interface AFRefreshControlNotificationObserver : NSObject 31 | @property (readonly, nonatomic, weak) UIRefreshControl *refreshControl; 32 | - (instancetype)initWithActivityRefreshControl:(UIRefreshControl *)refreshControl; 33 | 34 | - (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task; 35 | 36 | @end 37 | 38 | @implementation UIRefreshControl (AFNetworking) 39 | 40 | - (AFRefreshControlNotificationObserver *)af_notificationObserver { 41 | AFRefreshControlNotificationObserver *notificationObserver = objc_getAssociatedObject(self, @selector(af_notificationObserver)); 42 | if (notificationObserver == nil) { 43 | notificationObserver = [[AFRefreshControlNotificationObserver alloc] initWithActivityRefreshControl:self]; 44 | objc_setAssociatedObject(self, @selector(af_notificationObserver), notificationObserver, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 45 | } 46 | return notificationObserver; 47 | } 48 | 49 | - (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task { 50 | [[self af_notificationObserver] setRefreshingWithStateOfTask:task]; 51 | } 52 | 53 | @end 54 | 55 | @implementation AFRefreshControlNotificationObserver 56 | 57 | - (instancetype)initWithActivityRefreshControl:(UIRefreshControl *)refreshControl 58 | { 59 | self = [super init]; 60 | if (self) { 61 | _refreshControl = refreshControl; 62 | } 63 | return self; 64 | } 65 | 66 | - (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task { 67 | NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; 68 | 69 | [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; 70 | [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; 71 | [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; 72 | 73 | if (task) { 74 | UIRefreshControl *refreshControl = self.refreshControl; 75 | if (task.state == NSURLSessionTaskStateRunning) { 76 | [refreshControl beginRefreshing]; 77 | 78 | [notificationCenter addObserver:self selector:@selector(af_beginRefreshing) name:AFNetworkingTaskDidResumeNotification object:task]; 79 | [notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingTaskDidCompleteNotification object:task]; 80 | [notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingTaskDidSuspendNotification object:task]; 81 | } else { 82 | [refreshControl endRefreshing]; 83 | } 84 | } 85 | } 86 | 87 | #pragma mark - 88 | 89 | - (void)af_beginRefreshing { 90 | dispatch_async(dispatch_get_main_queue(), ^{ 91 | [self.refreshControl beginRefreshing]; 92 | }); 93 | } 94 | 95 | - (void)af_endRefreshing { 96 | dispatch_async(dispatch_get_main_queue(), ^{ 97 | [self.refreshControl endRefreshing]; 98 | }); 99 | } 100 | 101 | #pragma mark - 102 | 103 | - (void)dealloc { 104 | NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; 105 | 106 | [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; 107 | [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; 108 | [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; 109 | } 110 | 111 | @end 112 | 113 | #endif 114 | -------------------------------------------------------------------------------- /Pods/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.h: -------------------------------------------------------------------------------- 1 | // UIWebView+AFNetworking.h 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | 24 | #import 25 | 26 | #if TARGET_OS_IOS 27 | 28 | #import 29 | 30 | NS_ASSUME_NONNULL_BEGIN 31 | 32 | @class AFHTTPSessionManager; 33 | 34 | /** 35 | This category adds methods to the UIKit framework's `UIWebView` class. The methods in this category provide increased control over the request cycle, including progress monitoring and success / failure handling. 36 | 37 | @discussion When using these category methods, make sure to assign `delegate` for the web view, which implements `–webView:shouldStartLoadWithRequest:navigationType:` appropriately. This allows for tapped links to be loaded through AFNetworking, and can ensure that `canGoBack` & `canGoForward` update their values correctly. 38 | */ 39 | @interface UIWebView (AFNetworking) 40 | 41 | /** 42 | The session manager used to download all requests. 43 | */ 44 | @property (nonatomic, strong) AFHTTPSessionManager *sessionManager; 45 | 46 | /** 47 | Asynchronously loads the specified request. 48 | 49 | @param request A URL request identifying the location of the content to load. This must not be `nil`. 50 | @param progress A progress object monitoring the current download progress. 51 | @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. 52 | @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. 53 | */ 54 | - (void)loadRequest:(NSURLRequest *)request 55 | progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress 56 | success:(nullable NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success 57 | failure:(nullable void (^)(NSError *error))failure; 58 | 59 | /** 60 | Asynchronously loads the data associated with a particular request with a specified MIME type and text encoding. 61 | 62 | @param request A URL request identifying the location of the content to load. This must not be `nil`. 63 | @param MIMEType The MIME type of the content. Defaults to the content type of the response if not specified. 64 | @param textEncodingName The IANA encoding name, as in `utf-8` or `utf-16`. Defaults to the response text encoding if not specified. 65 | @param progress A progress object monitoring the current download progress. 66 | @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. 67 | @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. 68 | */ 69 | - (void)loadRequest:(NSURLRequest *)request 70 | MIMEType:(nullable NSString *)MIMEType 71 | textEncodingName:(nullable NSString *)textEncodingName 72 | progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress 73 | success:(nullable NSData * (^)(NSHTTPURLResponse *response, NSData *data))success 74 | failure:(nullable void (^)(NSError *error))failure; 75 | 76 | @end 77 | 78 | NS_ASSUME_NONNULL_END 79 | 80 | #endif 81 | -------------------------------------------------------------------------------- /Pods/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.m: -------------------------------------------------------------------------------- 1 | // UIWebView+AFNetworking.m 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import "UIWebView+AFNetworking.h" 23 | 24 | #import 25 | 26 | #if TARGET_OS_IOS 27 | 28 | #import "AFHTTPSessionManager.h" 29 | #import "AFURLResponseSerialization.h" 30 | #import "AFURLRequestSerialization.h" 31 | 32 | @interface UIWebView (_AFNetworking) 33 | @property (readwrite, nonatomic, strong, setter = af_setURLSessionTask:) NSURLSessionDataTask *af_URLSessionTask; 34 | @end 35 | 36 | @implementation UIWebView (_AFNetworking) 37 | 38 | - (NSURLSessionDataTask *)af_URLSessionTask { 39 | return (NSURLSessionDataTask *)objc_getAssociatedObject(self, @selector(af_URLSessionTask)); 40 | } 41 | 42 | - (void)af_setURLSessionTask:(NSURLSessionDataTask *)af_URLSessionTask { 43 | objc_setAssociatedObject(self, @selector(af_URLSessionTask), af_URLSessionTask, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 44 | } 45 | 46 | @end 47 | 48 | #pragma mark - 49 | 50 | @implementation UIWebView (AFNetworking) 51 | 52 | - (AFHTTPSessionManager *)sessionManager { 53 | static AFHTTPSessionManager *_af_defaultHTTPSessionManager = nil; 54 | static dispatch_once_t onceToken; 55 | dispatch_once(&onceToken, ^{ 56 | _af_defaultHTTPSessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; 57 | _af_defaultHTTPSessionManager.requestSerializer = [AFHTTPRequestSerializer serializer]; 58 | _af_defaultHTTPSessionManager.responseSerializer = [AFHTTPResponseSerializer serializer]; 59 | }); 60 | 61 | return objc_getAssociatedObject(self, @selector(sessionManager)) ?: _af_defaultHTTPSessionManager; 62 | } 63 | 64 | - (void)setSessionManager:(AFHTTPSessionManager *)sessionManager { 65 | objc_setAssociatedObject(self, @selector(sessionManager), sessionManager, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 66 | } 67 | 68 | - (AFHTTPResponseSerializer *)responseSerializer { 69 | static AFHTTPResponseSerializer *_af_defaultResponseSerializer = nil; 70 | static dispatch_once_t onceToken; 71 | dispatch_once(&onceToken, ^{ 72 | _af_defaultResponseSerializer = [AFHTTPResponseSerializer serializer]; 73 | }); 74 | 75 | return objc_getAssociatedObject(self, @selector(responseSerializer)) ?: _af_defaultResponseSerializer; 76 | } 77 | 78 | - (void)setResponseSerializer:(AFHTTPResponseSerializer *)responseSerializer { 79 | objc_setAssociatedObject(self, @selector(responseSerializer), responseSerializer, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 80 | } 81 | 82 | #pragma mark - 83 | 84 | - (void)loadRequest:(NSURLRequest *)request 85 | progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress 86 | success:(NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success 87 | failure:(void (^)(NSError *error))failure 88 | { 89 | [self loadRequest:request MIMEType:nil textEncodingName:nil progress:progress success:^NSData *(NSHTTPURLResponse *response, NSData *data) { 90 | NSStringEncoding stringEncoding = NSUTF8StringEncoding; 91 | if (response.textEncodingName) { 92 | CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)response.textEncodingName); 93 | if (encoding != kCFStringEncodingInvalidId) { 94 | stringEncoding = CFStringConvertEncodingToNSStringEncoding(encoding); 95 | } 96 | } 97 | 98 | NSString *string = [[NSString alloc] initWithData:data encoding:stringEncoding]; 99 | if (success) { 100 | string = success(response, string); 101 | } 102 | 103 | return [string dataUsingEncoding:stringEncoding]; 104 | } failure:failure]; 105 | } 106 | 107 | - (void)loadRequest:(NSURLRequest *)request 108 | MIMEType:(NSString *)MIMEType 109 | textEncodingName:(NSString *)textEncodingName 110 | progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress 111 | success:(NSData * (^)(NSHTTPURLResponse *response, NSData *data))success 112 | failure:(void (^)(NSError *error))failure 113 | { 114 | NSParameterAssert(request); 115 | 116 | if (self.af_URLSessionTask.state == NSURLSessionTaskStateRunning || self.af_URLSessionTask.state == NSURLSessionTaskStateSuspended) { 117 | [self.af_URLSessionTask cancel]; 118 | } 119 | self.af_URLSessionTask = nil; 120 | 121 | __weak __typeof(self)weakSelf = self; 122 | __block NSURLSessionDataTask *dataTask; 123 | dataTask = [self.sessionManager 124 | dataTaskWithRequest:request 125 | uploadProgress:nil 126 | downloadProgress:nil 127 | completionHandler:^(NSURLResponse * _Nonnull response, id _Nonnull responseObject, NSError * _Nullable error) { 128 | __strong __typeof(weakSelf) strongSelf = weakSelf; 129 | if (error) { 130 | if (failure) { 131 | failure(error); 132 | } 133 | } else { 134 | if (success) { 135 | success((NSHTTPURLResponse *)response, responseObject); 136 | } 137 | [strongSelf loadData:responseObject MIMEType:MIMEType textEncodingName:textEncodingName baseURL:[dataTask.currentRequest URL]]; 138 | 139 | if ([strongSelf.delegate respondsToSelector:@selector(webViewDidFinishLoad:)]) { 140 | [strongSelf.delegate webViewDidFinishLoad:strongSelf]; 141 | } 142 | } 143 | }]; 144 | self.af_URLSessionTask = dataTask; 145 | if (progress != nil) { 146 | *progress = [self.sessionManager downloadProgressForTask:dataTask]; 147 | } 148 | [self.af_URLSessionTask resume]; 149 | 150 | if ([self.delegate respondsToSelector:@selector(webViewDidStartLoad:)]) { 151 | [self.delegate webViewDidStartLoad:self]; 152 | } 153 | } 154 | 155 | @end 156 | 157 | #endif 158 | -------------------------------------------------------------------------------- /Pods/Headers/Private/AFNetworking/AFAutoPurgingImageCache.h: -------------------------------------------------------------------------------- 1 | ../../../AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.h -------------------------------------------------------------------------------- /Pods/Headers/Private/AFNetworking/AFCompatibilityMacros.h: -------------------------------------------------------------------------------- 1 | ../../../AFNetworking/AFNetworking/AFCompatibilityMacros.h -------------------------------------------------------------------------------- /Pods/Headers/Private/AFNetworking/AFHTTPSessionManager.h: -------------------------------------------------------------------------------- 1 | ../../../AFNetworking/AFNetworking/AFHTTPSessionManager.h -------------------------------------------------------------------------------- /Pods/Headers/Private/AFNetworking/AFImageDownloader.h: -------------------------------------------------------------------------------- 1 | ../../../AFNetworking/UIKit+AFNetworking/AFImageDownloader.h -------------------------------------------------------------------------------- /Pods/Headers/Private/AFNetworking/AFNetworkActivityIndicatorManager.h: -------------------------------------------------------------------------------- 1 | ../../../AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h -------------------------------------------------------------------------------- /Pods/Headers/Private/AFNetworking/AFNetworkReachabilityManager.h: -------------------------------------------------------------------------------- 1 | ../../../AFNetworking/AFNetworking/AFNetworkReachabilityManager.h -------------------------------------------------------------------------------- /Pods/Headers/Private/AFNetworking/AFNetworking.h: -------------------------------------------------------------------------------- 1 | ../../../AFNetworking/AFNetworking/AFNetworking.h -------------------------------------------------------------------------------- /Pods/Headers/Private/AFNetworking/AFSecurityPolicy.h: -------------------------------------------------------------------------------- 1 | ../../../AFNetworking/AFNetworking/AFSecurityPolicy.h -------------------------------------------------------------------------------- /Pods/Headers/Private/AFNetworking/AFURLRequestSerialization.h: -------------------------------------------------------------------------------- 1 | ../../../AFNetworking/AFNetworking/AFURLRequestSerialization.h -------------------------------------------------------------------------------- /Pods/Headers/Private/AFNetworking/AFURLResponseSerialization.h: -------------------------------------------------------------------------------- 1 | ../../../AFNetworking/AFNetworking/AFURLResponseSerialization.h -------------------------------------------------------------------------------- /Pods/Headers/Private/AFNetworking/AFURLSessionManager.h: -------------------------------------------------------------------------------- 1 | ../../../AFNetworking/AFNetworking/AFURLSessionManager.h -------------------------------------------------------------------------------- /Pods/Headers/Private/AFNetworking/UIActivityIndicatorView+AFNetworking.h: -------------------------------------------------------------------------------- 1 | ../../../AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h -------------------------------------------------------------------------------- /Pods/Headers/Private/AFNetworking/UIButton+AFNetworking.h: -------------------------------------------------------------------------------- 1 | ../../../AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h -------------------------------------------------------------------------------- /Pods/Headers/Private/AFNetworking/UIImage+AFNetworking.h: -------------------------------------------------------------------------------- 1 | ../../../AFNetworking/UIKit+AFNetworking/UIImage+AFNetworking.h -------------------------------------------------------------------------------- /Pods/Headers/Private/AFNetworking/UIImageView+AFNetworking.h: -------------------------------------------------------------------------------- 1 | ../../../AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h -------------------------------------------------------------------------------- /Pods/Headers/Private/AFNetworking/UIKit+AFNetworking.h: -------------------------------------------------------------------------------- 1 | ../../../AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h -------------------------------------------------------------------------------- /Pods/Headers/Private/AFNetworking/UIProgressView+AFNetworking.h: -------------------------------------------------------------------------------- 1 | ../../../AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h -------------------------------------------------------------------------------- /Pods/Headers/Private/AFNetworking/UIRefreshControl+AFNetworking.h: -------------------------------------------------------------------------------- 1 | ../../../AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h -------------------------------------------------------------------------------- /Pods/Headers/Private/AFNetworking/UIWebView+AFNetworking.h: -------------------------------------------------------------------------------- 1 | ../../../AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.h -------------------------------------------------------------------------------- /Pods/Headers/Private/YYCache/YYCache.h: -------------------------------------------------------------------------------- 1 | ../../../YYCache/YYCache/YYCache.h -------------------------------------------------------------------------------- /Pods/Headers/Private/YYCache/YYDiskCache.h: -------------------------------------------------------------------------------- 1 | ../../../YYCache/YYCache/YYDiskCache.h -------------------------------------------------------------------------------- /Pods/Headers/Private/YYCache/YYKVStorage.h: -------------------------------------------------------------------------------- 1 | ../../../YYCache/YYCache/YYKVStorage.h -------------------------------------------------------------------------------- /Pods/Headers/Private/YYCache/YYMemoryCache.h: -------------------------------------------------------------------------------- 1 | ../../../YYCache/YYCache/YYMemoryCache.h -------------------------------------------------------------------------------- /Pods/Headers/Public/AFNetworking/AFAutoPurgingImageCache.h: -------------------------------------------------------------------------------- 1 | ../../../AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.h -------------------------------------------------------------------------------- /Pods/Headers/Public/AFNetworking/AFCompatibilityMacros.h: -------------------------------------------------------------------------------- 1 | ../../../AFNetworking/AFNetworking/AFCompatibilityMacros.h -------------------------------------------------------------------------------- /Pods/Headers/Public/AFNetworking/AFHTTPSessionManager.h: -------------------------------------------------------------------------------- 1 | ../../../AFNetworking/AFNetworking/AFHTTPSessionManager.h -------------------------------------------------------------------------------- /Pods/Headers/Public/AFNetworking/AFImageDownloader.h: -------------------------------------------------------------------------------- 1 | ../../../AFNetworking/UIKit+AFNetworking/AFImageDownloader.h -------------------------------------------------------------------------------- /Pods/Headers/Public/AFNetworking/AFNetworkActivityIndicatorManager.h: -------------------------------------------------------------------------------- 1 | ../../../AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h -------------------------------------------------------------------------------- /Pods/Headers/Public/AFNetworking/AFNetworkReachabilityManager.h: -------------------------------------------------------------------------------- 1 | ../../../AFNetworking/AFNetworking/AFNetworkReachabilityManager.h -------------------------------------------------------------------------------- /Pods/Headers/Public/AFNetworking/AFNetworking.h: -------------------------------------------------------------------------------- 1 | ../../../AFNetworking/AFNetworking/AFNetworking.h -------------------------------------------------------------------------------- /Pods/Headers/Public/AFNetworking/AFSecurityPolicy.h: -------------------------------------------------------------------------------- 1 | ../../../AFNetworking/AFNetworking/AFSecurityPolicy.h -------------------------------------------------------------------------------- /Pods/Headers/Public/AFNetworking/AFURLRequestSerialization.h: -------------------------------------------------------------------------------- 1 | ../../../AFNetworking/AFNetworking/AFURLRequestSerialization.h -------------------------------------------------------------------------------- /Pods/Headers/Public/AFNetworking/AFURLResponseSerialization.h: -------------------------------------------------------------------------------- 1 | ../../../AFNetworking/AFNetworking/AFURLResponseSerialization.h -------------------------------------------------------------------------------- /Pods/Headers/Public/AFNetworking/AFURLSessionManager.h: -------------------------------------------------------------------------------- 1 | ../../../AFNetworking/AFNetworking/AFURLSessionManager.h -------------------------------------------------------------------------------- /Pods/Headers/Public/AFNetworking/UIActivityIndicatorView+AFNetworking.h: -------------------------------------------------------------------------------- 1 | ../../../AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h -------------------------------------------------------------------------------- /Pods/Headers/Public/AFNetworking/UIButton+AFNetworking.h: -------------------------------------------------------------------------------- 1 | ../../../AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h -------------------------------------------------------------------------------- /Pods/Headers/Public/AFNetworking/UIImage+AFNetworking.h: -------------------------------------------------------------------------------- 1 | ../../../AFNetworking/UIKit+AFNetworking/UIImage+AFNetworking.h -------------------------------------------------------------------------------- /Pods/Headers/Public/AFNetworking/UIImageView+AFNetworking.h: -------------------------------------------------------------------------------- 1 | ../../../AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h -------------------------------------------------------------------------------- /Pods/Headers/Public/AFNetworking/UIKit+AFNetworking.h: -------------------------------------------------------------------------------- 1 | ../../../AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h -------------------------------------------------------------------------------- /Pods/Headers/Public/AFNetworking/UIProgressView+AFNetworking.h: -------------------------------------------------------------------------------- 1 | ../../../AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h -------------------------------------------------------------------------------- /Pods/Headers/Public/AFNetworking/UIRefreshControl+AFNetworking.h: -------------------------------------------------------------------------------- 1 | ../../../AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h -------------------------------------------------------------------------------- /Pods/Headers/Public/AFNetworking/UIWebView+AFNetworking.h: -------------------------------------------------------------------------------- 1 | ../../../AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.h -------------------------------------------------------------------------------- /Pods/Headers/Public/YYCache/YYCache.h: -------------------------------------------------------------------------------- 1 | ../../../YYCache/YYCache/YYCache.h -------------------------------------------------------------------------------- /Pods/Headers/Public/YYCache/YYDiskCache.h: -------------------------------------------------------------------------------- 1 | ../../../YYCache/YYCache/YYDiskCache.h -------------------------------------------------------------------------------- /Pods/Headers/Public/YYCache/YYKVStorage.h: -------------------------------------------------------------------------------- 1 | ../../../YYCache/YYCache/YYKVStorage.h -------------------------------------------------------------------------------- /Pods/Headers/Public/YYCache/YYMemoryCache.h: -------------------------------------------------------------------------------- 1 | ../../../YYCache/YYCache/YYMemoryCache.h -------------------------------------------------------------------------------- /Pods/Manifest.lock: -------------------------------------------------------------------------------- 1 | PODS: 2 | - AFNetworking (3.2.1): 3 | - AFNetworking/NSURLSession (= 3.2.1) 4 | - AFNetworking/Reachability (= 3.2.1) 5 | - AFNetworking/Security (= 3.2.1) 6 | - AFNetworking/Serialization (= 3.2.1) 7 | - AFNetworking/UIKit (= 3.2.1) 8 | - AFNetworking/NSURLSession (3.2.1): 9 | - AFNetworking/Reachability 10 | - AFNetworking/Security 11 | - AFNetworking/Serialization 12 | - AFNetworking/Reachability (3.2.1) 13 | - AFNetworking/Security (3.2.1) 14 | - AFNetworking/Serialization (3.2.1) 15 | - AFNetworking/UIKit (3.2.1): 16 | - AFNetworking/NSURLSession 17 | - YYCache (1.0.4) 18 | 19 | DEPENDENCIES: 20 | - AFNetworking (~> 3.2.1) 21 | - YYCache (~> 1.0.4) 22 | 23 | SPEC REPOS: 24 | https://github.com/cocoapods/specs.git: 25 | - AFNetworking 26 | - YYCache 27 | 28 | SPEC CHECKSUMS: 29 | AFNetworking: b6f891fdfaed196b46c7a83cf209e09697b94057 30 | YYCache: 8105b6638f5e849296c71f331ff83891a4942952 31 | 32 | PODFILE CHECKSUM: cf44b36011f0dc3371dc54820b015cffc9c73bce 33 | 34 | COCOAPODS: 1.5.3 35 | -------------------------------------------------------------------------------- /Pods/Target Support Files/AFNetworking/AFNetworking-dummy.m: -------------------------------------------------------------------------------- 1 | #import 2 | @interface PodsDummy_AFNetworking : NSObject 3 | @end 4 | @implementation PodsDummy_AFNetworking 5 | @end 6 | -------------------------------------------------------------------------------- /Pods/Target Support Files/AFNetworking/AFNetworking-prefix.pch: -------------------------------------------------------------------------------- 1 | #ifdef __OBJC__ 2 | #import 3 | #else 4 | #ifndef FOUNDATION_EXPORT 5 | #if defined(__cplusplus) 6 | #define FOUNDATION_EXPORT extern "C" 7 | #else 8 | #define FOUNDATION_EXPORT extern 9 | #endif 10 | #endif 11 | #endif 12 | 13 | #ifndef TARGET_OS_IOS 14 | #define TARGET_OS_IOS TARGET_OS_IPHONE 15 | #endif 16 | 17 | #ifndef TARGET_OS_WATCH 18 | #define TARGET_OS_WATCH 0 19 | #endif 20 | 21 | #ifndef TARGET_OS_TV 22 | #define TARGET_OS_TV 0 23 | #endif 24 | -------------------------------------------------------------------------------- /Pods/Target Support Files/AFNetworking/AFNetworking.xcconfig: -------------------------------------------------------------------------------- 1 | CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/AFNetworking 2 | GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 3 | HEADER_SEARCH_PATHS = $(inherited) "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Private/AFNetworking" "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/AFNetworking" 4 | OTHER_LDFLAGS = -framework "CoreGraphics" -framework "MobileCoreServices" -framework "Security" -framework "SystemConfiguration" 5 | PODS_BUILD_DIR = ${BUILD_DIR} 6 | PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) 7 | PODS_ROOT = ${SRCROOT} 8 | PODS_TARGET_SRCROOT = ${PODS_ROOT}/AFNetworking 9 | PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} 10 | SKIP_INSTALL = YES 11 | -------------------------------------------------------------------------------- /Pods/Target Support Files/Pods-YBNetworkDemo/Pods-YBNetworkDemo-acknowledgements.markdown: -------------------------------------------------------------------------------- 1 | # Acknowledgements 2 | This application makes use of the following third party libraries: 3 | 4 | ## AFNetworking 5 | 6 | Copyright (c) 2011-2016 Alamofire Software Foundation (http://alamofire.org/) 7 | 8 | Permission is hereby granted, free of charge, to any person obtaining a copy 9 | of this software and associated documentation files (the "Software"), to deal 10 | in the Software without restriction, including without limitation the rights 11 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | copies of the Software, and to permit persons to whom the Software is 13 | furnished to do so, subject to the following conditions: 14 | 15 | The above copyright notice and this permission notice shall be included in 16 | all copies or substantial portions of the Software. 17 | 18 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | THE SOFTWARE. 25 | 26 | 27 | ## YYCache 28 | 29 | The MIT License (MIT) 30 | 31 | Copyright (c) 2015 ibireme 32 | 33 | Permission is hereby granted, free of charge, to any person obtaining a copy 34 | of this software and associated documentation files (the "Software"), to deal 35 | in the Software without restriction, including without limitation the rights 36 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 37 | copies of the Software, and to permit persons to whom the Software is 38 | furnished to do so, subject to the following conditions: 39 | 40 | The above copyright notice and this permission notice shall be included in all 41 | copies or substantial portions of the Software. 42 | 43 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 44 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 45 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 46 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 47 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 48 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 49 | SOFTWARE. 50 | 51 | 52 | Generated by CocoaPods - https://cocoapods.org 53 | -------------------------------------------------------------------------------- /Pods/Target Support Files/Pods-YBNetworkDemo/Pods-YBNetworkDemo-acknowledgements.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | PreferenceSpecifiers 6 | 7 | 8 | FooterText 9 | This application makes use of the following third party libraries: 10 | Title 11 | Acknowledgements 12 | Type 13 | PSGroupSpecifier 14 | 15 | 16 | FooterText 17 | Copyright (c) 2011-2016 Alamofire Software Foundation (http://alamofire.org/) 18 | 19 | Permission is hereby granted, free of charge, to any person obtaining a copy 20 | of this software and associated documentation files (the "Software"), to deal 21 | in the Software without restriction, including without limitation the rights 22 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 23 | copies of the Software, and to permit persons to whom the Software is 24 | furnished to do so, subject to the following conditions: 25 | 26 | The above copyright notice and this permission notice shall be included in 27 | all copies or substantial portions of the Software. 28 | 29 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 30 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 31 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 32 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 33 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 34 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 35 | THE SOFTWARE. 36 | 37 | License 38 | MIT 39 | Title 40 | AFNetworking 41 | Type 42 | PSGroupSpecifier 43 | 44 | 45 | FooterText 46 | The MIT License (MIT) 47 | 48 | Copyright (c) 2015 ibireme <ibireme@gmail.com> 49 | 50 | Permission is hereby granted, free of charge, to any person obtaining a copy 51 | of this software and associated documentation files (the "Software"), to deal 52 | in the Software without restriction, including without limitation the rights 53 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 54 | copies of the Software, and to permit persons to whom the Software is 55 | furnished to do so, subject to the following conditions: 56 | 57 | The above copyright notice and this permission notice shall be included in all 58 | copies or substantial portions of the Software. 59 | 60 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 61 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 62 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 63 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 64 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 65 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 66 | SOFTWARE. 67 | 68 | 69 | License 70 | MIT 71 | Title 72 | YYCache 73 | Type 74 | PSGroupSpecifier 75 | 76 | 77 | FooterText 78 | Generated by CocoaPods - https://cocoapods.org 79 | Title 80 | 81 | Type 82 | PSGroupSpecifier 83 | 84 | 85 | StringsTable 86 | Acknowledgements 87 | Title 88 | Acknowledgements 89 | 90 | 91 | -------------------------------------------------------------------------------- /Pods/Target Support Files/Pods-YBNetworkDemo/Pods-YBNetworkDemo-dummy.m: -------------------------------------------------------------------------------- 1 | #import 2 | @interface PodsDummy_Pods_YBNetworkDemo : NSObject 3 | @end 4 | @implementation PodsDummy_Pods_YBNetworkDemo 5 | @end 6 | -------------------------------------------------------------------------------- /Pods/Target Support Files/Pods-YBNetworkDemo/Pods-YBNetworkDemo-frameworks.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | set -e 3 | set -u 4 | set -o pipefail 5 | 6 | if [ -z ${FRAMEWORKS_FOLDER_PATH+x} ]; then 7 | # If FRAMEWORKS_FOLDER_PATH is not set, then there's nowhere for us to copy 8 | # frameworks to, so exit 0 (signalling the script phase was successful). 9 | exit 0 10 | fi 11 | 12 | echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" 13 | mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" 14 | 15 | COCOAPODS_PARALLEL_CODE_SIGN="${COCOAPODS_PARALLEL_CODE_SIGN:-false}" 16 | SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" 17 | 18 | # Used as a return value for each invocation of `strip_invalid_archs` function. 19 | STRIP_BINARY_RETVAL=0 20 | 21 | # This protects against multiple targets copying the same framework dependency at the same time. The solution 22 | # was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html 23 | RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") 24 | 25 | # Copies and strips a vendored framework 26 | install_framework() 27 | { 28 | if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then 29 | local source="${BUILT_PRODUCTS_DIR}/$1" 30 | elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then 31 | local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" 32 | elif [ -r "$1" ]; then 33 | local source="$1" 34 | fi 35 | 36 | local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" 37 | 38 | if [ -L "${source}" ]; then 39 | echo "Symlinked..." 40 | source="$(readlink "${source}")" 41 | fi 42 | 43 | # Use filter instead of exclude so missing patterns don't throw errors. 44 | echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" 45 | rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" 46 | 47 | local basename 48 | basename="$(basename -s .framework "$1")" 49 | binary="${destination}/${basename}.framework/${basename}" 50 | if ! [ -r "$binary" ]; then 51 | binary="${destination}/${basename}" 52 | fi 53 | 54 | # Strip invalid architectures so "fat" simulator / device frameworks work on device 55 | if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then 56 | strip_invalid_archs "$binary" 57 | fi 58 | 59 | # Resign the code if required by the build settings to avoid unstable apps 60 | code_sign_if_enabled "${destination}/$(basename "$1")" 61 | 62 | # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. 63 | if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then 64 | local swift_runtime_libs 65 | swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]}) 66 | for lib in $swift_runtime_libs; do 67 | echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" 68 | rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" 69 | code_sign_if_enabled "${destination}/${lib}" 70 | done 71 | fi 72 | } 73 | 74 | # Copies and strips a vendored dSYM 75 | install_dsym() { 76 | local source="$1" 77 | if [ -r "$source" ]; then 78 | # Copy the dSYM into a the targets temp dir. 79 | 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}\"" 80 | 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}" 81 | 82 | local basename 83 | basename="$(basename -s .framework.dSYM "$source")" 84 | binary="${DERIVED_FILES_DIR}/${basename}.framework.dSYM/Contents/Resources/DWARF/${basename}" 85 | 86 | # Strip invalid architectures so "fat" simulator / device frameworks work on device 87 | if [[ "$(file "$binary")" == *"Mach-O dSYM companion"* ]]; then 88 | strip_invalid_archs "$binary" 89 | fi 90 | 91 | if [[ $STRIP_BINARY_RETVAL == 1 ]]; then 92 | # Move the stripped file into its final destination. 93 | echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\"" 94 | rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.framework.dSYM" "${DWARF_DSYM_FOLDER_PATH}" 95 | else 96 | # 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. 97 | touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.framework.dSYM" 98 | fi 99 | fi 100 | } 101 | 102 | # Signs a framework with the provided identity 103 | code_sign_if_enabled() { 104 | if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED:-}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then 105 | # Use the current code_sign_identitiy 106 | echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" 107 | local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS:-} --preserve-metadata=identifier,entitlements '$1'" 108 | 109 | if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then 110 | code_sign_cmd="$code_sign_cmd &" 111 | fi 112 | echo "$code_sign_cmd" 113 | eval "$code_sign_cmd" 114 | fi 115 | } 116 | 117 | # Strip invalid architectures 118 | strip_invalid_archs() { 119 | binary="$1" 120 | # Get architectures for current target binary 121 | binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)" 122 | # Intersect them with the architectures we are building for 123 | intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)" 124 | # If there are no archs supported by this binary then warn the user 125 | if [[ -z "$intersected_archs" ]]; then 126 | echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)." 127 | STRIP_BINARY_RETVAL=0 128 | return 129 | fi 130 | stripped="" 131 | for arch in $binary_archs; do 132 | if ! [[ "${ARCHS}" == *"$arch"* ]]; then 133 | # Strip non-valid architectures in-place 134 | lipo -remove "$arch" -output "$binary" "$binary" || exit 1 135 | stripped="$stripped $arch" 136 | fi 137 | done 138 | if [[ "$stripped" ]]; then 139 | echo "Stripped $binary of architectures:$stripped" 140 | fi 141 | STRIP_BINARY_RETVAL=1 142 | } 143 | 144 | if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then 145 | wait 146 | fi 147 | -------------------------------------------------------------------------------- /Pods/Target Support Files/Pods-YBNetworkDemo/Pods-YBNetworkDemo-resources.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | set -e 3 | set -u 4 | set -o pipefail 5 | 6 | if [ -z ${UNLOCALIZED_RESOURCES_FOLDER_PATH+x} ]; then 7 | # If UNLOCALIZED_RESOURCES_FOLDER_PATH is not set, then there's nowhere for us to copy 8 | # resources to, so exit 0 (signalling the script phase was successful). 9 | exit 0 10 | fi 11 | 12 | mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" 13 | 14 | RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt 15 | > "$RESOURCES_TO_COPY" 16 | 17 | XCASSET_FILES=() 18 | 19 | # This protects against multiple targets copying the same framework dependency at the same time. The solution 20 | # was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html 21 | RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") 22 | 23 | case "${TARGETED_DEVICE_FAMILY:-}" in 24 | 1,2) 25 | TARGET_DEVICE_ARGS="--target-device ipad --target-device iphone" 26 | ;; 27 | 1) 28 | TARGET_DEVICE_ARGS="--target-device iphone" 29 | ;; 30 | 2) 31 | TARGET_DEVICE_ARGS="--target-device ipad" 32 | ;; 33 | 3) 34 | TARGET_DEVICE_ARGS="--target-device tv" 35 | ;; 36 | 4) 37 | TARGET_DEVICE_ARGS="--target-device watch" 38 | ;; 39 | *) 40 | TARGET_DEVICE_ARGS="--target-device mac" 41 | ;; 42 | esac 43 | 44 | install_resource() 45 | { 46 | if [[ "$1" = /* ]] ; then 47 | RESOURCE_PATH="$1" 48 | else 49 | RESOURCE_PATH="${PODS_ROOT}/$1" 50 | fi 51 | if [[ ! -e "$RESOURCE_PATH" ]] ; then 52 | cat << EOM 53 | error: Resource "$RESOURCE_PATH" not found. Run 'pod install' to update the copy resources script. 54 | EOM 55 | exit 1 56 | fi 57 | case $RESOURCE_PATH in 58 | *.storyboard) 59 | echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" || true 60 | ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} 61 | ;; 62 | *.xib) 63 | echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" || true 64 | ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} 65 | ;; 66 | *.framework) 67 | echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" || true 68 | mkdir -p "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" 69 | echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" $RESOURCE_PATH ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" || true 70 | rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" 71 | ;; 72 | *.xcdatamodel) 73 | echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH"`.mom\"" || true 74 | xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodel`.mom" 75 | ;; 76 | *.xcdatamodeld) 77 | echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd\"" || true 78 | xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd" 79 | ;; 80 | *.xcmappingmodel) 81 | echo "xcrun mapc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm\"" || true 82 | xcrun mapc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm" 83 | ;; 84 | *.xcassets) 85 | ABSOLUTE_XCASSET_FILE="$RESOURCE_PATH" 86 | XCASSET_FILES+=("$ABSOLUTE_XCASSET_FILE") 87 | ;; 88 | *) 89 | echo "$RESOURCE_PATH" || true 90 | echo "$RESOURCE_PATH" >> "$RESOURCES_TO_COPY" 91 | ;; 92 | esac 93 | } 94 | 95 | mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" 96 | rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" 97 | if [[ "${ACTION}" == "install" ]] && [[ "${SKIP_INSTALL}" == "NO" ]]; then 98 | mkdir -p "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" 99 | rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" 100 | fi 101 | rm -f "$RESOURCES_TO_COPY" 102 | 103 | if [[ -n "${WRAPPER_EXTENSION}" ]] && [ "`xcrun --find actool`" ] && [ -n "${XCASSET_FILES:-}" ] 104 | then 105 | # Find all other xcassets (this unfortunately includes those of path pods and other targets). 106 | OTHER_XCASSETS=$(find "$PWD" -iname "*.xcassets" -type d) 107 | while read line; do 108 | if [[ $line != "${PODS_ROOT}*" ]]; then 109 | XCASSET_FILES+=("$line") 110 | fi 111 | done <<<"$OTHER_XCASSETS" 112 | 113 | if [ -z ${ASSETCATALOG_COMPILER_APPICON_NAME+x} ]; then 114 | printf "%s\0" "${XCASSET_FILES[@]}" | xargs -0 xcrun actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${!DEPLOYMENT_TARGET_SETTING_NAME}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" 115 | else 116 | printf "%s\0" "${XCASSET_FILES[@]}" | xargs -0 xcrun actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${!DEPLOYMENT_TARGET_SETTING_NAME}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" --app-icon "${ASSETCATALOG_COMPILER_APPICON_NAME}" --output-partial-info-plist "${TARGET_TEMP_DIR}/assetcatalog_generated_info_cocoapods.plist" 117 | fi 118 | fi 119 | -------------------------------------------------------------------------------- /Pods/Target Support Files/Pods-YBNetworkDemo/Pods-YBNetworkDemo.debug.xcconfig: -------------------------------------------------------------------------------- 1 | GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 2 | HEADER_SEARCH_PATHS = $(inherited) "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/AFNetworking" "${PODS_ROOT}/Headers/Public/YYCache" 3 | LIBRARY_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/AFNetworking" "${PODS_CONFIGURATION_BUILD_DIR}/YYCache" 4 | OTHER_CFLAGS = $(inherited) -isystem "${PODS_ROOT}/Headers/Public" -isystem "${PODS_ROOT}/Headers/Public/AFNetworking" -isystem "${PODS_ROOT}/Headers/Public/YYCache" 5 | OTHER_LDFLAGS = $(inherited) -ObjC -l"AFNetworking" -l"YYCache" -l"sqlite3" -framework "CoreFoundation" -framework "CoreGraphics" -framework "MobileCoreServices" -framework "QuartzCore" -framework "Security" -framework "SystemConfiguration" -framework "UIKit" 6 | PODS_BUILD_DIR = ${BUILD_DIR} 7 | PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) 8 | PODS_PODFILE_DIR_PATH = ${SRCROOT}/. 9 | PODS_ROOT = ${SRCROOT}/Pods 10 | -------------------------------------------------------------------------------- /Pods/Target Support Files/Pods-YBNetworkDemo/Pods-YBNetworkDemo.release.xcconfig: -------------------------------------------------------------------------------- 1 | GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 2 | HEADER_SEARCH_PATHS = $(inherited) "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/AFNetworking" "${PODS_ROOT}/Headers/Public/YYCache" 3 | LIBRARY_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/AFNetworking" "${PODS_CONFIGURATION_BUILD_DIR}/YYCache" 4 | OTHER_CFLAGS = $(inherited) -isystem "${PODS_ROOT}/Headers/Public" -isystem "${PODS_ROOT}/Headers/Public/AFNetworking" -isystem "${PODS_ROOT}/Headers/Public/YYCache" 5 | OTHER_LDFLAGS = $(inherited) -ObjC -l"AFNetworking" -l"YYCache" -l"sqlite3" -framework "CoreFoundation" -framework "CoreGraphics" -framework "MobileCoreServices" -framework "QuartzCore" -framework "Security" -framework "SystemConfiguration" -framework "UIKit" 6 | PODS_BUILD_DIR = ${BUILD_DIR} 7 | PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) 8 | PODS_PODFILE_DIR_PATH = ${SRCROOT}/. 9 | PODS_ROOT = ${SRCROOT}/Pods 10 | -------------------------------------------------------------------------------- /Pods/Target Support Files/YYCache/YYCache-dummy.m: -------------------------------------------------------------------------------- 1 | #import 2 | @interface PodsDummy_YYCache : NSObject 3 | @end 4 | @implementation PodsDummy_YYCache 5 | @end 6 | -------------------------------------------------------------------------------- /Pods/Target Support Files/YYCache/YYCache-prefix.pch: -------------------------------------------------------------------------------- 1 | #ifdef __OBJC__ 2 | #import 3 | #else 4 | #ifndef FOUNDATION_EXPORT 5 | #if defined(__cplusplus) 6 | #define FOUNDATION_EXPORT extern "C" 7 | #else 8 | #define FOUNDATION_EXPORT extern 9 | #endif 10 | #endif 11 | #endif 12 | 13 | -------------------------------------------------------------------------------- /Pods/Target Support Files/YYCache/YYCache.xcconfig: -------------------------------------------------------------------------------- 1 | CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/YYCache 2 | GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 3 | HEADER_SEARCH_PATHS = $(inherited) "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Private/YYCache" "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/YYCache" 4 | OTHER_LDFLAGS = -l"sqlite3" -framework "CoreFoundation" -framework "QuartzCore" -framework "UIKit" 5 | PODS_BUILD_DIR = ${BUILD_DIR} 6 | PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) 7 | PODS_ROOT = ${SRCROOT} 8 | PODS_TARGET_SRCROOT = ${PODS_ROOT}/YYCache 9 | PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} 10 | SKIP_INSTALL = YES 11 | -------------------------------------------------------------------------------- /Pods/YYCache/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 ibireme 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /Pods/YYCache/README.md: -------------------------------------------------------------------------------- 1 | YYCache 2 | ============== 3 | 4 | [![License MIT](https://img.shields.io/badge/license-MIT-green.svg?style=flat)](https://raw.githubusercontent.com/ibireme/YYCache/master/LICENSE)  5 | [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)  6 | [![CocoaPods](http://img.shields.io/cocoapods/v/YYCache.svg?style=flat)](http://cocoapods.org/?q= YYCache)  7 | [![CocoaPods](http://img.shields.io/cocoapods/p/YYCache.svg?style=flat)](http://cocoapods.org/?q= YYCache)  8 | [![Support](https://img.shields.io/badge/support-iOS%206%2B%20-blue.svg?style=flat)](https://www.apple.com/nl/ios/)  9 | [![Build Status](https://travis-ci.org/ibireme/YYCache.svg?branch=master)](https://travis-ci.org/ibireme/YYCache) 10 | 11 | High performance cache framework for iOS.
12 | (It's a component of [YYKit](https://github.com/ibireme/YYKit)) 13 | 14 | Performance 15 | ============== 16 | 17 | ![Memory cache benchmark result](https://raw.github.com/ibireme/YYCache/master/Benchmark/Result_memory.png 18 | ) 19 | 20 | ![Disk benchmark result](https://raw.github.com/ibireme/YYCache/master/Benchmark/Result_disk.png 21 | ) 22 | 23 | You may [download](http://www.sqlite.org/download.html) and compile the latest version of sqlite and ignore the libsqlite3.dylib in iOS system to get higher performance. 24 | 25 | See `Benchmark/CacheBenchmark.xcodeproj` for more benchmark case. 26 | 27 | 28 | Features 29 | ============== 30 | - **LRU**: Objects can be evicted with least-recently-used algorithm. 31 | - **Limitation**: Cache limitation can be controlled with count, cost, age and free space. 32 | - **Compatibility**: The API is similar to `NSCache`, all methods are thread-safe. 33 | - **Memory Cache** 34 | - **Release Control**: Objects can be released synchronously/asynchronously on main thread or background thread. 35 | - **Automatically Clear**: It can be configured to automatically evict objects when receive memory warning or app enter background. 36 | - **Disk Cache** 37 | - **Customization**: It supports custom archive and unarchive method to store object which does not adopt NSCoding. 38 | - **Storage Type Control**: It can automatically decide the storage type (sqlite / file) for each object to get 39 | better performance. 40 | 41 | 42 | Installation 43 | ============== 44 | 45 | ### CocoaPods 46 | 47 | 1. Add `pod 'YYCache'` to your Podfile. 48 | 2. Run `pod install` or `pod update`. 49 | 3. Import \. 50 | 51 | 52 | ### Carthage 53 | 54 | 1. Add `github "ibireme/YYCache"` to your Cartfile. 55 | 2. Run `carthage update --platform ios` and add the framework to your project. 56 | 3. Import \. 57 | 58 | 59 | ### Manually 60 | 61 | 1. Download all the files in the YYCache subdirectory. 62 | 2. Add the source files to your Xcode project. 63 | 3. Link with required frameworks: 64 | * UIKit 65 | * CoreFoundation 66 | * QuartzCore 67 | * sqlite3 68 | 4. Import `YYCache.h`. 69 | 70 | 71 | Documentation 72 | ============== 73 | Full API documentation is available on [CocoaDocs](http://cocoadocs.org/docsets/YYCache/).
74 | You can also install documentation locally using [appledoc](https://github.com/tomaz/appledoc). 75 | 76 | 77 | Requirements 78 | ============== 79 | This library requires `iOS 6.0+` and `Xcode 7.0+`. 80 | 81 | 82 | License 83 | ============== 84 | YYCache is provided under the MIT license. See LICENSE file for details. 85 | 86 | 87 |

88 | --- 89 | 中文介绍 90 | ============== 91 | 高性能 iOS 缓存框架。
92 | (该项目是 [YYKit](https://github.com/ibireme/YYKit) 组件之一) 93 | 94 | 性能 95 | ============== 96 | 97 | iPhone 6 上,内存缓存每秒响应次数 (越高越好): 98 | ![Memory cache benchmark result](https://raw.github.com/ibireme/YYCache/master/Benchmark/Result_memory.png 99 | ) 100 | 101 | iPhone 6 上,磁盘缓存每秒响应次数 (越高越好): 102 | ![Disk benchmark result](https://raw.github.com/ibireme/YYCache/master/Benchmark/Result_disk.png 103 | ) 104 | 105 | 推荐到 SQLite 官网[下载](http://www.sqlite.org/download.html)和编译最新的 SQLite,以替换 iOS 自带的 libsqlite3.dylib,以获得最高 1.5~3 倍的性能提升。 106 | 107 | 更多测试代码和用例见 `Benchmark/CacheBenchmark.xcodeproj`。 108 | 109 | 110 | 特性 111 | ============== 112 | - **LRU**: 缓存支持 LRU (least-recently-used) 淘汰算法。 113 | - **缓存控制**: 支持多种缓存控制方法:总数量、总大小、存活时间、空闲空间。 114 | - **兼容性**: API 基本和 `NSCache` 保持一致, 所有方法都是线程安全的。 115 | - **内存缓存** 116 | - **对象释放控制**: 对象的释放(release) 可以配置为同步或异步进行,可以配置在主线程或后台线程进行。 117 | - **自动清空**: 当收到内存警告或 App 进入后台时,缓存可以配置为自动清空。 118 | - **磁盘缓存** 119 | - **可定制性**: 磁盘缓存支持自定义的归档解档方法,以支持那些没有实现 NSCoding 协议的对象。 120 | - **存储类型控制**: 磁盘缓存支持对每个对象的存储类型 (SQLite/文件) 进行自动或手动控制,以获得更高的存取性能。 121 | 122 | 123 | 安装 124 | ============== 125 | 126 | ### CocoaPods 127 | 128 | 1. 在 Podfile 中添加 `pod 'YYCache'`。 129 | 2. 执行 `pod install` 或 `pod update`。 130 | 3. 导入 \。 131 | 132 | 133 | ### Carthage 134 | 135 | 1. 在 Cartfile 中添加 `github "ibireme/YYCache"`。 136 | 2. 执行 `carthage update --platform ios` 并将生成的 framework 添加到你的工程。 137 | 3. 导入 \。 138 | 139 | 140 | ### 手动安装 141 | 142 | 1. 下载 YYCache 文件夹内的所有内容。 143 | 2. 将 YYCache 内的源文件添加(拖放)到你的工程。 144 | 3. 链接以下的 frameworks: 145 | * UIKit 146 | * CoreFoundation 147 | * QuartzCore 148 | * sqlite3 149 | 4. 导入 `YYCache.h`。 150 | 151 | 152 | 文档 153 | ============== 154 | 你可以在 [CocoaDocs](http://cocoadocs.org/docsets/YYCache/) 查看在线 API 文档,也可以用 [appledoc](https://github.com/tomaz/appledoc) 本地生成文档。 155 | 156 | 157 | 系统要求 158 | ============== 159 | 该项目最低支持 `iOS 6.0` 和 `Xcode 7.0`。 160 | 161 | 162 | 许可证 163 | ============== 164 | YYCache 使用 MIT 许可证,详情见 LICENSE 文件。 165 | 166 | 167 | 相关链接 168 | ============== 169 | [YYCache 设计思路与技术细节](http://blog.ibireme.com/2015/10/26/yycache/) 170 | 171 | 172 | -------------------------------------------------------------------------------- /Pods/YYCache/YYCache/YYCache.h: -------------------------------------------------------------------------------- 1 | // 2 | // YYCache.h 3 | // YYCache 4 | // 5 | // Created by ibireme on 15/2/13. 6 | // Copyright (c) 2015 ibireme. 7 | // 8 | // This source code is licensed under the MIT-style license found in the 9 | // LICENSE file in the root directory of this source tree. 10 | // 11 | 12 | #import 13 | 14 | #if __has_include() 15 | FOUNDATION_EXPORT double YYCacheVersionNumber; 16 | FOUNDATION_EXPORT const unsigned char YYCacheVersionString[]; 17 | #import 18 | #import 19 | #import 20 | #elif __has_include() 21 | #import 22 | #import 23 | #import 24 | #else 25 | #import "YYMemoryCache.h" 26 | #import "YYDiskCache.h" 27 | #import "YYKVStorage.h" 28 | #endif 29 | 30 | NS_ASSUME_NONNULL_BEGIN 31 | 32 | 33 | /** 34 | `YYCache` is a thread safe key-value cache. 35 | 36 | It use `YYMemoryCache` to store objects in a small and fast memory cache, 37 | and use `YYDiskCache` to persisting objects to a large and slow disk cache. 38 | See `YYMemoryCache` and `YYDiskCache` for more information. 39 | */ 40 | @interface YYCache : NSObject 41 | 42 | /** The name of the cache, readonly. */ 43 | @property (copy, readonly) NSString *name; 44 | 45 | /** The underlying memory cache. see `YYMemoryCache` for more information.*/ 46 | @property (strong, readonly) YYMemoryCache *memoryCache; 47 | 48 | /** The underlying disk cache. see `YYDiskCache` for more information.*/ 49 | @property (strong, readonly) YYDiskCache *diskCache; 50 | 51 | /** 52 | Create a new instance with the specified name. 53 | Multiple instances with the same name will make the cache unstable. 54 | 55 | @param name The name of the cache. It will create a dictionary with the name in 56 | the app's caches dictionary for disk cache. Once initialized you should not 57 | read and write to this directory. 58 | @result A new cache object, or nil if an error occurs. 59 | */ 60 | - (nullable instancetype)initWithName:(NSString *)name; 61 | 62 | /** 63 | Create a new instance with the specified path. 64 | Multiple instances with the same name will make the cache unstable. 65 | 66 | @param path Full path of a directory in which the cache will write data. 67 | Once initialized you should not read and write to this directory. 68 | @result A new cache object, or nil if an error occurs. 69 | */ 70 | - (nullable instancetype)initWithPath:(NSString *)path NS_DESIGNATED_INITIALIZER; 71 | 72 | /** 73 | Convenience Initializers 74 | Create a new instance with the specified name. 75 | Multiple instances with the same name will make the cache unstable. 76 | 77 | @param name The name of the cache. It will create a dictionary with the name in 78 | the app's caches dictionary for disk cache. Once initialized you should not 79 | read and write to this directory. 80 | @result A new cache object, or nil if an error occurs. 81 | */ 82 | + (nullable instancetype)cacheWithName:(NSString *)name; 83 | 84 | /** 85 | Convenience Initializers 86 | Create a new instance with the specified path. 87 | Multiple instances with the same name will make the cache unstable. 88 | 89 | @param path Full path of a directory in which the cache will write data. 90 | Once initialized you should not read and write to this directory. 91 | @result A new cache object, or nil if an error occurs. 92 | */ 93 | + (nullable instancetype)cacheWithPath:(NSString *)path; 94 | 95 | - (instancetype)init UNAVAILABLE_ATTRIBUTE; 96 | + (instancetype)new UNAVAILABLE_ATTRIBUTE; 97 | 98 | #pragma mark - Access Methods 99 | ///============================================================================= 100 | /// @name Access Methods 101 | ///============================================================================= 102 | 103 | /** 104 | Returns a boolean value that indicates whether a given key is in cache. 105 | This method may blocks the calling thread until file read finished. 106 | 107 | @param key A string identifying the value. If nil, just return NO. 108 | @return Whether the key is in cache. 109 | */ 110 | - (BOOL)containsObjectForKey:(NSString *)key; 111 | 112 | /** 113 | Returns a boolean value with the block that indicates whether a given key is in cache. 114 | This method returns immediately and invoke the passed block in background queue 115 | when the operation finished. 116 | 117 | @param key A string identifying the value. If nil, just return NO. 118 | @param block A block which will be invoked in background queue when finished. 119 | */ 120 | - (void)containsObjectForKey:(NSString *)key withBlock:(nullable void(^)(NSString *key, BOOL contains))block; 121 | 122 | /** 123 | Returns the value associated with a given key. 124 | This method may blocks the calling thread until file read finished. 125 | 126 | @param key A string identifying the value. If nil, just return nil. 127 | @return The value associated with key, or nil if no value is associated with key. 128 | */ 129 | - (nullable id)objectForKey:(NSString *)key; 130 | 131 | /** 132 | Returns the value associated with a given key. 133 | This method returns immediately and invoke the passed block in background queue 134 | when the operation finished. 135 | 136 | @param key A string identifying the value. If nil, just return nil. 137 | @param block A block which will be invoked in background queue when finished. 138 | */ 139 | - (void)objectForKey:(NSString *)key withBlock:(nullable void(^)(NSString *key, id object))block; 140 | 141 | /** 142 | Sets the value of the specified key in the cache. 143 | This method may blocks the calling thread until file write finished. 144 | 145 | @param object The object to be stored in the cache. If nil, it calls `removeObjectForKey:`. 146 | @param key The key with which to associate the value. If nil, this method has no effect. 147 | */ 148 | - (void)setObject:(nullable id)object forKey:(NSString *)key; 149 | 150 | /** 151 | Sets the value of the specified key in the cache. 152 | This method returns immediately and invoke the passed block in background queue 153 | when the operation finished. 154 | 155 | @param object The object to be stored in the cache. If nil, it calls `removeObjectForKey:`. 156 | @param block A block which will be invoked in background queue when finished. 157 | */ 158 | - (void)setObject:(nullable id)object forKey:(NSString *)key withBlock:(nullable void(^)(void))block; 159 | 160 | /** 161 | Removes the value of the specified key in the cache. 162 | This method may blocks the calling thread until file delete finished. 163 | 164 | @param key The key identifying the value to be removed. If nil, this method has no effect. 165 | */ 166 | - (void)removeObjectForKey:(NSString *)key; 167 | 168 | /** 169 | Removes the value of the specified key in the cache. 170 | This method returns immediately and invoke the passed block in background queue 171 | when the operation finished. 172 | 173 | @param key The key identifying the value to be removed. If nil, this method has no effect. 174 | @param block A block which will be invoked in background queue when finished. 175 | */ 176 | - (void)removeObjectForKey:(NSString *)key withBlock:(nullable void(^)(NSString *key))block; 177 | 178 | /** 179 | Empties the cache. 180 | This method may blocks the calling thread until file delete finished. 181 | */ 182 | - (void)removeAllObjects; 183 | 184 | /** 185 | Empties the cache. 186 | This method returns immediately and invoke the passed block in background queue 187 | when the operation finished. 188 | 189 | @param block A block which will be invoked in background queue when finished. 190 | */ 191 | - (void)removeAllObjectsWithBlock:(void(^)(void))block; 192 | 193 | /** 194 | Empties the cache with block. 195 | This method returns immediately and executes the clear operation with block in background. 196 | 197 | @warning You should not send message to this instance in these blocks. 198 | @param progress This block will be invoked during removing, pass nil to ignore. 199 | @param end This block will be invoked at the end, pass nil to ignore. 200 | */ 201 | - (void)removeAllObjectsWithProgressBlock:(nullable void(^)(int removedCount, int totalCount))progress 202 | endBlock:(nullable void(^)(BOOL error))end; 203 | 204 | @end 205 | 206 | NS_ASSUME_NONNULL_END 207 | -------------------------------------------------------------------------------- /Pods/YYCache/YYCache/YYCache.m: -------------------------------------------------------------------------------- 1 | // 2 | // YYCache.m 3 | // YYCache 4 | // 5 | // Created by ibireme on 15/2/13. 6 | // Copyright (c) 2015 ibireme. 7 | // 8 | // This source code is licensed under the MIT-style license found in the 9 | // LICENSE file in the root directory of this source tree. 10 | // 11 | 12 | #import "YYCache.h" 13 | #import "YYMemoryCache.h" 14 | #import "YYDiskCache.h" 15 | 16 | @implementation YYCache 17 | 18 | - (instancetype) init { 19 | NSLog(@"Use \"initWithName\" or \"initWithPath\" to create YYCache instance."); 20 | return [self initWithPath:@""]; 21 | } 22 | 23 | - (instancetype)initWithName:(NSString *)name { 24 | if (name.length == 0) return nil; 25 | NSString *cacheFolder = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]; 26 | NSString *path = [cacheFolder stringByAppendingPathComponent:name]; 27 | return [self initWithPath:path]; 28 | } 29 | 30 | - (instancetype)initWithPath:(NSString *)path { 31 | if (path.length == 0) return nil; 32 | YYDiskCache *diskCache = [[YYDiskCache alloc] initWithPath:path]; 33 | if (!diskCache) return nil; 34 | NSString *name = [path lastPathComponent]; 35 | YYMemoryCache *memoryCache = [YYMemoryCache new]; 36 | memoryCache.name = name; 37 | 38 | self = [super init]; 39 | _name = name; 40 | _diskCache = diskCache; 41 | _memoryCache = memoryCache; 42 | return self; 43 | } 44 | 45 | + (instancetype)cacheWithName:(NSString *)name { 46 | return [[self alloc] initWithName:name]; 47 | } 48 | 49 | + (instancetype)cacheWithPath:(NSString *)path { 50 | return [[self alloc] initWithPath:path]; 51 | } 52 | 53 | - (BOOL)containsObjectForKey:(NSString *)key { 54 | return [_memoryCache containsObjectForKey:key] || [_diskCache containsObjectForKey:key]; 55 | } 56 | 57 | - (void)containsObjectForKey:(NSString *)key withBlock:(void (^)(NSString *key, BOOL contains))block { 58 | if (!block) return; 59 | 60 | if ([_memoryCache containsObjectForKey:key]) { 61 | dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 62 | block(key, YES); 63 | }); 64 | } else { 65 | [_diskCache containsObjectForKey:key withBlock:block]; 66 | } 67 | } 68 | 69 | - (id)objectForKey:(NSString *)key { 70 | id object = [_memoryCache objectForKey:key]; 71 | if (!object) { 72 | object = [_diskCache objectForKey:key]; 73 | if (object) { 74 | [_memoryCache setObject:object forKey:key]; 75 | } 76 | } 77 | return object; 78 | } 79 | 80 | - (void)objectForKey:(NSString *)key withBlock:(void (^)(NSString *key, id object))block { 81 | if (!block) return; 82 | id object = [_memoryCache objectForKey:key]; 83 | if (object) { 84 | dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 85 | block(key, object); 86 | }); 87 | } else { 88 | [_diskCache objectForKey:key withBlock:^(NSString *key, id object) { 89 | if (object && ![_memoryCache objectForKey:key]) { 90 | [_memoryCache setObject:object forKey:key]; 91 | } 92 | block(key, object); 93 | }]; 94 | } 95 | } 96 | 97 | - (void)setObject:(id)object forKey:(NSString *)key { 98 | [_memoryCache setObject:object forKey:key]; 99 | [_diskCache setObject:object forKey:key]; 100 | } 101 | 102 | - (void)setObject:(id)object forKey:(NSString *)key withBlock:(void (^)(void))block { 103 | [_memoryCache setObject:object forKey:key]; 104 | [_diskCache setObject:object forKey:key withBlock:block]; 105 | } 106 | 107 | - (void)removeObjectForKey:(NSString *)key { 108 | [_memoryCache removeObjectForKey:key]; 109 | [_diskCache removeObjectForKey:key]; 110 | } 111 | 112 | - (void)removeObjectForKey:(NSString *)key withBlock:(void (^)(NSString *key))block { 113 | [_memoryCache removeObjectForKey:key]; 114 | [_diskCache removeObjectForKey:key withBlock:block]; 115 | } 116 | 117 | - (void)removeAllObjects { 118 | [_memoryCache removeAllObjects]; 119 | [_diskCache removeAllObjects]; 120 | } 121 | 122 | - (void)removeAllObjectsWithBlock:(void(^)(void))block { 123 | [_memoryCache removeAllObjects]; 124 | [_diskCache removeAllObjectsWithBlock:block]; 125 | } 126 | 127 | - (void)removeAllObjectsWithProgressBlock:(void(^)(int removedCount, int totalCount))progress 128 | endBlock:(void(^)(BOOL error))end { 129 | [_memoryCache removeAllObjects]; 130 | [_diskCache removeAllObjectsWithProgressBlock:progress endBlock:end]; 131 | 132 | } 133 | 134 | - (NSString *)description { 135 | if (_name) return [NSString stringWithFormat:@"<%@: %p> (%@)", self.class, self, _name]; 136 | else return [NSString stringWithFormat:@"<%@: %p>", self.class, self]; 137 | } 138 | 139 | @end 140 | -------------------------------------------------------------------------------- /Pods/YYCache/YYCache/YYMemoryCache.h: -------------------------------------------------------------------------------- 1 | // 2 | // YYMemoryCache.h 3 | // YYCache 4 | // 5 | // Created by ibireme on 15/2/7. 6 | // Copyright (c) 2015 ibireme. 7 | // 8 | // This source code is licensed under the MIT-style license found in the 9 | // LICENSE file in the root directory of this source tree. 10 | // 11 | 12 | #import 13 | 14 | NS_ASSUME_NONNULL_BEGIN 15 | 16 | /** 17 | YYMemoryCache is a fast in-memory cache that stores key-value pairs. 18 | In contrast to NSDictionary, keys are retained and not copied. 19 | The API and performance is similar to `NSCache`, all methods are thread-safe. 20 | 21 | YYMemoryCache objects differ from NSCache in a few ways: 22 | 23 | * It uses LRU (least-recently-used) to remove objects; NSCache's eviction method 24 | is non-deterministic. 25 | * It can be controlled by cost, count and age; NSCache's limits are imprecise. 26 | * It can be configured to automatically evict objects when receive memory 27 | warning or app enter background. 28 | 29 | The time of `Access Methods` in YYMemoryCache is typically in constant time (O(1)). 30 | */ 31 | @interface YYMemoryCache : NSObject 32 | 33 | #pragma mark - Attribute 34 | ///============================================================================= 35 | /// @name Attribute 36 | ///============================================================================= 37 | 38 | /** The name of the cache. Default is nil. */ 39 | @property (nullable, copy) NSString *name; 40 | 41 | /** The number of objects in the cache (read-only) */ 42 | @property (readonly) NSUInteger totalCount; 43 | 44 | /** The total cost of objects in the cache (read-only). */ 45 | @property (readonly) NSUInteger totalCost; 46 | 47 | 48 | #pragma mark - Limit 49 | ///============================================================================= 50 | /// @name Limit 51 | ///============================================================================= 52 | 53 | /** 54 | The maximum number of objects the cache should hold. 55 | 56 | @discussion The default value is NSUIntegerMax, which means no limit. 57 | This is not a strict limit—if the cache goes over the limit, some objects in the 58 | cache could be evicted later in backgound thread. 59 | */ 60 | @property NSUInteger countLimit; 61 | 62 | /** 63 | The maximum total cost that the cache can hold before it starts evicting objects. 64 | 65 | @discussion The default value is NSUIntegerMax, which means no limit. 66 | This is not a strict limit—if the cache goes over the limit, some objects in the 67 | cache could be evicted later in backgound thread. 68 | */ 69 | @property NSUInteger costLimit; 70 | 71 | /** 72 | The maximum expiry time of objects in cache. 73 | 74 | @discussion The default value is DBL_MAX, which means no limit. 75 | This is not a strict limit—if an object goes over the limit, the object could 76 | be evicted later in backgound thread. 77 | */ 78 | @property NSTimeInterval ageLimit; 79 | 80 | /** 81 | The auto trim check time interval in seconds. Default is 5.0. 82 | 83 | @discussion The cache holds an internal timer to check whether the cache reaches 84 | its limits, and if the limit is reached, it begins to evict objects. 85 | */ 86 | @property NSTimeInterval autoTrimInterval; 87 | 88 | /** 89 | If `YES`, the cache will remove all objects when the app receives a memory warning. 90 | The default value is `YES`. 91 | */ 92 | @property BOOL shouldRemoveAllObjectsOnMemoryWarning; 93 | 94 | /** 95 | If `YES`, The cache will remove all objects when the app enter background. 96 | The default value is `YES`. 97 | */ 98 | @property BOOL shouldRemoveAllObjectsWhenEnteringBackground; 99 | 100 | /** 101 | A block to be executed when the app receives a memory warning. 102 | The default value is nil. 103 | */ 104 | @property (nullable, copy) void(^didReceiveMemoryWarningBlock)(YYMemoryCache *cache); 105 | 106 | /** 107 | A block to be executed when the app enter background. 108 | The default value is nil. 109 | */ 110 | @property (nullable, copy) void(^didEnterBackgroundBlock)(YYMemoryCache *cache); 111 | 112 | /** 113 | If `YES`, the key-value pair will be released on main thread, otherwise on 114 | background thread. Default is NO. 115 | 116 | @discussion You may set this value to `YES` if the key-value object contains 117 | the instance which should be released in main thread (such as UIView/CALayer). 118 | */ 119 | @property BOOL releaseOnMainThread; 120 | 121 | /** 122 | If `YES`, the key-value pair will be released asynchronously to avoid blocking 123 | the access methods, otherwise it will be released in the access method 124 | (such as removeObjectForKey:). Default is YES. 125 | */ 126 | @property BOOL releaseAsynchronously; 127 | 128 | 129 | #pragma mark - Access Methods 130 | ///============================================================================= 131 | /// @name Access Methods 132 | ///============================================================================= 133 | 134 | /** 135 | Returns a Boolean value that indicates whether a given key is in cache. 136 | 137 | @param key An object identifying the value. If nil, just return `NO`. 138 | @return Whether the key is in cache. 139 | */ 140 | - (BOOL)containsObjectForKey:(id)key; 141 | 142 | /** 143 | Returns the value associated with a given key. 144 | 145 | @param key An object identifying the value. If nil, just return nil. 146 | @return The value associated with key, or nil if no value is associated with key. 147 | */ 148 | - (nullable id)objectForKey:(id)key; 149 | 150 | /** 151 | Sets the value of the specified key in the cache (0 cost). 152 | 153 | @param object The object to be stored in the cache. If nil, it calls `removeObjectForKey:`. 154 | @param key The key with which to associate the value. If nil, this method has no effect. 155 | @discussion Unlike an NSMutableDictionary object, a cache does not copy the key 156 | objects that are put into it. 157 | */ 158 | - (void)setObject:(nullable id)object forKey:(id)key; 159 | 160 | /** 161 | Sets the value of the specified key in the cache, and associates the key-value 162 | pair with the specified cost. 163 | 164 | @param object The object to store in the cache. If nil, it calls `removeObjectForKey`. 165 | @param key The key with which to associate the value. If nil, this method has no effect. 166 | @param cost The cost with which to associate the key-value pair. 167 | @discussion Unlike an NSMutableDictionary object, a cache does not copy the key 168 | objects that are put into it. 169 | */ 170 | - (void)setObject:(nullable id)object forKey:(id)key withCost:(NSUInteger)cost; 171 | 172 | /** 173 | Removes the value of the specified key in the cache. 174 | 175 | @param key The key identifying the value to be removed. If nil, this method has no effect. 176 | */ 177 | - (void)removeObjectForKey:(id)key; 178 | 179 | /** 180 | Empties the cache immediately. 181 | */ 182 | - (void)removeAllObjects; 183 | 184 | 185 | #pragma mark - Trim 186 | ///============================================================================= 187 | /// @name Trim 188 | ///============================================================================= 189 | 190 | /** 191 | Removes objects from the cache with LRU, until the `totalCount` is below or equal to 192 | the specified value. 193 | @param count The total count allowed to remain after the cache has been trimmed. 194 | */ 195 | - (void)trimToCount:(NSUInteger)count; 196 | 197 | /** 198 | Removes objects from the cache with LRU, until the `totalCost` is or equal to 199 | the specified value. 200 | @param cost The total cost allowed to remain after the cache has been trimmed. 201 | */ 202 | - (void)trimToCost:(NSUInteger)cost; 203 | 204 | /** 205 | Removes objects from the cache with LRU, until all expiry objects removed by the 206 | specified value. 207 | @param age The maximum age (in seconds) of objects. 208 | */ 209 | - (void)trimToAge:(NSTimeInterval)age; 210 | 211 | @end 212 | 213 | NS_ASSUME_NONNULL_END 214 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # YBNetwork 2 | 3 | [![Cocoapods](https://img.shields.io/cocoapods/v/YBNetwork.svg)](https://cocoapods.org/pods/YBNetwork)  4 | [![Cocoapods](https://img.shields.io/cocoapods/p/YBNetwork.svg)](https://github.com/indulgeIn/YBNetwork)  5 | [![License](https://img.shields.io/github/license/indulgeIn/YBNetwork.svg)](https://github.com/indulgeIn/YBNetwork)  6 | 7 | 基于 AFNetworking 二次封装,功能细致易拓展。 8 | 9 | 设计原理博客:[谈谈 iOS 网络层设计](https://www.jianshu.com/p/fe0dd50d0af1) 10 | 11 | 参考思路:[iOS应用架构谈 网络层设计方案](https://casatwy.com/iosying-yong-jia-gou-tan-wang-luo-ceng-she-ji-fang-an.html) 12 |
参考源码:[YTKNetwork](https://github.com/yuantiku/YTKNetwork) [CTNetworking](https://github.com/casatwy/CTNetworking) 13 | 14 | 15 | ## 特性 16 | 17 | - 支持缓存写入模式、读取模式、有效时长等自定义配置 (同时享有来着 YYCache 的优越性能) 18 | - 支持网络落地重定向 19 | - 支持发起请求和响应回调的预处理 20 | - 支持网络落地异步重定向 21 | - 重复请求处理策略选择 22 | - 网络请求释放策略选择 23 | - 支持 Block 和 Delegate 回调方式 24 | - 代码层级简单,便于功能拓展 25 | 26 | 27 | ## 安装 28 | 29 | ### CocoaPods 30 | 31 | 1. 在 Podfile 中添加 `pod 'YBNetwork'`。 32 | 2. 执行 `pod install` 或 `pod update`。 33 | 34 | 若搜索不到库,可使用 rm ~/Library/Caches/CocoaPods/search_index.json 移除本地索引然后再执行安装,或者更新一下 CocoaPods 版本。 35 | 36 | ### 手动导入 37 | 38 | 1. 下载 YBNetwork 文件夹所有内容并且拖入你的工程中。 39 | 2. 链接以下 frameworks: 40 | * AFNetworking 41 | * YYCache 42 | 43 | 44 | ## 用法 45 | 46 | 可下载 DEMO 查看示例。 47 | 48 | ### 基本使用 49 | 50 | #### 1、第一步 51 | 52 | 创建子类继承自`YBBaseRequest`,并且在构造方法中初始化一些通用的配置 (比如服务器地址、解析器) 53 | ``` 54 | @interface DefaultServerRequest : YBBaseRequest 55 | @end 56 | 57 | @implementation DefaultServerRequest 58 | - (instancetype)init { 59 | self = [super init]; 60 | if (self) { 61 | self.baseURI = @"https://www.baidu.com"; 62 | } 63 | return self; 64 | } 65 | - (AFHTTPRequestSerializer *)requestSerializer {...} 66 | - (AFHTTPResponseSerializer *)responseSerializer {...} 67 | @end 68 | ``` 69 | 如果项目接口来自不同的接口团队(往往通用配置不同),那么就为每一个接口团队子类化一个`YBBaseRequest`,然后分别配置通用配置。 70 | 71 | #### 2、第二步 72 | 73 | 创建具体接口配置,有两种方式,一种是直接实例化`DefaultServerRequest`,一种是继续子类化`DefaultServerRequest`: 74 | ``` 75 | //直接实例化 76 | DefaultServerRequest *request = [DefaultServerRequest new]; 77 | request.requestMethod = YBRequestMethodGET; 78 | request.requestURI = @"..."; 79 | request.requestParameter = @{...}; 80 | ``` 81 | ``` 82 | //继续子类化 83 | @interface SearchWeatherRequest : DefaultServerRequest 84 | @end 85 | @implementation SearchWeatherRequest 86 | - (YBRequestMethod)requestMethod { 87 | return YBRequestMethodGET; 88 | } 89 | - (NSString *)requestURI { 90 | return @"..."; 91 | } 92 | - (NSDictionary *)requestParameter { 93 | return @{...}; 94 | } 95 | @end 96 | ``` 97 | 98 | #### 3、第三步 99 | 100 | 发起网络请求,设置回调: 101 | ``` 102 | //Block 103 | __weak typeof(self) weakSelf = self; 104 | [request startWithSuccess:^(YBNetworkResponse * _Nonnull response) { 105 | __strong typeof(weakSelf) self = weakSelf; 106 | if (!self) return; 107 | } failure:^(YBNetworkResponse * _Nonnull response) { 108 | __strong typeof(weakSelf) self = weakSelf; 109 | if (!self) return; 110 | }]; 111 | 112 | //Delegate 113 | request.delegate = self; //代理方法回调结果 114 | [request start]; 115 | ``` 116 | 目前的内部实现是,若有重复的网络请求发起,将只回调最新的 Block,而 Delegate 方式会每次都回调。 117 | 118 | 注意:虽然 Block 方式就算不弱引用`self`也不会循环引用 (内部会回调完成后破除循环),但是为了避免延长`self`的生命周期,强烈建议使用弱引用,不然可能会导致网络请求释放策略失效。如果你是主导者,那么可以规定必须使用 Delegate 方式回调,从源头上避免延长网络响应接受者生命周期。 119 | 120 | 121 | 122 | ### 请求和响应预处理 123 | 124 | 往往我们需要为所有请求参数添加一些字段,比如设备ID,用户ID。 125 | 只需要在一级子类`DefaultServerRequest`中重载父类方法就行了: 126 | ``` 127 | @implementation DefaultServerRequest 128 | ... 129 | //请求预处理 130 | - (NSDictionary *)yb_preprocessParameter:(NSDictionary *)parameter { 131 | //预处理所有请求参数 132 | } 133 | - (NSString *)yb_preprocessURLString:(NSString *)URLString { 134 | //预处理所有请求URL字符串 135 | } 136 | //请求响应预处理 137 | - (void)yb_preprocessSuccessInChildThreadWithResponse:(YBNetworkResponse *)response { 138 | //预处理请求成功 139 | } 140 | - (void)yb_preprocessSuccessInMainThreadWithResponse:(YBNetworkResponse *)response { 141 | //预处理请求成功 142 | } 143 | ... 144 | @end 145 | ``` 146 | 147 | 148 | ### 重定向 149 | 150 | 网络落地重定向使用此方法: 151 | ``` 152 | - (void)yb_redirection:(void (^)(YBRequestRedirection))redirection response:(YBNetworkResponse *)response { 153 | // 同步或异步的做一些事情 154 | redirection(YBRequestRedirectionSuccess); 155 | } 156 | ``` 157 | 使用`redirection`闭包来达到可异步重定向的能力,在这之间可以做一些具体网络接口无感知的逻辑。 158 | 159 | 160 | ### 为响应对象添加属性 161 | 162 | `YBNetworkResponse` 包含必要的响应数据,可以添加额外属性,在网络响应预处理时为这些属性赋值,那么具体接口调用方就可以很方便的拿到这些处理后的值了。建议创建一个`YBNetworkResponse`的分类,使用 Runtime 的关联属性来拓展。 163 | 164 | 165 | ### 缓存处理 166 | 167 | 缓存处理配置都在`request.cacheHandler`变量`YBNetworkCache`类中,支持以下配置: 168 | - 内存/磁盘存储方式 169 | - 缓存命中后是否继续发起网络请求 170 | - 缓存的有效时长 171 | - 定制缓存的 key 172 | - 直接配置 YYCache 173 | 174 | #### 缓存有效性验证 175 | 176 | 内部会在业务处理完成网络响应数据后尝试进行缓存,且提供一个`shouldCacheBlock`可根据请求响应成功数据判断是否需要缓存(比如仅当 `code == 0` 时数据有效允许缓存)。 177 | 178 | 179 | ### 重复网络请求处理策略 180 | 181 | `request.repeatStrategy`变量配置,三种策略: 182 | 1. 允许重复网络请求 183 | 2. 取消最旧的网络请求 184 | 3. 取消最新的网络请求 185 | 186 | 举几个例子,当接口数据并不会在短时间变化时,重复发起网络请求就会浪费网络资源,可以选择方案 2 或 3;比如在搜索业务中,用户往往频繁的调用搜索接口,而发起一次搜索时,之前的搜索请求一般是没有意义了,就可以选用方案 2。 187 | 188 | 189 | ### 网络请求释放策略 190 | `request.releaseStrategy`变量配置,有几种方式可以选择: 191 | 1. 网络任务会持有 YBBaseRequest 实例,网络任务完成 YBBaseRequest 实例才会释放 192 | 2. 网络请求将随着 YBBaseRequest 实例的释放而取消 193 | 3. 网络请求和 YBBaseRequest 实例无关联 194 | 195 | 举几个例子,若你的控制器出栈以后希望取消未落地的网络请求,那么就使用方案 2,注意管理好 YBBaseRequest 的生命周期就行了;若你的网络请求是不论如何都不希望它取消的,那么使用方案 3;若你希望网络请求任务始终持有 YBBaseRequest 实例避免它提前释放,那么使用方案 1。 196 | 197 | 198 | ## 业务使用 Tips 199 | 200 | #### 1、使用 block 回调注意事项 201 | - 外部变量和 block 相互强持有也没关系,在网络回调完成过后组件会断开循环引用。 202 | - 尽量保证闭包内部捕获的变量是弱引用,避免延长被捕获变量的生命周期。 203 | 204 | #### 2、使用 delegate 回调注意事项 205 | 当多个 request 的代理都是同一个对象时,需要通过返回的 request 判断具体网络请求;所以若使用代理回调建议外部应该持有这个 request 便于比较。 206 | 207 | #### 3、重复请求 208 | 只需要持有 request,当对同一个 reqeust 多次进行 start 发起网络请求时,组件提供的几种重复请求策略便可以工作了。 209 | 210 | #### 4、网络安全落地 211 | 若使用 block 方式回调并且 block 强持有了外部变量,那么在网络结束之前外部变量不会释放。弱外部变量在业务中已经不存在了(比如出栈了),那么此时回调会出现隐患(最常见的就是野指针)。 212 | 213 | - 使用 block 回调时,最好做一下业务落脚点所有变量是否可用的判断(回调提取一个方法能减少判断,这时不如用 delegate 回调)。 214 | - 使用 delegate 回调只需要保证代理者的可用性,所以比较安全。 215 | - 在 request 未持有外部变量时,在外部变量 `dealloc` 时调用 request 的 `cancel` 方法可以取消网络请求,这样就不会有回调了,保证安全。 216 | - 更便捷的方法是使用“网络请求将随着 request 实例的释放而取消”的策略(`request.releaseStrategy`),然后 reqeust 释放时网络请求将自动取消。 217 | 218 | 219 | -------------------------------------------------------------------------------- /YBNetwork.podspec: -------------------------------------------------------------------------------- 1 | 2 | 3 | Pod::Spec.new do |s| 4 | 5 | 6 | s.name = "YBNetwork" 7 | s.version = "1.0.6" 8 | s.summary = "基于 AFNetworking 网络中间层,注重性能,设计简洁,易于拓展" 9 | s.description = <<-DESC 10 | 基于 AFNetworking 网络中间层,注重性能,设计简洁,易于拓展。 11 | DESC 12 | 13 | s.homepage = "https://github.com/indulgeIn" 14 | 15 | s.license = "MIT" 16 | 17 | s.author = { "杨波" => "1106355439@qq.com" } 18 | 19 | s.platform = :ios, "8.0" 20 | 21 | s.source = { :git => "https://github.com/indulgeIn/YBNetwork.git", :tag => "#{s.version}" } 22 | 23 | s.source_files = "YBNetwork/**/*.{h,m}" 24 | 25 | s.dependency 'AFNetworking' 26 | s.dependency 'YYCache', '~>1.0.4' 27 | 28 | s.requires_arc = true 29 | 30 | end 31 | -------------------------------------------------------------------------------- /YBNetwork/Cache/YBNetworkCache+Internal.h: -------------------------------------------------------------------------------- 1 | // 2 | // YBNetworkCache+Internal.h 3 | // YBNetwork 4 | // 5 | // Created by 波儿菜 on 2019/4/7. 6 | // Copyright © 2019 波儿菜. All rights reserved. 7 | // 8 | 9 | #import "YBNetworkCache.h" 10 | 11 | NS_ASSUME_NONNULL_BEGIN 12 | 13 | @interface YBNetworkCache () 14 | 15 | /** 16 | 存数据 17 | 18 | @param object 数据对象 19 | @param key 标识 20 | */ 21 | - (void)setObject:(nullable id)object forKey:(id)key; 22 | 23 | /** 24 | 取数据 25 | 26 | @param key 标识 27 | @param block 回调 (主线程) 28 | */ 29 | - (void)objectForKey:(NSString *)key withBlock:(void(^)(NSString *key, id _Nullable object))block; 30 | 31 | @end 32 | 33 | NS_ASSUME_NONNULL_END 34 | -------------------------------------------------------------------------------- /YBNetwork/Cache/YBNetworkCache.h: -------------------------------------------------------------------------------- 1 | // 2 | // YBNetworkCache.h 3 | // YBNetwork 4 | // 5 | // Created by 波儿菜 on 2019/4/5. 6 | // Copyright © 2019 波儿菜. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "YBNetworkDefine.h" 11 | 12 | #if __has_include() 13 | #import 14 | #else 15 | #import "YYCache.h" 16 | #endif 17 | 18 | @class YBNetworkResponse; 19 | 20 | NS_ASSUME_NONNULL_BEGIN 21 | 22 | @interface YBNetworkCache : NSObject 23 | 24 | /** 缓存存储模式 (默认不缓存) */ 25 | @property (nonatomic, assign) YBNetworkCacheWriteMode writeMode; 26 | 27 | /** 缓存读取模式 (默认不读取) */ 28 | @property (nonatomic, assign) YBNetworkCacheReadMode readMode; 29 | 30 | /** 缓存有效时长 (单位:秒,默认不限制) */ 31 | @property (nonatomic, assign) NSTimeInterval ageSeconds; 32 | 33 | /** 缓存 key 额外的部分,默认是 app 版本号 */ 34 | @property (nonatomic, copy) NSString *extraCacheKey; 35 | 36 | /** 根据请求成功数据判断是否需要缓存 (保证仅在数据有效时返回 YES) */ 37 | @property (nonatomic, copy, nullable) BOOL(^shouldCacheBlock)(YBNetworkResponse *response); 38 | 39 | /** 根据默认的缓存 key 自定义缓存 key */ 40 | @property (nonatomic, copy, nullable) NSString *(^customCacheKeyBlock)(NSString *defaultCacheKey); 41 | 42 | /** 43 | 获取磁盘缓存大小 44 | 45 | @return 缓存大小(单位 M) 46 | */ 47 | + (NSInteger)getDiskCacheSize; 48 | 49 | /** 50 | 清除磁盘缓存 51 | */ 52 | + (void)removeDiskCache; 53 | 54 | /** 55 | 清除内存缓存 56 | */ 57 | + (void)removeMemeryCache; 58 | 59 | /** 磁盘缓存对象 */ 60 | @property (nonatomic, class, readonly) YYDiskCache *diskCache; 61 | 62 | /** 内存缓存对象 */ 63 | @property (nonatomic, class, readonly) YYMemoryCache *memoryCache; 64 | 65 | @end 66 | 67 | NS_ASSUME_NONNULL_END 68 | -------------------------------------------------------------------------------- /YBNetwork/Cache/YBNetworkCache.m: -------------------------------------------------------------------------------- 1 | // 2 | // YBNetworkCache.m 3 | // YBNetwork 4 | // 5 | // Created by 波儿菜 on 2019/4/5. 6 | // Copyright © 2019 波儿菜. All rights reserved. 7 | // 8 | 9 | #import "YBNetworkCache.h" 10 | #import "YBNetworkCache+Internal.h" 11 | 12 | 13 | @interface YBNetworkCachePackage : NSObject 14 | @property (nonatomic, strong) id object; 15 | @property (nonatomic, strong) NSDate *updateDate; 16 | @end 17 | @implementation YBNetworkCachePackage 18 | - (instancetype)initWithCoder:(NSCoder *)aDecoder { 19 | self = [self init]; 20 | self.object = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(object))]; 21 | self.updateDate = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(updateDate))]; 22 | return self; 23 | } 24 | - (void)encodeWithCoder:(NSCoder *)aCoder { 25 | [aCoder encodeObject:self.object forKey:NSStringFromSelector(@selector(object))]; 26 | [aCoder encodeObject:self.updateDate forKey:NSStringFromSelector(@selector(updateDate))]; 27 | } 28 | @end 29 | 30 | 31 | static NSString * const YBNetworkCacheName = @"YBNetworkCacheName"; 32 | static YYDiskCache *_diskCache = nil; 33 | static YYMemoryCache *_memoryCache = nil; 34 | 35 | @implementation YBNetworkCache 36 | 37 | #pragma mark - life cycle 38 | 39 | - (instancetype)init { 40 | self = [super init]; 41 | if (self) { 42 | self.writeMode = YBNetworkCacheWriteModeNone; 43 | self.readMode = YBNetworkCacheReadModeNone; 44 | self.ageSeconds = 0; 45 | self.extraCacheKey = [@"v" stringByAppendingString:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]]; 46 | } 47 | return self; 48 | } 49 | 50 | #pragma mark - public 51 | 52 | + (NSInteger)getDiskCacheSize { 53 | return [YBNetworkCache.diskCache totalCost] / 1024.0 / 1024.0; 54 | } 55 | 56 | + (void)removeDiskCache { 57 | [YBNetworkCache.diskCache removeAllObjects]; 58 | } 59 | 60 | + (void)removeMemeryCache { 61 | [YBNetworkCache.memoryCache removeAllObjects]; 62 | } 63 | 64 | #pragma mark - internal 65 | 66 | - (void)setObject:(id)object forKey:(id)key { 67 | if (self.writeMode == YBNetworkCacheWriteModeNone) return; 68 | 69 | YBNetworkCachePackage *package = [YBNetworkCachePackage new]; 70 | package.object = object; 71 | package.updateDate = [NSDate date]; 72 | 73 | if (self.writeMode & YBNetworkCacheWriteModeMemory) { 74 | [YBNetworkCache.memoryCache setObject:package forKey:key]; 75 | } 76 | if (self.writeMode & YBNetworkCacheWriteModeDisk) { 77 | [YBNetworkCache.diskCache setObject:package forKey:key withBlock:^{}]; //子线程执行,空闭包仅为了去除警告 78 | } 79 | } 80 | 81 | - (void)objectForKey:(NSString *)key withBlock:(nonnull void (^)(NSString * _Nonnull, id _Nullable))block { 82 | if (!block) return; 83 | 84 | void(^callBack)(id) = ^(id obj) { 85 | YBNETWORK_MAIN_QUEUE_ASYNC(^{ 86 | if (obj && [((NSObject *)obj) isKindOfClass:YBNetworkCachePackage.class]) { 87 | YBNetworkCachePackage *package = (YBNetworkCachePackage *)obj; 88 | if (self.ageSeconds != 0 && -[package.updateDate timeIntervalSinceNow] > self.ageSeconds) { 89 | block(key, nil); 90 | } else { 91 | block(key, package.object); 92 | } 93 | } else { 94 | block(key, nil); 95 | } 96 | }) 97 | }; 98 | 99 | id object = [YBNetworkCache.memoryCache objectForKey:key]; 100 | if (object) { 101 | callBack(object); 102 | } else { 103 | [YBNetworkCache.diskCache objectForKey:key withBlock:^(NSString *key, id object) { 104 | if (object && ![YBNetworkCache.memoryCache objectForKey:key]) { 105 | [YBNetworkCache.memoryCache setObject:object forKey:key]; 106 | } 107 | callBack(object); 108 | }]; 109 | } 110 | } 111 | 112 | #pragma mark - getter and setter 113 | 114 | + (YYDiskCache *)diskCache { 115 | if (!_diskCache) { 116 | NSString *cacheFolder = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]; 117 | NSString *path = [cacheFolder stringByAppendingPathComponent:YBNetworkCacheName]; 118 | _diskCache = [[YYDiskCache alloc] initWithPath:path]; 119 | } 120 | return _diskCache; 121 | } 122 | 123 | + (void)setDiskCache:(YYDiskCache *)diskCache { 124 | _diskCache = diskCache; 125 | } 126 | 127 | + (YYMemoryCache *)memoryCache { 128 | if (!_memoryCache) { 129 | _memoryCache = [YYMemoryCache new]; 130 | _memoryCache.name = YBNetworkCacheName; 131 | } 132 | return _memoryCache; 133 | } 134 | 135 | + (void)setMemoryCache:(YYMemoryCache *)memoryCache { 136 | _memoryCache = memoryCache; 137 | } 138 | 139 | @end 140 | -------------------------------------------------------------------------------- /YBNetwork/Manger/YBBaseRequest+Internal.h: -------------------------------------------------------------------------------- 1 | // 2 | // YBBaseRequest+Internal.h 3 | // YBNetwork 4 | // 5 | // Created by 波儿菜 on 2019/4/3. 6 | // Copyright © 2019 波儿菜. All rights reserved. 7 | // 8 | 9 | #import "YBBaseRequest.h" 10 | 11 | NS_ASSUME_NONNULL_BEGIN 12 | 13 | @interface YBBaseRequest () 14 | 15 | /// 请求方法字符串 16 | - (NSString *)requestMethodString; 17 | 18 | /// 请求 URL 字符串 19 | - (NSString *)validRequestURLString; 20 | 21 | /// 请求参数字符串 22 | - (id)validRequestParameter; 23 | 24 | @end 25 | 26 | NS_ASSUME_NONNULL_END 27 | -------------------------------------------------------------------------------- /YBNetwork/Manger/YBNetworkManager.h: -------------------------------------------------------------------------------- 1 | // 2 | // YBNetworkManager.h 3 | // YBNetwork 4 | // 5 | // Created by 波儿菜 on 2019/4/2. 6 | // Copyright © 2019 波儿菜. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "YBBaseRequest.h" 11 | #import "YBNetworkResponse.h" 12 | 13 | NS_ASSUME_NONNULL_BEGIN 14 | 15 | typedef void(^YBRequestCompletionBlock)(YBNetworkResponse *response); 16 | 17 | @interface YBNetworkManager : NSObject 18 | 19 | + (instancetype)sharedManager; 20 | 21 | - (nullable NSNumber *)startNetworkingWithRequest:(YBBaseRequest *)request 22 | uploadProgress:(nullable YBRequestProgressBlock)uploadProgress 23 | downloadProgress:(nullable YBRequestProgressBlock)downloadProgress 24 | completion:(nullable YBRequestCompletionBlock)completion; 25 | 26 | - (void)cancelNetworkingWithSet:(NSSet *)set; 27 | 28 | - (instancetype)init OBJC_UNAVAILABLE("use '+sharedManager' instead"); 29 | + (instancetype)new OBJC_UNAVAILABLE("use '+sharedManager' instead"); 30 | 31 | @end 32 | 33 | NS_ASSUME_NONNULL_END 34 | -------------------------------------------------------------------------------- /YBNetwork/Manger/YBNetworkManager.m: -------------------------------------------------------------------------------- 1 | // 2 | // YBNetworkManager.m 3 | // YBNetwork 4 | // 5 | // Created by 波儿菜 on 2019/4/2. 6 | // Copyright © 2019 波儿菜. All rights reserved. 7 | // 8 | 9 | #import "YBNetworkManager.h" 10 | #import "YBBaseRequest+Internal.h" 11 | #import 12 | 13 | #define YBNM_TASKRECORD_LOCK(...) \ 14 | pthread_mutex_lock(&self->_lock); \ 15 | __VA_ARGS__ \ 16 | pthread_mutex_unlock(&self->_lock); 17 | 18 | @interface YBNetworkManager () 19 | @property (nonatomic, strong) NSMutableDictionary *taskRecord; 20 | @end 21 | 22 | @implementation YBNetworkManager { 23 | pthread_mutex_t _lock; 24 | } 25 | 26 | #pragma mark - life cycle 27 | 28 | - (void)dealloc { 29 | pthread_mutex_destroy(&_lock); 30 | } 31 | 32 | + (instancetype)sharedManager { 33 | static YBNetworkManager *manager = nil; 34 | static dispatch_once_t onceToken; 35 | dispatch_once(&onceToken, ^{ 36 | manager = [[YBNetworkManager alloc] initSpecially]; 37 | }); 38 | return manager; 39 | } 40 | 41 | - (instancetype)initSpecially { 42 | self = [super init]; 43 | if (self) { 44 | pthread_mutex_init(&_lock, NULL); 45 | } 46 | return self; 47 | } 48 | 49 | #pragma mark - private 50 | 51 | - (void)cancelTaskWithIdentifier:(NSNumber *)identifier { 52 | YBNM_TASKRECORD_LOCK(NSURLSessionTask *task = self.taskRecord[identifier];) 53 | if (task) { 54 | [task cancel]; 55 | YBNM_TASKRECORD_LOCK([self.taskRecord removeObjectForKey:identifier];) 56 | } 57 | } 58 | 59 | - (void)cancelAllTask { 60 | YBNM_TASKRECORD_LOCK( 61 | for (NSURLSessionTask *task in self.taskRecord) { 62 | [task cancel]; 63 | } 64 | [self.taskRecord removeAllObjects]; 65 | ) 66 | } 67 | 68 | - (NSNumber *)startDownloadTaskWithManager:(AFHTTPSessionManager *)manager URLRequest:(NSURLRequest *)URLRequest downloadPath:(NSString *)downloadPath downloadProgress:(nullable YBRequestProgressBlock)downloadProgress completion:(YBRequestCompletionBlock)completion { 69 | 70 | // 保证下载路径是文件而不是目录 71 | NSString *validDownloadPath = downloadPath.copy; 72 | BOOL isDirectory; 73 | if(![[NSFileManager defaultManager] fileExistsAtPath:validDownloadPath isDirectory:&isDirectory]) { 74 | isDirectory = NO; 75 | } 76 | if (isDirectory) { 77 | validDownloadPath = [NSString pathWithComponents:@[validDownloadPath, URLRequest.URL.lastPathComponent]]; 78 | } 79 | 80 | // 若存在文件则移除 81 | if ([[NSFileManager defaultManager] fileExistsAtPath:validDownloadPath]) { 82 | [[NSFileManager defaultManager] removeItemAtPath:validDownloadPath error:nil]; 83 | } 84 | 85 | __block NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:URLRequest progress:downloadProgress destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) { 86 | return [NSURL fileURLWithPath:validDownloadPath isDirectory:NO]; 87 | } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) { 88 | YBNM_TASKRECORD_LOCK([self.taskRecord removeObjectForKey:@(task.taskIdentifier)];) 89 | if (completion) { 90 | completion([YBNetworkResponse responseWithSessionTask:task responseObject:filePath error:error]); 91 | } 92 | }]; 93 | 94 | NSNumber *taskIdentifier = @(task.taskIdentifier); 95 | YBNM_TASKRECORD_LOCK(self.taskRecord[taskIdentifier] = task;) 96 | [task resume]; 97 | return taskIdentifier; 98 | } 99 | 100 | - (NSNumber *)startDataTaskWithManager:(AFHTTPSessionManager *)manager URLRequest:(NSURLRequest *)URLRequest uploadProgress:(nullable YBRequestProgressBlock)uploadProgress downloadProgress:(nullable YBRequestProgressBlock)downloadProgress completion:(YBRequestCompletionBlock)completion { 101 | 102 | __block NSURLSessionDataTask *task = [manager dataTaskWithRequest:URLRequest uploadProgress:^(NSProgress * _Nonnull _uploadProgress) { 103 | if (uploadProgress) { 104 | uploadProgress(_uploadProgress); 105 | } 106 | } downloadProgress:^(NSProgress * _Nonnull _downloadProgress) { 107 | if (downloadProgress) { 108 | downloadProgress(_downloadProgress); 109 | } 110 | } completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { 111 | YBNM_TASKRECORD_LOCK([self.taskRecord removeObjectForKey:@(task.taskIdentifier)];) 112 | if (completion) { 113 | completion([YBNetworkResponse responseWithSessionTask:task responseObject:responseObject error:error]); 114 | } 115 | }]; 116 | 117 | NSNumber *taskIdentifier = @(task.taskIdentifier); 118 | YBNM_TASKRECORD_LOCK(self.taskRecord[taskIdentifier] = task;) 119 | [task resume]; 120 | return taskIdentifier; 121 | } 122 | 123 | #pragma mark - public 124 | 125 | - (void)cancelNetworkingWithSet:(NSSet *)set { 126 | YBNM_TASKRECORD_LOCK( 127 | for (NSNumber *identifier in set) { 128 | NSURLSessionTask *task = self.taskRecord[identifier]; 129 | if (task) { 130 | [task cancel]; 131 | [self.taskRecord removeObjectForKey:identifier]; 132 | } 133 | } 134 | ) 135 | } 136 | 137 | - (NSNumber *)startNetworkingWithRequest:(YBBaseRequest *)request uploadProgress:(nullable YBRequestProgressBlock)uploadProgress downloadProgress:(nullable YBRequestProgressBlock)downloadProgress completion:(nullable YBRequestCompletionBlock)completion { 138 | 139 | // 构建网络请求数据 140 | NSString *method = [request requestMethodString]; 141 | AFHTTPRequestSerializer *serializer = [self requestSerializerForRequest:request]; 142 | NSString *URLString = [request validRequestURLString]; 143 | id parameter = [request validRequestParameter]; 144 | 145 | // 构建 URLRequest 146 | NSError *error = nil; 147 | NSMutableURLRequest *URLRequest = nil; 148 | if (request.requestConstructingBody) { 149 | URLRequest = [serializer multipartFormRequestWithMethod:@"POST" URLString:URLString parameters:parameter constructingBodyWithBlock:request.requestConstructingBody error:&error]; 150 | } else { 151 | URLRequest = [serializer requestWithMethod:method URLString:URLString parameters:parameter error:&error]; 152 | } 153 | 154 | if (error) { 155 | if (completion) completion([YBNetworkResponse responseWithSessionTask:nil responseObject:nil error:error]); 156 | return nil; 157 | } 158 | 159 | // 发起网络请求 160 | AFHTTPSessionManager *manager = [self sessionManagerForRequest:request]; 161 | if (request.downloadPath.length > 0) { 162 | return [self startDownloadTaskWithManager:manager URLRequest:URLRequest downloadPath:request.downloadPath downloadProgress:downloadProgress completion:completion]; 163 | } else { 164 | return [self startDataTaskWithManager:manager URLRequest:URLRequest uploadProgress:uploadProgress downloadProgress:downloadProgress completion:completion]; 165 | } 166 | } 167 | 168 | #pragma mark - read info from request 169 | 170 | - (AFHTTPRequestSerializer *)requestSerializerForRequest:(YBBaseRequest *)request { 171 | AFHTTPRequestSerializer *serializer = request.requestSerializer ?: [AFJSONRequestSerializer serializer]; 172 | if (request.requestTimeoutInterval > 0) { 173 | serializer.timeoutInterval = request.requestTimeoutInterval; 174 | } 175 | return serializer; 176 | } 177 | 178 | - (AFHTTPSessionManager *)sessionManagerForRequest:(YBBaseRequest *)request { 179 | AFHTTPSessionManager *manager = request.sessionManager; 180 | if (!manager) { 181 | static AFHTTPSessionManager *defaultManager = nil; 182 | static dispatch_once_t onceToken; 183 | dispatch_once(&onceToken, ^{ 184 | defaultManager = [AFHTTPSessionManager new]; 185 | }); 186 | manager = defaultManager; 187 | } 188 | manager.completionQueue = dispatch_queue_create("com.ybnetwork.completionqueue", DISPATCH_QUEUE_CONCURRENT); 189 | AFHTTPResponseSerializer *customSerializer = request.responseSerializer; 190 | if (customSerializer) manager.responseSerializer = customSerializer; 191 | return manager; 192 | } 193 | 194 | #pragma mark - getter 195 | 196 | - (NSMutableDictionary *)taskRecord { 197 | if (!_taskRecord) { 198 | _taskRecord = [NSMutableDictionary dictionary]; 199 | } 200 | return _taskRecord; 201 | } 202 | 203 | @end 204 | -------------------------------------------------------------------------------- /YBNetwork/Response/YBNetworkResponse.h: -------------------------------------------------------------------------------- 1 | // 2 | // YBNetworkResponse.h 3 | // YBNetwork 4 | // 5 | // Created by 波儿菜 on 2019/4/6. 6 | // Copyright © 2019 波儿菜. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "YBNetworkDefine.h" 11 | 12 | NS_ASSUME_NONNULL_BEGIN 13 | 14 | /** 15 | 网络请求响应对象 16 | 如果想拓展一些属性,使用 runtime 关联属性,然后重写预处理方法进行计算并赋值就行了。 17 | */ 18 | @interface YBNetworkResponse : NSObject 19 | 20 | /// 请求成功数据 21 | @property (nonatomic, strong, nullable) id responseObject; 22 | 23 | /// 请求失败 NSError 24 | @property (nonatomic, strong, readonly, nullable) NSError *error; 25 | 26 | /// 请求任务 27 | @property (nonatomic, strong, readonly, nullable) NSURLSessionTask *sessionTask; 28 | 29 | /// sessionTask.response 30 | @property (nonatomic, strong, readonly, nullable) NSHTTPURLResponse *URLResponse; 31 | 32 | /// 便利构造 33 | + (instancetype)responseWithSessionTask:(nullable NSURLSessionTask *)sessionTask 34 | responseObject:(nullable id)responseObject 35 | error:(nullable NSError *)error; 36 | 37 | @end 38 | 39 | NS_ASSUME_NONNULL_END 40 | -------------------------------------------------------------------------------- /YBNetwork/Response/YBNetworkResponse.m: -------------------------------------------------------------------------------- 1 | // 2 | // YBNetworkResponse.m 3 | // YBNetwork 4 | // 5 | // Created by 波儿菜 on 2019/4/6. 6 | // Copyright © 2019 波儿菜. All rights reserved. 7 | // 8 | 9 | #import "YBNetworkResponse.h" 10 | 11 | @implementation YBNetworkResponse 12 | 13 | #pragma mark - life cycle 14 | 15 | + (instancetype)responseWithSessionTask:(NSURLSessionTask *)sessionTask responseObject:(id)responseObject error:(NSError *)error { 16 | YBNetworkResponse *response = [YBNetworkResponse new]; 17 | response->_sessionTask = sessionTask; 18 | response->_responseObject = responseObject; 19 | response->_error = error; 20 | return response; 21 | } 22 | 23 | #pragma mark - getter 24 | 25 | - (NSHTTPURLResponse *)URLResponse { 26 | if (!self.sessionTask || ![self.sessionTask.response isKindOfClass:NSHTTPURLResponse.class]) { 27 | return nil; 28 | } 29 | return (NSHTTPURLResponse *)self.sessionTask.response; 30 | } 31 | 32 | @end 33 | -------------------------------------------------------------------------------- /YBNetwork/YBBaseRequest.h: -------------------------------------------------------------------------------- 1 | // 2 | // YBBaseRequest.h 3 | // YBNetwork 4 | // 5 | // Created by 波儿菜 on 2019/4/3. 6 | // Copyright © 2019 波儿菜. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "YBNetworkResponse.h" 11 | #import "YBNetworkCache.h" 12 | 13 | NS_ASSUME_NONNULL_BEGIN 14 | 15 | @interface YBBaseRequest : NSObject 16 | 17 | #pragma - 网络请求数据 18 | 19 | /** 请求方法类型 */ 20 | @property (nonatomic, assign) YBRequestMethod requestMethod; 21 | 22 | /** 请求访问路径 (例如:/detail/list) */ 23 | @property (nonatomic, copy) NSString *requestURI; 24 | 25 | /** 请求参数 */ 26 | @property (nonatomic, copy, nullable) NSDictionary *requestParameter; 27 | 28 | /** 请求超时时间 */ 29 | @property (nonatomic, assign) NSTimeInterval requestTimeoutInterval; 30 | 31 | /** 请求上传文件包 */ 32 | @property (nonatomic, copy, nullable) void(^requestConstructingBody)(id formData); 33 | 34 | /** 下载路径 */ 35 | @property (nonatomic, copy) NSString *downloadPath; 36 | 37 | #pragma - 发起网络请求 38 | 39 | /** 发起网络请求 */ 40 | - (void)start; 41 | 42 | /** 发起网络请求带回调 */ 43 | - (void)startWithSuccess:(nullable YBRequestSuccessBlock)success 44 | failure:(nullable YBRequestFailureBlock)failure; 45 | 46 | - (void)startWithCache:(nullable YBRequestCacheBlock)cache 47 | success:(nullable YBRequestSuccessBlock)success 48 | failure:(nullable YBRequestFailureBlock)failure; 49 | 50 | - (void)startWithUploadProgress:(nullable YBRequestProgressBlock)uploadProgress 51 | downloadProgress:(nullable YBRequestProgressBlock)downloadProgress 52 | cache:(nullable YBRequestCacheBlock)cache 53 | success:(nullable YBRequestSuccessBlock)success 54 | failure:(nullable YBRequestFailureBlock)failure; 55 | 56 | /** 取消网络请求 */ 57 | - (void)cancel; 58 | 59 | #pragma - 相关回调代理 60 | 61 | /** 请求结果回调代理 */ 62 | @property (nonatomic, weak) id delegate; 63 | 64 | #pragma - 缓存 65 | 66 | /** 缓存处理器 */ 67 | @property (nonatomic, strong, readonly) YBNetworkCache *cacheHandler; 68 | 69 | #pragma - 其它 70 | 71 | /** 网络请求释放策略 (默认 YBNetworkReleaseStrategyHoldRequest) */ 72 | @property (nonatomic, assign) YBNetworkReleaseStrategy releaseStrategy; 73 | 74 | /** 重复网络请求处理策略 (默认 YBNetworkRepeatStrategyAllAllowed) */ 75 | @property (nonatomic, assign) YBNetworkRepeatStrategy repeatStrategy; 76 | 77 | /** 是否正在网络请求 */ 78 | - (BOOL)isExecuting; 79 | 80 | /** 请求标识,可以查看完整的请求路径和参数 */ 81 | - (NSString *)requestIdentifier; 82 | 83 | /** 清空所有请求回调闭包 */ 84 | - (void)clearRequestBlocks; 85 | 86 | #pragma - 网络请求公共配置 (以子类化方式实现: 针对不同的接口团队设计不同的公共配置) 87 | 88 | /** 89 | 事务管理器 (通常情况下不需设置) 。注意: 90 | 1、其 requestSerializer 和 responseSerializer 属性会被下面两个同名属性覆盖。 91 | 2、其 completionQueue 属性会被框架内部覆盖。 92 | */ 93 | @property (nonatomic, strong, nullable) AFHTTPSessionManager *sessionManager; 94 | 95 | /** 请求序列化器 */ 96 | @property (nonatomic, strong) AFHTTPRequestSerializer *requestSerializer; 97 | 98 | /** 响应序列化器 */ 99 | @property (nonatomic, strong) AFHTTPResponseSerializer *responseSerializer; 100 | 101 | /** 服务器地址及公共路径 (例如:https://www.baidu.com) */ 102 | @property (nonatomic, copy) NSString *baseURI; 103 | 104 | @end 105 | 106 | 107 | /// 预处理请求数据 (重写分类方法) 108 | @interface YBBaseRequest (PreprocessRequest) 109 | 110 | /** 预处理请求参数, 返回处理后的请求参数 */ 111 | - (nullable NSDictionary *)yb_preprocessParameter:(nullable NSDictionary *)parameter; 112 | 113 | /** 预处理拼接后的完整 URL 字符串, 返回处理后的 URL 字符串 */ 114 | - (NSString *)yb_preprocessURLString:(NSString *)URLString; 115 | 116 | @end 117 | 118 | 119 | /// 预处理响应数据 (重写分类方法) 120 | @interface YBBaseRequest (PreprocessResponse) 121 | 122 | /** 123 | 网络请求回调重定向,方法在子线程回调,并会再下面几个预处理方法之前调用。 124 | 需要特别注意 YBRequestRedirectionStop 会停止后续操作,如果业务使用闭包回调,这个闭包不会被清空,可能会造成循环引用,所以这种场景务必保证回调被正确处理,一般有以下两种方式: 125 | 1、Stop 过后执行特定逻辑,然后重新 start 发起网络请求,之前的回调闭包就能继续正常处理了。 126 | 2、直接调用 clearRequestBlocks 清空回调闭包。 127 | */ 128 | - (void)yb_redirection:(void(^)(YBRequestRedirection))redirection response:(YBNetworkResponse *)response; 129 | 130 | /** 预处理请求成功数据 (子线程执行, 若数据来自缓存在主线程执行) */ 131 | - (void)yb_preprocessSuccessInChildThreadWithResponse:(YBNetworkResponse *)response; 132 | 133 | /** 预处理请求成功数据 */ 134 | - (void)yb_preprocessSuccessInMainThreadWithResponse:(YBNetworkResponse *)response; 135 | 136 | /** 预处理请求失败数据 (子线程执行) */ 137 | - (void)yb_preprocessFailureInChildThreadWithResponse:(YBNetworkResponse *)response; 138 | 139 | /** 预处理请求失败数据 */ 140 | - (void)yb_preprocessFailureInMainThreadWithResponse:(YBNetworkResponse *)response; 141 | 142 | @end 143 | 144 | NS_ASSUME_NONNULL_END 145 | -------------------------------------------------------------------------------- /YBNetwork/YBNetworkDefine.h: -------------------------------------------------------------------------------- 1 | // 2 | // YBNetworkDefine.h 3 | // YBNetwork 4 | // 5 | // Created by 波儿菜 on 2019/4/3. 6 | // Copyright © 2019 波儿菜. All rights reserved. 7 | // 8 | 9 | #ifndef YBNetworkDefine_h 10 | #define YBNetworkDefine_h 11 | 12 | #if __has_include() 13 | #import 14 | #else 15 | #import "AFNetworking.h" 16 | #endif 17 | 18 | 19 | #define YBNETWORK_QUEUE_ASYNC(queue, block)\ 20 | if (strcmp(dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL), dispatch_queue_get_label(queue)) == 0) {\ 21 | block();\ 22 | } else {\ 23 | dispatch_async(queue, block);\ 24 | } 25 | 26 | #define YBNETWORK_MAIN_QUEUE_ASYNC(block) YBNETWORK_QUEUE_ASYNC(dispatch_get_main_queue(), block) 27 | 28 | 29 | NS_ASSUME_NONNULL_BEGIN 30 | 31 | /// 请求类型 32 | typedef NS_ENUM(NSInteger, YBRequestMethod) { 33 | YBRequestMethodGET, 34 | YBRequestMethodPOST, 35 | YBRequestMethodDELETE, 36 | YBRequestMethodPUT, 37 | YBRequestMethodHEAD, 38 | YBRequestMethodPATCH 39 | }; 40 | 41 | /// 缓存存储模式 42 | typedef NS_OPTIONS(NSUInteger, YBNetworkCacheWriteMode) { 43 | /// 无缓存 44 | YBNetworkCacheWriteModeNone = 0, 45 | /// 内存缓存 46 | YBNetworkCacheWriteModeMemory = 1 << 0, 47 | /// 磁盘缓存 48 | YBNetworkCacheWriteModeDisk = 1 << 1, 49 | YBNetworkCacheWriteModeMemoryAndDisk = YBNetworkCacheWriteModeMemory | YBNetworkCacheWriteModeDisk 50 | }; 51 | 52 | /// 缓存读取模式 53 | typedef NS_ENUM(NSInteger, YBNetworkCacheReadMode) { 54 | /// 不读取缓存 55 | YBNetworkCacheReadModeNone, 56 | /// 缓存命中后仍然发起网络请求 57 | YBNetworkCacheReadModeAlsoNetwork, 58 | /// 缓存命中后不发起网络请求 59 | YBNetworkCacheReadModeCancelNetwork, 60 | }; 61 | 62 | /// 网络请求释放策略 63 | typedef NS_ENUM(NSInteger, YBNetworkReleaseStrategy) { 64 | /// 网络任务会持有 YBBaseRequest 实例,网络任务完成 YBBaseRequest 实例才会释放 65 | YBNetworkReleaseStrategyHoldRequest, 66 | /// 网络请求将随着 YBBaseRequest 实例的释放而取消 67 | YBNetworkReleaseStrategyWhenRequestDealloc, 68 | /// 网络请求和 YBBaseRequest 实例无关联 69 | YBNetworkReleaseStrategyNotCareRequest 70 | }; 71 | 72 | /// 重复网络请求处理策略 73 | typedef NS_ENUM(NSInteger, YBNetworkRepeatStrategy) { 74 | /// 允许重复网络请求 75 | YBNetworkRepeatStrategyAllAllowed, 76 | /// 取消最旧的网络请求 77 | YBNetworkRepeatStrategyCancelOldest, 78 | /// 取消最新的网络请求 79 | YBNetworkRepeatStrategyCancelNewest 80 | }; 81 | 82 | /// 网络请求回调重定向类型 83 | typedef NS_ENUM(NSInteger, YBRequestRedirection) { 84 | /// 重定向为成功 85 | YBRequestRedirectionSuccess, 86 | /// 重定向为失败 87 | YBRequestRedirectionFailure, 88 | /// 停止后续操作(主要是停止回调) 89 | YBRequestRedirectionStop 90 | }; 91 | 92 | 93 | @class YBBaseRequest; 94 | @class YBNetworkResponse; 95 | 96 | 97 | /// 进度闭包 98 | typedef void(^YBRequestProgressBlock)(NSProgress *progress); 99 | 100 | /// 缓存命中闭包 101 | typedef void(^YBRequestCacheBlock)(YBNetworkResponse *response); 102 | 103 | /// 请求成功闭包 104 | typedef void(^YBRequestSuccessBlock)(YBNetworkResponse *response); 105 | 106 | /// 请求失败闭包 107 | typedef void(^YBRequestFailureBlock)(YBNetworkResponse *response); 108 | 109 | 110 | /// 网络请求响应代理 111 | @protocol YBResponseDelegate 112 | @optional 113 | 114 | /// 上传进度 115 | - (void)request:(__kindof YBBaseRequest *)request uploadProgress:(NSProgress *)progress; 116 | 117 | /// 下载进度 118 | - (void)request:(__kindof YBBaseRequest *)request downloadProgress:(NSProgress *)progress; 119 | 120 | /// 缓存命中 121 | - (void)request:(__kindof YBBaseRequest *)request cacheWithResponse:(YBNetworkResponse *)response; 122 | 123 | /// 请求成功 124 | - (void)request:(__kindof YBBaseRequest *)request successWithResponse:(YBNetworkResponse *)response; 125 | 126 | /// 请求失败 127 | - (void)request:(__kindof YBBaseRequest *)request failureWithResponse:(YBNetworkResponse *)response; 128 | 129 | @end 130 | 131 | NS_ASSUME_NONNULL_END 132 | 133 | #endif /* YBNetworkDefine_h */ 134 | -------------------------------------------------------------------------------- /YBNetworkDemo.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /YBNetworkDemo.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /YBNetworkDemo.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /YBNetworkDemo.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /YBNetworkDemo/AppDelegate.h: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.h 3 | // YBNetworkDemo 4 | // 5 | // Created by 波儿菜 on 2019/4/9. 6 | // Copyright © 2019 波儿菜. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface AppDelegate : UIResponder 12 | 13 | @property (strong, nonatomic) UIWindow *window; 14 | 15 | 16 | @end 17 | 18 | -------------------------------------------------------------------------------- /YBNetworkDemo/AppDelegate.m: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.m 3 | // YBNetworkDemo 4 | // 5 | // Created by 波儿菜 on 2019/4/9. 6 | // Copyright © 2019 波儿菜. All rights reserved. 7 | // 8 | 9 | #import "AppDelegate.h" 10 | #import "ViewController.h" 11 | 12 | @interface AppDelegate () 13 | 14 | @end 15 | 16 | @implementation AppDelegate 17 | 18 | 19 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 20 | ViewController *vc = [ViewController new]; 21 | UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc]; 22 | _window = [[UIWindow alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)]; 23 | _window.rootViewController = nav; 24 | [_window makeKeyAndVisible]; 25 | return YES; 26 | } 27 | 28 | 29 | - (void)applicationWillResignActive:(UIApplication *)application { 30 | // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. 31 | // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. 32 | } 33 | 34 | 35 | - (void)applicationDidEnterBackground:(UIApplication *)application { 36 | // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 37 | // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 38 | } 39 | 40 | 41 | - (void)applicationWillEnterForeground:(UIApplication *)application { 42 | // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. 43 | } 44 | 45 | 46 | - (void)applicationDidBecomeActive:(UIApplication *)application { 47 | // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. 48 | } 49 | 50 | 51 | - (void)applicationWillTerminate:(UIApplication *)application { 52 | // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. 53 | } 54 | 55 | 56 | @end 57 | -------------------------------------------------------------------------------- /YBNetworkDemo/Assets.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "iphone", 5 | "size" : "20x20", 6 | "scale" : "2x" 7 | }, 8 | { 9 | "idiom" : "iphone", 10 | "size" : "20x20", 11 | "scale" : "3x" 12 | }, 13 | { 14 | "idiom" : "iphone", 15 | "size" : "29x29", 16 | "scale" : "2x" 17 | }, 18 | { 19 | "idiom" : "iphone", 20 | "size" : "29x29", 21 | "scale" : "3x" 22 | }, 23 | { 24 | "idiom" : "iphone", 25 | "size" : "40x40", 26 | "scale" : "2x" 27 | }, 28 | { 29 | "idiom" : "iphone", 30 | "size" : "40x40", 31 | "scale" : "3x" 32 | }, 33 | { 34 | "idiom" : "iphone", 35 | "size" : "60x60", 36 | "scale" : "2x" 37 | }, 38 | { 39 | "idiom" : "iphone", 40 | "size" : "60x60", 41 | "scale" : "3x" 42 | }, 43 | { 44 | "idiom" : "ipad", 45 | "size" : "20x20", 46 | "scale" : "1x" 47 | }, 48 | { 49 | "idiom" : "ipad", 50 | "size" : "20x20", 51 | "scale" : "2x" 52 | }, 53 | { 54 | "idiom" : "ipad", 55 | "size" : "29x29", 56 | "scale" : "1x" 57 | }, 58 | { 59 | "idiom" : "ipad", 60 | "size" : "29x29", 61 | "scale" : "2x" 62 | }, 63 | { 64 | "idiom" : "ipad", 65 | "size" : "40x40", 66 | "scale" : "1x" 67 | }, 68 | { 69 | "idiom" : "ipad", 70 | "size" : "40x40", 71 | "scale" : "2x" 72 | }, 73 | { 74 | "idiom" : "ipad", 75 | "size" : "76x76", 76 | "scale" : "1x" 77 | }, 78 | { 79 | "idiom" : "ipad", 80 | "size" : "76x76", 81 | "scale" : "2x" 82 | }, 83 | { 84 | "idiom" : "ipad", 85 | "size" : "83.5x83.5", 86 | "scale" : "2x" 87 | }, 88 | { 89 | "idiom" : "ios-marketing", 90 | "size" : "1024x1024", 91 | "scale" : "1x" 92 | } 93 | ], 94 | "info" : { 95 | "version" : 1, 96 | "author" : "xcode" 97 | } 98 | } -------------------------------------------------------------------------------- /YBNetworkDemo/Assets.xcassets/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "version" : 1, 4 | "author" : "xcode" 5 | } 6 | } -------------------------------------------------------------------------------- /YBNetworkDemo/Base.lproj/LaunchScreen.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /YBNetworkDemo/Base.lproj/Main.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /YBNetworkDemo/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | $(DEVELOPMENT_LANGUAGE) 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | APPL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleVersion 20 | 1 21 | LSRequiresIPhoneOS 22 | 23 | NSAppTransportSecurity 24 | 25 | NSAllowsArbitraryLoads 26 | 27 | 28 | UILaunchStoryboardName 29 | LaunchScreen 30 | UIMainStoryboardFile 31 | 32 | UIRequiredDeviceCapabilities 33 | 34 | armv7 35 | 36 | UISupportedInterfaceOrientations 37 | 38 | UIInterfaceOrientationPortrait 39 | UIInterfaceOrientationLandscapeLeft 40 | UIInterfaceOrientationLandscapeRight 41 | 42 | UISupportedInterfaceOrientations~ipad 43 | 44 | UIInterfaceOrientationPortrait 45 | UIInterfaceOrientationPortraitUpsideDown 46 | UIInterfaceOrientationLandscapeLeft 47 | UIInterfaceOrientationLandscapeRight 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /YBNetworkDemo/TestCase/APITeams/DefaultServerRequest.h: -------------------------------------------------------------------------------- 1 | // 2 | // DefaultRequest.h 3 | // YBNetworkDemo 4 | // 5 | // Created by 波儿菜 on 2019/4/9. 6 | // Copyright © 2019 波儿菜. All rights reserved. 7 | // 8 | 9 | #import "YBBaseRequest.h" 10 | #import "YBNetworkResponse+YBCustom.h" 11 | 12 | NS_ASSUME_NONNULL_BEGIN 13 | 14 | @interface DefaultServerRequest : YBBaseRequest 15 | 16 | @end 17 | 18 | NS_ASSUME_NONNULL_END 19 | -------------------------------------------------------------------------------- /YBNetworkDemo/TestCase/APITeams/DefaultServerRequest.m: -------------------------------------------------------------------------------- 1 | // 2 | // DefaultRequest.m 3 | // YBNetworkDemo 4 | // 5 | // Created by 波儿菜 on 2019/4/9. 6 | // Copyright © 2019 波儿菜. All rights reserved. 7 | // 8 | 9 | #import "DefaultServerRequest.h" 10 | 11 | @implementation DefaultServerRequest 12 | 13 | #pragma mark - life cycle 14 | 15 | - (instancetype)init { 16 | self = [super init]; 17 | if (self) { 18 | self.baseURI = @"http://japi.juhe.cn"; 19 | 20 | [self.cacheHandler setShouldCacheBlock:^BOOL(YBNetworkResponse * _Nonnull response) { 21 | // 检查数据正确性,保证缓存有用的内容 22 | return YES; 23 | }]; 24 | } 25 | return self; 26 | } 27 | 28 | #pragma mark - override 29 | 30 | - (AFHTTPRequestSerializer *)requestSerializer { 31 | AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer new]; 32 | serializer.timeoutInterval = 25; 33 | return serializer; 34 | } 35 | 36 | - (AFHTTPResponseSerializer *)responseSerializer { 37 | AFHTTPResponseSerializer *serializer = [AFJSONResponseSerializer serializer]; 38 | NSMutableSet *types = [NSMutableSet set]; 39 | [types addObject:@"text/html"]; 40 | [types addObject:@"text/plain"]; 41 | [types addObject:@"application/json"]; 42 | [types addObject:@"text/json"]; 43 | [types addObject:@"text/javascript"]; 44 | serializer.acceptableContentTypes = types; 45 | return serializer; 46 | } 47 | 48 | - (void)start { 49 | NSLog(@"发起请求:%@", self.requestIdentifier); 50 | [super start]; 51 | } 52 | 53 | - (void)yb_redirection:(void (^)(YBRequestRedirection))redirection response:(YBNetworkResponse *)response { 54 | 55 | // 处理错误的状态码 56 | if (response.error) { 57 | YBResponseErrorType errorType; 58 | switch (response.error.code) { 59 | case NSURLErrorTimedOut: 60 | errorType = YBResponseErrorTypeTimedOut; 61 | break; 62 | case NSURLErrorCancelled: 63 | errorType = YBResponseErrorTypeCancelled; 64 | break; 65 | default: 66 | errorType = YBResponseErrorTypeNoNetwork; 67 | break; 68 | } 69 | response.errorType = errorType; 70 | } 71 | 72 | // 自定义重定向 73 | NSDictionary *responseDic = response.responseObject; 74 | if ([[NSString stringWithFormat:@"%@", responseDic[@"error_code"]] isEqualToString:@"2"]) { 75 | redirection(YBRequestRedirectionFailure); 76 | response.errorType = YBResponseErrorTypeServerError; 77 | return; 78 | } 79 | redirection(YBRequestRedirectionSuccess); 80 | } 81 | 82 | - (NSDictionary *)yb_preprocessParameter:(NSDictionary *)parameter { 83 | NSMutableDictionary *tmp = [NSMutableDictionary dictionaryWithDictionary:parameter ?: @{}]; 84 | tmp[@"test_deviceID"] = @"test250"; //给每一个请求,添加额外的参数 85 | return tmp; 86 | } 87 | 88 | - (NSString *)yb_preprocessURLString:(NSString *)URLString { 89 | return URLString; 90 | } 91 | 92 | - (void)yb_preprocessSuccessInChildThreadWithResponse:(YBNetworkResponse *)response { 93 | NSMutableDictionary *res = [NSMutableDictionary dictionaryWithDictionary:response.responseObject]; 94 | res[@"test_user"] = @"indulge_in"; //为每一个返回结果添加字段 95 | response.responseObject = res; 96 | } 97 | 98 | - (void)yb_preprocessSuccessInMainThreadWithResponse:(YBNetworkResponse *)response { 99 | 100 | } 101 | 102 | - (void)yb_preprocessFailureInChildThreadWithResponse:(YBNetworkResponse *)response { 103 | 104 | } 105 | 106 | - (void)yb_preprocessFailureInMainThreadWithResponse:(YBNetworkResponse *)response { 107 | 108 | } 109 | 110 | @end 111 | -------------------------------------------------------------------------------- /YBNetworkDemo/TestCase/APITeams/OtherServerRequest.h: -------------------------------------------------------------------------------- 1 | // 2 | // OtherRequest.h 3 | // YBNetworkDemo 4 | // 5 | // Created by 波儿菜 on 2019/4/9. 6 | // Copyright © 2019 波儿菜. All rights reserved. 7 | // 8 | 9 | #import "YBBaseRequest.h" 10 | 11 | NS_ASSUME_NONNULL_BEGIN 12 | 13 | @interface OtherServerRequest : YBBaseRequest 14 | 15 | @end 16 | 17 | NS_ASSUME_NONNULL_END 18 | -------------------------------------------------------------------------------- /YBNetworkDemo/TestCase/APITeams/OtherServerRequest.m: -------------------------------------------------------------------------------- 1 | // 2 | // OtherRequest.m 3 | // YBNetworkDemo 4 | // 5 | // Created by 波儿菜 on 2019/4/9. 6 | // Copyright © 2019 波儿菜. All rights reserved. 7 | // 8 | 9 | #import "OtherServerRequest.h" 10 | 11 | @implementation OtherServerRequest 12 | //TODO 13 | @end 14 | -------------------------------------------------------------------------------- /YBNetworkDemo/TestCase/TestViewController.h: -------------------------------------------------------------------------------- 1 | // 2 | // TestViewController.h 3 | // YBNetworkDemo 4 | // 5 | // Created by 波儿菜 on 2019/4/9. 6 | // Copyright © 2019 波儿菜. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | NS_ASSUME_NONNULL_BEGIN 12 | 13 | @interface TestViewController : UIViewController 14 | 15 | @end 16 | 17 | NS_ASSUME_NONNULL_END 18 | -------------------------------------------------------------------------------- /YBNetworkDemo/TestCase/TestViewController.m: -------------------------------------------------------------------------------- 1 | // 2 | // TestViewController.m 3 | // YBNetworkDemo 4 | // 5 | // Created by 波儿菜 on 2019/4/9. 6 | // Copyright © 2019 波儿菜. All rights reserved. 7 | // 8 | 9 | #import "TestViewController.h" 10 | #import "DefaultServerRequest.h" 11 | 12 | @interface TestViewController () 13 | @property (nonatomic, strong) DefaultServerRequest *request; 14 | @end 15 | 16 | @implementation TestViewController 17 | 18 | #pragma mark - life cycle 19 | 20 | - (void)dealloc { 21 | NSLog(@"释放:%@", self); 22 | if (_request) [_request cancel]; 23 | } 24 | 25 | - (void)viewDidLoad { 26 | [super viewDidLoad]; 27 | 28 | self.view.backgroundColor = [UIColor whiteColor]; 29 | [@[@"调用接口A", @"调用接口B"] enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { 30 | UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem]; 31 | button.bounds = CGRectMake(0, 0, 300, 100); 32 | button.center = CGPointMake(self.view.center.x, 200 + 100 * (idx + 1)); 33 | button.tag = idx; 34 | button.titleLabel.font = [UIFont boldSystemFontOfSize:30]; 35 | [button setTitle:obj forState:UIControlStateNormal]; 36 | [button addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside]; 37 | [self.view addSubview:button]; 38 | }]; 39 | } 40 | 41 | #pragma mark - event 42 | 43 | - (void)clickButton:(UIButton *)button { 44 | if (button.tag == 0) { 45 | [self searchA]; 46 | } else { 47 | [self searchB]; 48 | } 49 | } 50 | 51 | #pragma mark - request 52 | 53 | - (void)searchA { 54 | 55 | DefaultServerRequest *request = [DefaultServerRequest new]; 56 | request.cacheHandler.writeMode = YBNetworkCacheWriteModeMemoryAndDisk; 57 | request.cacheHandler.readMode = YBNetworkCacheReadModeCancelNetwork; 58 | request.requestMethod = YBRequestMethodGET; 59 | request.requestURI = @"charconvert/change.from"; 60 | request.requestParameter = @{@"key":@"0e27c575047e83b407ff9e517cde9c76", @"type":@"2", @"text":@"呵呵呵呵"}; 61 | 62 | __weak typeof(self) weakSelf = self; 63 | [request startWithCache:^(YBNetworkResponse * _Nonnull response) { 64 | __strong typeof(weakSelf) self = weakSelf; 65 | if (!self) return; 66 | NSLog(@"\ncache success : %@", response.responseObject); 67 | } success:^(YBNetworkResponse * _Nonnull response) { 68 | __strong typeof(weakSelf) self = weakSelf; 69 | if (!self) return; 70 | NSLog(@"\nresponse success : %@", response.responseObject); 71 | } failure:^(YBNetworkResponse * _Nonnull response) { 72 | __strong typeof(weakSelf) self = weakSelf; 73 | if (!self) return; 74 | NSLog(@"\nresponse failure : 类型 : %@", @(response.errorType)); 75 | }]; 76 | } 77 | 78 | - (void)searchB { 79 | [self.request start]; 80 | } 81 | 82 | #pragma mark - 83 | 84 | - (void)request:(__kindof YBBaseRequest *)request successWithResponse:(YBNetworkResponse *)response { 85 | NSLog(@"\nresponse success : %@", response.responseObject); 86 | } 87 | 88 | - (void)request:(__kindof YBBaseRequest *)request failureWithResponse:(YBNetworkResponse *)response { 89 | NSLog(@"\nresponse failure : 类型 : %@", @(response.errorType)); 90 | } 91 | 92 | #pragma mark - getter 93 | 94 | - (DefaultServerRequest *)request { 95 | if (!_request) { 96 | _request = [DefaultServerRequest new]; 97 | _request.delegate = self; 98 | _request.requestMethod = YBRequestMethodGET; 99 | _request.requestURI = @"charconvert/change.from"; 100 | _request.requestParameter = @{@"key":@"0e27c575047e83b407ff9e517cde9c76", @"type":@"2", @"text":@"哈哈哈哈"}; 101 | _request.repeatStrategy = YBNetworkRepeatStrategyCancelOldest; 102 | } 103 | return _request; 104 | } 105 | 106 | @end 107 | -------------------------------------------------------------------------------- /YBNetworkDemo/TestCase/为响应对象拓展属性/YBNetworkResponse+YBCustom.h: -------------------------------------------------------------------------------- 1 | // 2 | // YBNetworkResponse+YBCustom.h 3 | // YBNetworkDemo 4 | // 5 | // Created by 波儿菜 on 2019/9/27. 6 | // Copyright © 2019 杨波. All rights reserved. 7 | // 8 | 9 | #import "YBNetworkResponse.h" 10 | 11 | NS_ASSUME_NONNULL_BEGIN 12 | 13 | /// 网络响应错误类型 14 | typedef NS_ENUM(NSInteger, YBResponseErrorType) { 15 | /// 未知 16 | YBResponseErrorTypeUnknown, 17 | /// 超时 18 | YBResponseErrorTypeTimedOut, 19 | /// 取消 20 | YBResponseErrorTypeCancelled, 21 | /// 无网络 22 | YBResponseErrorTypeNoNetwork, 23 | /// 服务器错误 24 | YBResponseErrorTypeServerError, 25 | /// 登录状态过期 26 | YBResponseErrorTypeLoginExpired 27 | }; 28 | 29 | @interface YBNetworkResponse (YBCustom) 30 | 31 | /// 请求失败类型 (使用该属性做业务处理足够) 32 | @property (nonatomic, assign) YBResponseErrorType errorType; 33 | 34 | @end 35 | 36 | NS_ASSUME_NONNULL_END 37 | -------------------------------------------------------------------------------- /YBNetworkDemo/TestCase/为响应对象拓展属性/YBNetworkResponse+YBCustom.m: -------------------------------------------------------------------------------- 1 | // 2 | // YBNetworkResponse+YBCustom.m 3 | // YBNetworkDemo 4 | // 5 | // Created by 波儿菜 on 2019/9/27. 6 | // Copyright © 2019 杨波. All rights reserved. 7 | // 8 | 9 | #import "YBNetworkResponse+YBCustom.h" 10 | #import 11 | 12 | @implementation YBNetworkResponse (YBCustom) 13 | 14 | static void const *YBNetworkResponseErrorTypeKey = &YBNetworkResponseErrorTypeKey; 15 | - (void)setErrorType:(YBResponseErrorType)errorType { 16 | objc_setAssociatedObject(self, YBNetworkResponseErrorTypeKey, @(errorType), OBJC_ASSOCIATION_RETAIN_NONATOMIC); 17 | } 18 | - (YBResponseErrorType)errorType { 19 | NSNumber *tmp = objc_getAssociatedObject(self, YBNetworkResponseErrorTypeKey); 20 | return tmp.integerValue; 21 | } 22 | 23 | @end 24 | -------------------------------------------------------------------------------- /YBNetworkDemo/ViewController.h: -------------------------------------------------------------------------------- 1 | // 2 | // ViewController.h 3 | // YBNetworkDemo 4 | // 5 | // Created by 波儿菜 on 2019/4/9. 6 | // Copyright © 2019 波儿菜. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface ViewController : UIViewController 12 | 13 | 14 | @end 15 | 16 | -------------------------------------------------------------------------------- /YBNetworkDemo/ViewController.m: -------------------------------------------------------------------------------- 1 | // 2 | // ViewController.m 3 | // YBNetworkDemo 4 | // 5 | // Created by 波儿菜 on 2019/4/9. 6 | // Copyright © 2019 波儿菜. All rights reserved. 7 | // 8 | 9 | #import "ViewController.h" 10 | #import "TestViewController.h" 11 | 12 | @interface ViewController () 13 | 14 | @end 15 | 16 | @implementation ViewController 17 | 18 | - (void)viewDidLoad { 19 | [super viewDidLoad]; 20 | self.view.backgroundColor = UIColor.whiteColor; 21 | UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem]; 22 | button.bounds = CGRectMake(0, 0, 300, 100); 23 | button.center = self.view.center; 24 | button.titleLabel.font = [UIFont boldSystemFontOfSize:30]; 25 | [button setTitle:@"跳转" forState:UIControlStateNormal]; 26 | [button addTarget:self action:@selector(clickButton) forControlEvents:UIControlEventTouchUpInside]; 27 | [self.view addSubview:button]; 28 | } 29 | 30 | - (void)clickButton { 31 | [self.navigationController pushViewController:TestViewController.new animated:YES]; 32 | } 33 | 34 | @end 35 | -------------------------------------------------------------------------------- /YBNetworkDemo/main.m: -------------------------------------------------------------------------------- 1 | // 2 | // main.m 3 | // YBNetworkDemo 4 | // 5 | // Created by 波儿菜 on 2019/4/9. 6 | // Copyright © 2019 波儿菜. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "AppDelegate.h" 11 | 12 | int main(int argc, char * argv[]) { 13 | @autoreleasepool { 14 | return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); 15 | } 16 | } 17 | --------------------------------------------------------------------------------