├── .gitignore ├── LICENSE ├── PPNetworkHelper.podspec ├── PPNetworkHelper.xcodeproj ├── project.pbxproj ├── project.xcworkspace │ ├── contents.xcworkspacedata │ └── xcuserdata │ │ ├── AndyPang.xcuserdatad │ │ └── UserInterfaceState.xcuserstate │ │ ├── YiAi.xcuserdatad │ │ └── UserInterfaceState.xcuserstate │ │ ├── duoyi.xcuserdatad │ │ └── UserInterfaceState.xcuserstate │ │ └── huangqisheng.xcuserdatad │ │ └── UserInterfaceState.xcuserstate └── xcuserdata │ ├── AndyPang.xcuserdatad │ ├── xcdebugger │ │ └── Breakpoints_v2.xcbkptlist │ └── xcschemes │ │ ├── PPNetworkHelper.xcscheme │ │ └── xcschememanagement.plist │ ├── YiAi.xcuserdatad │ ├── xcdebugger │ │ └── Breakpoints_v2.xcbkptlist │ └── xcschemes │ │ ├── PPNetworkHelper.xcscheme │ │ └── xcschememanagement.plist │ ├── duoyi.xcuserdatad │ ├── xcdebugger │ │ └── Breakpoints_v2.xcbkptlist │ └── xcschemes │ │ ├── PPNetworkHelper.xcscheme │ │ └── xcschememanagement.plist │ └── huangqisheng.xcuserdatad │ └── xcschemes │ ├── PPNetworkHelper.xcscheme │ └── xcschememanagement.plist ├── PPNetworkHelper ├── AFNetworking │ ├── AFNetworking │ │ ├── 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 ├── AppDelegate.h ├── AppDelegate.m ├── Assets.xcassets │ └── AppIcon.appiconset │ │ └── Contents.json ├── Base.lproj │ ├── LaunchScreen.storyboard │ └── Main.storyboard ├── Info.plist ├── PPHTTPRequest.h ├── PPHTTPRequest.m ├── PPInterfacedConst.h ├── PPInterfacedConst.m ├── PPNetworkHelper │ ├── PPNetworkCache.h │ ├── PPNetworkCache.m │ ├── PPNetworkHelper.h │ └── PPNetworkHelper.m ├── ViewController.h ├── ViewController.m ├── YYCache │ ├── YYCache.h │ ├── YYCache.m │ ├── YYDiskCache.h │ ├── YYDiskCache.m │ ├── YYKVStorage.h │ ├── YYKVStorage.m │ ├── YYMemoryCache.h │ └── YYMemoryCache.m └── main.m ├── PPNetworkHelperTests ├── Info.plist └── PPNetworkHelperTests.m ├── Picture ├── PPNetworkHelper.png └── network.gif └── README.md /.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 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) 2016 jkpang 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 | -------------------------------------------------------------------------------- /PPNetworkHelper.podspec: -------------------------------------------------------------------------------- 1 | 2 | Pod::Spec.new do |s| 3 | 4 | s.name = "PPNetworkHelper" 5 | s.version = "0.8.1" 6 | s.summary = "AFNetworking 3.x 与YYCache封装,一句代码搞定数据请求与缓存,告别FMDB!控制台直接打印json中文字符,调试更方便" 7 | 8 | s.homepage = "https://github.com/jkpang/PPNetworkHelper.git" 9 | 10 | s.license = { :type => "MIT", :file => "LICENSE" } 11 | 12 | s.author = { "jkpang" => "jkpang@outlook.com" } 13 | 14 | s.platform = :ios, "7.0" 15 | 16 | s.source = { :git => "https://github.com/jkpang/PPNetworkHelper.git", :tag => s.version.to_s } 17 | 18 | s.source_files = "PPNetworkHelper/PPNetworkHelper/*.{h,m}" 19 | 20 | s.dependency 'AFNetworking', '~> 3.2.0' 21 | 22 | s.dependency 'YYCache', '~> 1.0.4' 23 | 24 | s.requires_arc = true 25 | 26 | end 27 | -------------------------------------------------------------------------------- /PPNetworkHelper.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /PPNetworkHelper.xcodeproj/project.xcworkspace/xcuserdata/AndyPang.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jkpang/PPNetworkHelper/54505979e1522fed07cc0a4ecba057010b0d8c6b/PPNetworkHelper.xcodeproj/project.xcworkspace/xcuserdata/AndyPang.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /PPNetworkHelper.xcodeproj/project.xcworkspace/xcuserdata/YiAi.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jkpang/PPNetworkHelper/54505979e1522fed07cc0a4ecba057010b0d8c6b/PPNetworkHelper.xcodeproj/project.xcworkspace/xcuserdata/YiAi.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /PPNetworkHelper.xcodeproj/project.xcworkspace/xcuserdata/duoyi.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jkpang/PPNetworkHelper/54505979e1522fed07cc0a4ecba057010b0d8c6b/PPNetworkHelper.xcodeproj/project.xcworkspace/xcuserdata/duoyi.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /PPNetworkHelper.xcodeproj/project.xcworkspace/xcuserdata/huangqisheng.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jkpang/PPNetworkHelper/54505979e1522fed07cc0a4ecba057010b0d8c6b/PPNetworkHelper.xcodeproj/project.xcworkspace/xcuserdata/huangqisheng.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /PPNetworkHelper.xcodeproj/xcuserdata/AndyPang.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | -------------------------------------------------------------------------------- /PPNetworkHelper.xcodeproj/xcuserdata/AndyPang.xcuserdatad/xcschemes/PPNetworkHelper.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 33 | 39 | 40 | 41 | 42 | 43 | 49 | 50 | 51 | 52 | 53 | 54 | 64 | 66 | 72 | 73 | 74 | 75 | 79 | 80 | 81 | 82 | 83 | 84 | 90 | 92 | 98 | 99 | 100 | 101 | 103 | 104 | 107 | 108 | 109 | -------------------------------------------------------------------------------- /PPNetworkHelper.xcodeproj/xcuserdata/AndyPang.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | PPNetworkHelper.xcscheme 8 | 9 | orderHint 10 | 0 11 | 12 | 13 | SuppressBuildableAutocreation 14 | 15 | 22142E251D5E096E00EE2C40 16 | 17 | primary 18 | 19 | 20 | 22142E3E1D5E096E00EE2C40 21 | 22 | primary 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /PPNetworkHelper.xcodeproj/xcuserdata/YiAi.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | -------------------------------------------------------------------------------- /PPNetworkHelper.xcodeproj/xcuserdata/YiAi.xcuserdatad/xcschemes/PPNetworkHelper.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 33 | 39 | 40 | 41 | 42 | 43 | 49 | 50 | 51 | 52 | 53 | 54 | 64 | 66 | 72 | 73 | 74 | 75 | 76 | 77 | 83 | 85 | 91 | 92 | 93 | 94 | 96 | 97 | 100 | 101 | 102 | -------------------------------------------------------------------------------- /PPNetworkHelper.xcodeproj/xcuserdata/YiAi.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | PPNetworkHelper.xcscheme 8 | 9 | orderHint 10 | 0 11 | 12 | 13 | SuppressBuildableAutocreation 14 | 15 | 22142E251D5E096E00EE2C40 16 | 17 | primary 18 | 19 | 20 | 22142E3E1D5E096E00EE2C40 21 | 22 | primary 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /PPNetworkHelper.xcodeproj/xcuserdata/duoyi.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | -------------------------------------------------------------------------------- /PPNetworkHelper.xcodeproj/xcuserdata/duoyi.xcuserdatad/xcschemes/PPNetworkHelper.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 33 | 39 | 40 | 41 | 42 | 43 | 49 | 50 | 51 | 52 | 53 | 54 | 64 | 66 | 72 | 73 | 74 | 75 | 76 | 77 | 83 | 85 | 91 | 92 | 93 | 94 | 96 | 97 | 100 | 101 | 102 | -------------------------------------------------------------------------------- /PPNetworkHelper.xcodeproj/xcuserdata/duoyi.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | PPNetworkHelper.xcscheme 8 | 9 | orderHint 10 | 0 11 | 12 | 13 | SuppressBuildableAutocreation 14 | 15 | 22142E251D5E096E00EE2C40 16 | 17 | primary 18 | 19 | 20 | 22142E3E1D5E096E00EE2C40 21 | 22 | primary 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /PPNetworkHelper.xcodeproj/xcuserdata/huangqisheng.xcuserdatad/xcschemes/PPNetworkHelper.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 33 | 39 | 40 | 41 | 42 | 43 | 49 | 50 | 51 | 52 | 53 | 54 | 64 | 66 | 72 | 73 | 74 | 75 | 76 | 77 | 83 | 85 | 91 | 92 | 93 | 94 | 96 | 97 | 100 | 101 | 102 | -------------------------------------------------------------------------------- /PPNetworkHelper.xcodeproj/xcuserdata/huangqisheng.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | PPNetworkHelper.xcscheme 8 | 9 | orderHint 10 | 0 11 | 12 | 13 | SuppressBuildableAutocreation 14 | 15 | 22142E251D5E096E00EE2C40 16 | 17 | primary 18 | 19 | 20 | 22142E3E1D5E096E00EE2C40 21 | 22 | primary 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /PPNetworkHelper/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 | /// @name Starting & Stopping Reachability Monitoring 112 | ///-------------------------------------------------- 113 | 114 | /** 115 | Starts monitoring for changes in network reachability status. 116 | */ 117 | - (void)startMonitoring; 118 | 119 | /** 120 | Stops monitoring for changes in network reachability status. 121 | */ 122 | - (void)stopMonitoring; 123 | 124 | ///------------------------------------------------- 125 | /// @name Getting Localized Reachability Description 126 | ///------------------------------------------------- 127 | 128 | /** 129 | Returns a localized string representation of the current network reachability status. 130 | */ 131 | - (NSString *)localizedNetworkReachabilityStatusString; 132 | 133 | ///--------------------------------------------------- 134 | /// @name Setting Network Reachability Change Callback 135 | ///--------------------------------------------------- 136 | 137 | /** 138 | Sets a callback to be executed when the network availability of the `baseURL` host changes. 139 | 140 | @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`. 141 | */ 142 | - (void)setReachabilityStatusChangeBlock:(nullable void (^)(AFNetworkReachabilityStatus status))block; 143 | 144 | @end 145 | 146 | ///---------------- 147 | /// @name Constants 148 | ///---------------- 149 | 150 | /** 151 | ## Network Reachability 152 | 153 | The following constants are provided by `AFNetworkReachabilityManager` as possible network reachability statuses. 154 | 155 | enum { 156 | AFNetworkReachabilityStatusUnknown, 157 | AFNetworkReachabilityStatusNotReachable, 158 | AFNetworkReachabilityStatusReachableViaWWAN, 159 | AFNetworkReachabilityStatusReachableViaWiFi, 160 | } 161 | 162 | `AFNetworkReachabilityStatusUnknown` 163 | The `baseURL` host reachability is not known. 164 | 165 | `AFNetworkReachabilityStatusNotReachable` 166 | The `baseURL` host cannot be reached. 167 | 168 | `AFNetworkReachabilityStatusReachableViaWWAN` 169 | The `baseURL` host can be reached via a cellular connection, such as EDGE or GPRS. 170 | 171 | `AFNetworkReachabilityStatusReachableViaWiFi` 172 | The `baseURL` host can be reached via a Wi-Fi connection. 173 | 174 | ### Keys for Notification UserInfo Dictionary 175 | 176 | Strings that are used as keys in a `userInfo` dictionary in a network reachability status change notification. 177 | 178 | `AFNetworkingReachabilityNotificationStatusItem` 179 | A key in the userInfo dictionary in a `AFNetworkingReachabilityDidChangeNotification` notification. 180 | The corresponding value is an `NSNumber` object representing the `AFNetworkReachabilityStatus` value for the current reachability status. 181 | */ 182 | 183 | ///-------------------- 184 | /// @name Notifications 185 | ///-------------------- 186 | 187 | /** 188 | Posted when network reachability changes. 189 | 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. 190 | 191 | @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`). 192 | */ 193 | FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityDidChangeNotification; 194 | FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityNotificationStatusItem; 195 | 196 | ///-------------------- 197 | /// @name Functions 198 | ///-------------------- 199 | 200 | /** 201 | Returns a localized string representation of an `AFNetworkReachabilityStatus` value. 202 | */ 203 | FOUNDATION_EXPORT NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status); 204 | 205 | NS_ASSUME_NONNULL_END 206 | #endif 207 | -------------------------------------------------------------------------------- /PPNetworkHelper/AFNetworking/AFNetworking/AFNetworkReachabilityManager.m: -------------------------------------------------------------------------------- 1 | // AFNetworkReachabilityManager.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 "AFNetworkReachabilityManager.h" 23 | #if !TARGET_OS_WATCH 24 | 25 | #import 26 | #import 27 | #import 28 | #import 29 | #import 30 | 31 | NSString * const AFNetworkingReachabilityDidChangeNotification = @"com.alamofire.networking.reachability.change"; 32 | NSString * const AFNetworkingReachabilityNotificationStatusItem = @"AFNetworkingReachabilityNotificationStatusItem"; 33 | 34 | typedef void (^AFNetworkReachabilityStatusBlock)(AFNetworkReachabilityStatus status); 35 | 36 | NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status) { 37 | switch (status) { 38 | case AFNetworkReachabilityStatusNotReachable: 39 | return NSLocalizedStringFromTable(@"Not Reachable", @"AFNetworking", nil); 40 | case AFNetworkReachabilityStatusReachableViaWWAN: 41 | return NSLocalizedStringFromTable(@"Reachable via WWAN", @"AFNetworking", nil); 42 | case AFNetworkReachabilityStatusReachableViaWiFi: 43 | return NSLocalizedStringFromTable(@"Reachable via WiFi", @"AFNetworking", nil); 44 | case AFNetworkReachabilityStatusUnknown: 45 | default: 46 | return NSLocalizedStringFromTable(@"Unknown", @"AFNetworking", nil); 47 | } 48 | } 49 | 50 | static AFNetworkReachabilityStatus AFNetworkReachabilityStatusForFlags(SCNetworkReachabilityFlags flags) { 51 | BOOL isReachable = ((flags & kSCNetworkReachabilityFlagsReachable) != 0); 52 | BOOL needsConnection = ((flags & kSCNetworkReachabilityFlagsConnectionRequired) != 0); 53 | BOOL canConnectionAutomatically = (((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) || ((flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0)); 54 | BOOL canConnectWithoutUserInteraction = (canConnectionAutomatically && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0); 55 | BOOL isNetworkReachable = (isReachable && (!needsConnection || canConnectWithoutUserInteraction)); 56 | 57 | AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusUnknown; 58 | if (isNetworkReachable == NO) { 59 | status = AFNetworkReachabilityStatusNotReachable; 60 | } 61 | #if TARGET_OS_IPHONE 62 | else if ((flags & kSCNetworkReachabilityFlagsIsWWAN) != 0) { 63 | status = AFNetworkReachabilityStatusReachableViaWWAN; 64 | } 65 | #endif 66 | else { 67 | status = AFNetworkReachabilityStatusReachableViaWiFi; 68 | } 69 | 70 | return status; 71 | } 72 | 73 | /** 74 | * Queue a status change notification for the main thread. 75 | * 76 | * This is done to ensure that the notifications are received in the same order 77 | * as they are sent. If notifications are sent directly, it is possible that 78 | * a queued notification (for an earlier status condition) is processed after 79 | * the later update, resulting in the listener being left in the wrong state. 80 | */ 81 | static void AFPostReachabilityStatusChange(SCNetworkReachabilityFlags flags, AFNetworkReachabilityStatusBlock block) { 82 | AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags); 83 | dispatch_async(dispatch_get_main_queue(), ^{ 84 | if (block) { 85 | block(status); 86 | } 87 | NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; 88 | NSDictionary *userInfo = @{ AFNetworkingReachabilityNotificationStatusItem: @(status) }; 89 | [notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:userInfo]; 90 | }); 91 | } 92 | 93 | static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkReachabilityFlags flags, void *info) { 94 | AFPostReachabilityStatusChange(flags, (__bridge AFNetworkReachabilityStatusBlock)info); 95 | } 96 | 97 | 98 | static const void * AFNetworkReachabilityRetainCallback(const void *info) { 99 | return Block_copy(info); 100 | } 101 | 102 | static void AFNetworkReachabilityReleaseCallback(const void *info) { 103 | if (info) { 104 | Block_release(info); 105 | } 106 | } 107 | 108 | @interface AFNetworkReachabilityManager () 109 | @property (readonly, nonatomic, assign) SCNetworkReachabilityRef networkReachability; 110 | @property (readwrite, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus; 111 | @property (readwrite, nonatomic, copy) AFNetworkReachabilityStatusBlock networkReachabilityStatusBlock; 112 | @end 113 | 114 | @implementation AFNetworkReachabilityManager 115 | 116 | + (instancetype)sharedManager { 117 | static AFNetworkReachabilityManager *_sharedManager = nil; 118 | static dispatch_once_t onceToken; 119 | dispatch_once(&onceToken, ^{ 120 | _sharedManager = [self manager]; 121 | }); 122 | 123 | return _sharedManager; 124 | } 125 | 126 | + (instancetype)managerForDomain:(NSString *)domain { 127 | SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [domain UTF8String]); 128 | 129 | AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability]; 130 | 131 | CFRelease(reachability); 132 | 133 | return manager; 134 | } 135 | 136 | + (instancetype)managerForAddress:(const void *)address { 137 | SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)address); 138 | AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability]; 139 | 140 | CFRelease(reachability); 141 | 142 | return manager; 143 | } 144 | 145 | + (instancetype)manager 146 | { 147 | #if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 90000) || (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) 148 | struct sockaddr_in6 address; 149 | bzero(&address, sizeof(address)); 150 | address.sin6_len = sizeof(address); 151 | address.sin6_family = AF_INET6; 152 | #else 153 | struct sockaddr_in address; 154 | bzero(&address, sizeof(address)); 155 | address.sin_len = sizeof(address); 156 | address.sin_family = AF_INET; 157 | #endif 158 | return [self managerForAddress:&address]; 159 | } 160 | 161 | - (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability { 162 | self = [super init]; 163 | if (!self) { 164 | return nil; 165 | } 166 | 167 | _networkReachability = CFRetain(reachability); 168 | self.networkReachabilityStatus = AFNetworkReachabilityStatusUnknown; 169 | 170 | return self; 171 | } 172 | 173 | - (instancetype)init NS_UNAVAILABLE 174 | { 175 | return nil; 176 | } 177 | 178 | - (void)dealloc { 179 | [self stopMonitoring]; 180 | 181 | if (_networkReachability != NULL) { 182 | CFRelease(_networkReachability); 183 | } 184 | } 185 | 186 | #pragma mark - 187 | 188 | - (BOOL)isReachable { 189 | return [self isReachableViaWWAN] || [self isReachableViaWiFi]; 190 | } 191 | 192 | - (BOOL)isReachableViaWWAN { 193 | return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN; 194 | } 195 | 196 | - (BOOL)isReachableViaWiFi { 197 | return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi; 198 | } 199 | 200 | #pragma mark - 201 | 202 | - (void)startMonitoring { 203 | [self stopMonitoring]; 204 | 205 | if (!self.networkReachability) { 206 | return; 207 | } 208 | 209 | __weak __typeof(self)weakSelf = self; 210 | AFNetworkReachabilityStatusBlock callback = ^(AFNetworkReachabilityStatus status) { 211 | __strong __typeof(weakSelf)strongSelf = weakSelf; 212 | 213 | strongSelf.networkReachabilityStatus = status; 214 | if (strongSelf.networkReachabilityStatusBlock) { 215 | strongSelf.networkReachabilityStatusBlock(status); 216 | } 217 | 218 | }; 219 | 220 | SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL}; 221 | SCNetworkReachabilitySetCallback(self.networkReachability, AFNetworkReachabilityCallback, &context); 222 | SCNetworkReachabilityScheduleWithRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes); 223 | 224 | dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),^{ 225 | SCNetworkReachabilityFlags flags; 226 | if (SCNetworkReachabilityGetFlags(self.networkReachability, &flags)) { 227 | AFPostReachabilityStatusChange(flags, callback); 228 | } 229 | }); 230 | } 231 | 232 | - (void)stopMonitoring { 233 | if (!self.networkReachability) { 234 | return; 235 | } 236 | 237 | SCNetworkReachabilityUnscheduleFromRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes); 238 | } 239 | 240 | #pragma mark - 241 | 242 | - (NSString *)localizedNetworkReachabilityStatusString { 243 | return AFStringFromNetworkReachabilityStatus(self.networkReachabilityStatus); 244 | } 245 | 246 | #pragma mark - 247 | 248 | - (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block { 249 | self.networkReachabilityStatusBlock = block; 250 | } 251 | 252 | #pragma mark - NSKeyValueObserving 253 | 254 | + (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key { 255 | if ([key isEqualToString:@"reachable"] || [key isEqualToString:@"reachableViaWWAN"] || [key isEqualToString:@"reachableViaWiFi"]) { 256 | return [NSSet setWithObject:@"networkReachabilityStatus"]; 257 | } 258 | 259 | return [super keyPathsForValuesAffectingValueForKey:key]; 260 | } 261 | 262 | @end 263 | #endif 264 | -------------------------------------------------------------------------------- /PPNetworkHelper/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 | -------------------------------------------------------------------------------- /PPNetworkHelper/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 | -------------------------------------------------------------------------------- /PPNetworkHelper/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 | -------------------------------------------------------------------------------- /PPNetworkHelper/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 | Adds the image to the cache using an identifier created from the request and additional identifier. 77 | 78 | @param image The image to cache. 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 | - (void)addImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier; 83 | 84 | /** 85 | Removes the image from the cache using an identifier created from the request and additional identifier. 86 | 87 | @param request The unique URL request identifing the image asset. 88 | @param identifier The additional identifier to apply to the URL request to identify the image. 89 | 90 | @return A BOOL indicating whether or not all images were removed from the cache. 91 | */ 92 | - (BOOL)removeImageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier; 93 | 94 | /** 95 | Returns the image from the cache associated with an identifier created from the request and additional identifier. 96 | 97 | @param request The unique URL request identifing the image asset. 98 | @param identifier The additional identifier to apply to the URL request to identify the image. 99 | 100 | @return An image for the matching request and identifier, or nil. 101 | */ 102 | - (nullable UIImage *)imageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier; 103 | 104 | @end 105 | 106 | /** 107 | 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. 108 | */ 109 | @interface AFAutoPurgingImageCache : NSObject 110 | 111 | /** 112 | The total memory capacity of the cache in bytes. 113 | */ 114 | @property (nonatomic, assign) UInt64 memoryCapacity; 115 | 116 | /** 117 | The preferred memory usage after purge in bytes. During a purge, images will be purged until the memory capacity drops below this limit. 118 | */ 119 | @property (nonatomic, assign) UInt64 preferredMemoryUsageAfterPurge; 120 | 121 | /** 122 | The current total memory usage in bytes of all images stored within the cache. 123 | */ 124 | @property (nonatomic, assign, readonly) UInt64 memoryUsage; 125 | 126 | /** 127 | 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`. 128 | 129 | @return The new `AutoPurgingImageCache` instance. 130 | */ 131 | - (instancetype)init; 132 | 133 | /** 134 | Initialies the `AutoPurgingImageCache` instance with the given memory capacity and preferred memory usage 135 | after purge limit. 136 | 137 | @param memoryCapacity The total memory capacity of the cache in bytes. 138 | @param preferredMemoryCapacity The preferred memory usage after purge in bytes. 139 | 140 | @return The new `AutoPurgingImageCache` instance. 141 | */ 142 | - (instancetype)initWithMemoryCapacity:(UInt64)memoryCapacity preferredMemoryCapacity:(UInt64)preferredMemoryCapacity; 143 | 144 | @end 145 | 146 | NS_ASSUME_NONNULL_END 147 | 148 | #endif 149 | 150 | -------------------------------------------------------------------------------- /PPNetworkHelper/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 | @end 200 | 201 | #endif 202 | -------------------------------------------------------------------------------- /PPNetworkHelper/AFNetworking/UIKit+AFNetworking/AFImageDownloader.h: -------------------------------------------------------------------------------- 1 | // AFImageDownloader.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_IOS || TARGET_OS_TV 25 | 26 | #import 27 | #import "AFAutoPurgingImageCache.h" 28 | #import "AFHTTPSessionManager.h" 29 | 30 | NS_ASSUME_NONNULL_BEGIN 31 | 32 | typedef NS_ENUM(NSInteger, AFImageDownloadPrioritization) { 33 | AFImageDownloadPrioritizationFIFO, 34 | AFImageDownloadPrioritizationLIFO 35 | }; 36 | 37 | /** 38 | The `AFImageDownloadReceipt` is an object vended by the `AFImageDownloader` when starting a data task. It can be used to cancel active tasks running on the `AFImageDownloader` session. As a general rule, image data tasks should be cancelled using the `AFImageDownloadReceipt` instead of calling `cancel` directly on the `task` itself. The `AFImageDownloader` is optimized to handle duplicate task scenarios as well as pending versus active downloads. 39 | */ 40 | @interface AFImageDownloadReceipt : NSObject 41 | 42 | /** 43 | The data task created by the `AFImageDownloader`. 44 | */ 45 | @property (nonatomic, strong) NSURLSessionDataTask *task; 46 | 47 | /** 48 | The unique identifier for the success and failure blocks when duplicate requests are made. 49 | */ 50 | @property (nonatomic, strong) NSUUID *receiptID; 51 | @end 52 | 53 | /** The `AFImageDownloader` class is responsible for downloading images in parallel on a prioritized queue. Incoming downloads are added to the front or back of the queue depending on the download prioritization. Each downloaded image is cached in the underlying `NSURLCache` as well as the in-memory image cache. By default, any download request with a cached image equivalent in the image cache will automatically be served the cached image representation. 54 | */ 55 | @interface AFImageDownloader : NSObject 56 | 57 | /** 58 | The image cache used to store all downloaded images in. `AFAutoPurgingImageCache` by default. 59 | */ 60 | @property (nonatomic, strong, nullable) id imageCache; 61 | 62 | /** 63 | The `AFHTTPSessionManager` used to download images. By default, this is configured with an `AFImageResponseSerializer`, and a shared `NSURLCache` for all image downloads. 64 | */ 65 | @property (nonatomic, strong) AFHTTPSessionManager *sessionManager; 66 | 67 | /** 68 | Defines the order prioritization of incoming download requests being inserted into the queue. `AFImageDownloadPrioritizationFIFO` by default. 69 | */ 70 | @property (nonatomic, assign) AFImageDownloadPrioritization downloadPrioritizaton; 71 | 72 | /** 73 | The shared default instance of `AFImageDownloader` initialized with default values. 74 | */ 75 | + (instancetype)defaultInstance; 76 | 77 | /** 78 | Creates a default `NSURLCache` with common usage parameter values. 79 | 80 | @returns The default `NSURLCache` instance. 81 | */ 82 | + (NSURLCache *)defaultURLCache; 83 | 84 | /** 85 | Default initializer 86 | 87 | @return An instance of `AFImageDownloader` initialized with default values. 88 | */ 89 | - (instancetype)init; 90 | 91 | /** 92 | Initializes the `AFImageDownloader` instance with the given session manager, download prioritization, maximum active download count and image cache. 93 | 94 | @param sessionManager The session manager to use to download images. 95 | @param downloadPrioritization The download prioritization of the download queue. 96 | @param maximumActiveDownloads The maximum number of active downloads allowed at any given time. Recommend `4`. 97 | @param imageCache The image cache used to store all downloaded images in. 98 | 99 | @return The new `AFImageDownloader` instance. 100 | */ 101 | - (instancetype)initWithSessionManager:(AFHTTPSessionManager *)sessionManager 102 | downloadPrioritization:(AFImageDownloadPrioritization)downloadPrioritization 103 | maximumActiveDownloads:(NSInteger)maximumActiveDownloads 104 | imageCache:(nullable id )imageCache; 105 | 106 | /** 107 | Creates a data task using the `sessionManager` instance for the specified URL request. 108 | 109 | If the same data task is already in the queue or currently being downloaded, the success and failure blocks are 110 | appended to the already existing task. Once the task completes, all success or failure blocks attached to the 111 | task are executed in the order they were added. 112 | 113 | @param request The URL request. 114 | @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`. 115 | @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. 116 | 117 | @return The image download receipt for the data task if available. `nil` if the image is stored in the cache. 118 | cache and the URL request cache policy allows the cache to be used. 119 | */ 120 | - (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request 121 | success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success 122 | failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; 123 | 124 | /** 125 | Creates a data task using the `sessionManager` instance for the specified URL request. 126 | 127 | If the same data task is already in the queue or currently being downloaded, the success and failure blocks are 128 | appended to the already existing task. Once the task completes, all success or failure blocks attached to the 129 | task are executed in the order they were added. 130 | 131 | @param request The URL request. 132 | @param receiptID The identifier to use for the download receipt that will be created for this request. This must be a unique identifier that does not represent any other request. 133 | @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`. 134 | @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. 135 | 136 | @return The image download receipt for the data task if available. `nil` if the image is stored in the cache. 137 | cache and the URL request cache policy allows the cache to be used. 138 | */ 139 | - (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request 140 | withReceiptID:(NSUUID *)receiptID 141 | success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success 142 | failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; 143 | 144 | /** 145 | Cancels the data task in the receipt by removing the corresponding success and failure blocks and cancelling the data task if necessary. 146 | 147 | If the data task is pending in the queue, it will be cancelled if no other success and failure blocks are registered with the data task. If the data task is currently executing or is already completed, the success and failure blocks are removed and will not be called when the task finishes. 148 | 149 | @param imageDownloadReceipt The image download receipt to cancel. 150 | */ 151 | - (void)cancelTaskForImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt; 152 | 153 | @end 154 | 155 | #endif 156 | 157 | NS_ASSUME_NONNULL_END 158 | -------------------------------------------------------------------------------- /PPNetworkHelper/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 | -------------------------------------------------------------------------------- /PPNetworkHelper/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 | -------------------------------------------------------------------------------- /PPNetworkHelper/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 | 75 | #pragma clang diagnostic push 76 | #pragma clang diagnostic ignored "-Wreceiver-is-weak" 77 | #pragma clang diagnostic ignored "-Warc-repeated-use-of-weak" 78 | if (task.state == NSURLSessionTaskStateRunning) { 79 | [self.activityIndicatorView startAnimating]; 80 | } else { 81 | [self.activityIndicatorView stopAnimating]; 82 | } 83 | #pragma clang diagnostic pop 84 | 85 | [notificationCenter addObserver:self selector:@selector(af_startAnimating) name:AFNetworkingTaskDidResumeNotification object:task]; 86 | [notificationCenter addObserver:self selector:@selector(af_stopAnimating) name:AFNetworkingTaskDidCompleteNotification object:task]; 87 | [notificationCenter addObserver:self selector:@selector(af_stopAnimating) name:AFNetworkingTaskDidSuspendNotification object:task]; 88 | } 89 | } 90 | } 91 | 92 | #pragma mark - 93 | 94 | - (void)af_startAnimating { 95 | dispatch_async(dispatch_get_main_queue(), ^{ 96 | #pragma clang diagnostic push 97 | #pragma clang diagnostic ignored "-Wreceiver-is-weak" 98 | [self.activityIndicatorView startAnimating]; 99 | #pragma clang diagnostic pop 100 | }); 101 | } 102 | 103 | - (void)af_stopAnimating { 104 | dispatch_async(dispatch_get_main_queue(), ^{ 105 | #pragma clang diagnostic push 106 | #pragma clang diagnostic ignored "-Wreceiver-is-weak" 107 | [self.activityIndicatorView stopAnimating]; 108 | #pragma clang diagnostic pop 109 | }); 110 | } 111 | 112 | #pragma mark - 113 | 114 | - (void)dealloc { 115 | NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; 116 | 117 | [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; 118 | [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; 119 | [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; 120 | } 121 | 122 | @end 123 | 124 | #endif 125 | -------------------------------------------------------------------------------- /PPNetworkHelper/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h: -------------------------------------------------------------------------------- 1 | // UIButton+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 `UIButton` class. The methods in this category provide support for loading remote images and background images asynchronously from a URL. 36 | 37 | @warning Compound values for control `state` (such as `UIControlStateHighlighted | UIControlStateDisabled`) are unsupported. 38 | */ 39 | @interface UIButton (AFNetworking) 40 | 41 | ///------------------------------------ 42 | /// @name Accessing the Image Downloader 43 | ///------------------------------------ 44 | 45 | /** 46 | Set the shared image downloader used to download images. 47 | 48 | @param imageDownloader The shared image downloader used to download images. 49 | */ 50 | + (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader; 51 | 52 | /** 53 | The shared image downloader used to download images. 54 | */ 55 | + (AFImageDownloader *)sharedImageDownloader; 56 | 57 | ///-------------------- 58 | /// @name Setting Image 59 | ///-------------------- 60 | 61 | /** 62 | Asynchronously downloads an image from the specified URL, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. 63 | 64 | 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. 65 | 66 | @param state The control state. 67 | @param url The URL used for the image request. 68 | */ 69 | - (void)setImageForState:(UIControlState)state 70 | withURL:(NSURL *)url; 71 | 72 | /** 73 | Asynchronously downloads an image from the specified URL, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. 74 | 75 | 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. 76 | 77 | @param state The control state. 78 | @param url The URL used for the image request. 79 | @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the button will not change its image until the image request finishes. 80 | */ 81 | - (void)setImageForState:(UIControlState)state 82 | withURL:(NSURL *)url 83 | placeholderImage:(nullable UIImage *)placeholderImage; 84 | 85 | /** 86 | Asynchronously downloads an image from the specified URL request, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. 87 | 88 | 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. 89 | 90 | If a success block is specified, it is the responsibility of the block to set the image of the button before returning. If no success block is specified, the default behavior of setting the image with `setImage:forState:` is applied. 91 | 92 | @param state The control state. 93 | @param urlRequest The URL request used for the image request. 94 | @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the button will not change its image until the image request finishes. 95 | @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`. 96 | @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. 97 | */ 98 | - (void)setImageForState:(UIControlState)state 99 | withURLRequest:(NSURLRequest *)urlRequest 100 | placeholderImage:(nullable UIImage *)placeholderImage 101 | success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success 102 | failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; 103 | 104 | 105 | ///------------------------------- 106 | /// @name Setting Background Image 107 | ///------------------------------- 108 | 109 | /** 110 | Asynchronously downloads an image from the specified URL, and sets it as the background image for the specified state once the request is finished. Any previous background image request for the receiver will be cancelled. 111 | 112 | If the background image is cached locally, the background image is set immediately, otherwise the specified placeholder background image will be set immediately, and then the remote background image will be set once the request is finished. 113 | 114 | @param state The control state. 115 | @param url The URL used for the background image request. 116 | */ 117 | - (void)setBackgroundImageForState:(UIControlState)state 118 | withURL:(NSURL *)url; 119 | 120 | /** 121 | Asynchronously downloads an image from the specified URL, and sets it as the background image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. 122 | 123 | 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. 124 | 125 | @param state The control state. 126 | @param url The URL used for the background image request. 127 | @param placeholderImage The background image to be set initially, until the background image request finishes. If `nil`, the button will not change its background image until the background image request finishes. 128 | */ 129 | - (void)setBackgroundImageForState:(UIControlState)state 130 | withURL:(NSURL *)url 131 | placeholderImage:(nullable UIImage *)placeholderImage; 132 | 133 | /** 134 | Asynchronously downloads an image from the specified URL request, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. 135 | 136 | 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. 137 | 138 | If a success block is specified, it is the responsibility of the block to set the image of the button before returning. If no success block is specified, the default behavior of setting the image with `setBackgroundImage:forState:` is applied. 139 | 140 | @param state The control state. 141 | @param urlRequest The URL request used for the image request. 142 | @param placeholderImage The background image to be set initially, until the background image request finishes. If `nil`, the button will not change its background image until the background image request finishes. 143 | @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`. 144 | @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. 145 | */ 146 | - (void)setBackgroundImageForState:(UIControlState)state 147 | withURLRequest:(NSURLRequest *)urlRequest 148 | placeholderImage:(nullable UIImage *)placeholderImage 149 | success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success 150 | failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; 151 | 152 | 153 | ///------------------------------ 154 | /// @name Canceling Image Loading 155 | ///------------------------------ 156 | 157 | /** 158 | Cancels any executing image task for the specified control state of the receiver, if one exists. 159 | 160 | @param state The control state. 161 | */ 162 | - (void)cancelImageDownloadTaskForState:(UIControlState)state; 163 | 164 | /** 165 | Cancels any executing background image task for the specified control state of the receiver, if one exists. 166 | 167 | @param state The control state. 168 | */ 169 | - (void)cancelBackgroundImageDownloadTaskForState:(UIControlState)state; 170 | 171 | @end 172 | 173 | NS_ASSUME_NONNULL_END 174 | 175 | #endif 176 | -------------------------------------------------------------------------------- /PPNetworkHelper/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 | -------------------------------------------------------------------------------- /PPNetworkHelper/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 | -------------------------------------------------------------------------------- /PPNetworkHelper/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 | 52 | #pragma clang diagnostic push 53 | #pragma clang diagnostic ignored "-Wgnu" 54 | return objc_getAssociatedObject(self, @selector(sharedImageDownloader)) ?: [AFImageDownloader defaultInstance]; 55 | #pragma clang diagnostic pop 56 | } 57 | 58 | + (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader { 59 | objc_setAssociatedObject(self, @selector(sharedImageDownloader), imageDownloader, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 60 | } 61 | 62 | #pragma mark - 63 | 64 | - (void)setImageWithURL:(NSURL *)url { 65 | [self setImageWithURL:url placeholderImage:nil]; 66 | } 67 | 68 | - (void)setImageWithURL:(NSURL *)url 69 | placeholderImage:(UIImage *)placeholderImage 70 | { 71 | NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 72 | [request addValue:@"image/*" forHTTPHeaderField:@"Accept"]; 73 | 74 | [self setImageWithURLRequest:request placeholderImage:placeholderImage success:nil failure:nil]; 75 | } 76 | 77 | - (void)setImageWithURLRequest:(NSURLRequest *)urlRequest 78 | placeholderImage:(UIImage *)placeholderImage 79 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success 80 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure 81 | { 82 | 83 | if ([urlRequest URL] == nil) { 84 | [self cancelImageDownloadTask]; 85 | self.image = placeholderImage; 86 | return; 87 | } 88 | 89 | if ([self isActiveTaskURLEqualToURLRequest:urlRequest]){ 90 | return; 91 | } 92 | 93 | [self cancelImageDownloadTask]; 94 | 95 | AFImageDownloader *downloader = [[self class] sharedImageDownloader]; 96 | id imageCache = downloader.imageCache; 97 | 98 | //Use the image from the image cache if it exists 99 | UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil]; 100 | if (cachedImage) { 101 | if (success) { 102 | success(urlRequest, nil, cachedImage); 103 | } else { 104 | self.image = cachedImage; 105 | } 106 | [self clearActiveDownloadInformation]; 107 | } else { 108 | if (placeholderImage) { 109 | self.image = placeholderImage; 110 | } 111 | 112 | __weak __typeof(self)weakSelf = self; 113 | NSUUID *downloadID = [NSUUID UUID]; 114 | AFImageDownloadReceipt *receipt; 115 | receipt = [downloader 116 | downloadImageForURLRequest:urlRequest 117 | withReceiptID:downloadID 118 | success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { 119 | __strong __typeof(weakSelf)strongSelf = weakSelf; 120 | if ([strongSelf.af_activeImageDownloadReceipt.receiptID isEqual:downloadID]) { 121 | if (success) { 122 | success(request, response, responseObject); 123 | } else if(responseObject) { 124 | strongSelf.image = responseObject; 125 | } 126 | [strongSelf clearActiveDownloadInformation]; 127 | } 128 | 129 | } 130 | failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) { 131 | __strong __typeof(weakSelf)strongSelf = weakSelf; 132 | if ([strongSelf.af_activeImageDownloadReceipt.receiptID isEqual:downloadID]) { 133 | if (failure) { 134 | failure(request, response, error); 135 | } 136 | [strongSelf clearActiveDownloadInformation]; 137 | } 138 | }]; 139 | 140 | self.af_activeImageDownloadReceipt = receipt; 141 | } 142 | } 143 | 144 | - (void)cancelImageDownloadTask { 145 | if (self.af_activeImageDownloadReceipt != nil) { 146 | [[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:self.af_activeImageDownloadReceipt]; 147 | [self clearActiveDownloadInformation]; 148 | } 149 | } 150 | 151 | - (void)clearActiveDownloadInformation { 152 | self.af_activeImageDownloadReceipt = nil; 153 | } 154 | 155 | - (BOOL)isActiveTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest { 156 | return [self.af_activeImageDownloadReceipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString]; 157 | } 158 | 159 | @end 160 | 161 | #endif 162 | -------------------------------------------------------------------------------- /PPNetworkHelper/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 | -------------------------------------------------------------------------------- /PPNetworkHelper/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 | -------------------------------------------------------------------------------- /PPNetworkHelper/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 | [task addObserver:self forKeyPath:@"state" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesSentContext]; 59 | [task addObserver:self forKeyPath:@"countOfBytesSent" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesSentContext]; 60 | 61 | [self af_setUploadProgressAnimated:animated]; 62 | } 63 | 64 | - (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task 65 | animated:(BOOL)animated 66 | { 67 | [task addObserver:self forKeyPath:@"state" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext]; 68 | [task addObserver:self forKeyPath:@"countOfBytesReceived" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext]; 69 | 70 | [self af_setDownloadProgressAnimated:animated]; 71 | } 72 | 73 | #pragma mark - NSKeyValueObserving 74 | 75 | - (void)observeValueForKeyPath:(NSString *)keyPath 76 | ofObject:(id)object 77 | change:(__unused NSDictionary *)change 78 | context:(void *)context 79 | { 80 | if (context == AFTaskCountOfBytesSentContext || context == AFTaskCountOfBytesReceivedContext) { 81 | if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesSent))]) { 82 | if ([object countOfBytesExpectedToSend] > 0) { 83 | dispatch_async(dispatch_get_main_queue(), ^{ 84 | [self setProgress:[object countOfBytesSent] / ([object countOfBytesExpectedToSend] * 1.0f) animated:self.af_uploadProgressAnimated]; 85 | }); 86 | } 87 | } 88 | 89 | if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesReceived))]) { 90 | if ([object countOfBytesExpectedToReceive] > 0) { 91 | dispatch_async(dispatch_get_main_queue(), ^{ 92 | [self setProgress:[object countOfBytesReceived] / ([object countOfBytesExpectedToReceive] * 1.0f) animated:self.af_downloadProgressAnimated]; 93 | }); 94 | } 95 | } 96 | 97 | if ([keyPath isEqualToString:NSStringFromSelector(@selector(state))]) { 98 | if ([(NSURLSessionTask *)object state] == NSURLSessionTaskStateCompleted) { 99 | @try { 100 | [object removeObserver:self forKeyPath:NSStringFromSelector(@selector(state))]; 101 | 102 | if (context == AFTaskCountOfBytesSentContext) { 103 | [object removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesSent))]; 104 | } 105 | 106 | if (context == AFTaskCountOfBytesReceivedContext) { 107 | [object removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesReceived))]; 108 | } 109 | } 110 | @catch (NSException * __unused exception) {} 111 | } 112 | } 113 | } 114 | } 115 | 116 | @end 117 | 118 | #endif 119 | -------------------------------------------------------------------------------- /PPNetworkHelper/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 | -------------------------------------------------------------------------------- /PPNetworkHelper/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 | #pragma clang diagnostic push 75 | #pragma clang diagnostic ignored "-Wreceiver-is-weak" 76 | #pragma clang diagnostic ignored "-Warc-repeated-use-of-weak" 77 | if (task.state == NSURLSessionTaskStateRunning) { 78 | [self.refreshControl beginRefreshing]; 79 | 80 | [notificationCenter addObserver:self selector:@selector(af_beginRefreshing) name:AFNetworkingTaskDidResumeNotification object:task]; 81 | [notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingTaskDidCompleteNotification object:task]; 82 | [notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingTaskDidSuspendNotification object:task]; 83 | } else { 84 | [self.refreshControl endRefreshing]; 85 | } 86 | #pragma clang diagnostic pop 87 | } 88 | } 89 | 90 | #pragma mark - 91 | 92 | - (void)af_beginRefreshing { 93 | dispatch_async(dispatch_get_main_queue(), ^{ 94 | #pragma clang diagnostic push 95 | #pragma clang diagnostic ignored "-Wreceiver-is-weak" 96 | [self.refreshControl beginRefreshing]; 97 | #pragma clang diagnostic pop 98 | }); 99 | } 100 | 101 | - (void)af_endRefreshing { 102 | dispatch_async(dispatch_get_main_queue(), ^{ 103 | #pragma clang diagnostic push 104 | #pragma clang diagnostic ignored "-Wreceiver-is-weak" 105 | [self.refreshControl endRefreshing]; 106 | #pragma clang diagnostic pop 107 | }); 108 | } 109 | 110 | #pragma mark - 111 | 112 | - (void)dealloc { 113 | NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; 114 | 115 | [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; 116 | [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; 117 | [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; 118 | } 119 | 120 | @end 121 | 122 | #endif 123 | -------------------------------------------------------------------------------- /PPNetworkHelper/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 | -------------------------------------------------------------------------------- /PPNetworkHelper/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 | #pragma clang diagnostic push 62 | #pragma clang diagnostic ignored "-Wgnu" 63 | return objc_getAssociatedObject(self, @selector(sessionManager)) ?: _af_defaultHTTPSessionManager; 64 | #pragma clang diagnostic pop 65 | } 66 | 67 | - (void)setSessionManager:(AFHTTPSessionManager *)sessionManager { 68 | objc_setAssociatedObject(self, @selector(sessionManager), sessionManager, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 69 | } 70 | 71 | - (AFHTTPResponseSerializer *)responseSerializer { 72 | static AFHTTPResponseSerializer *_af_defaultResponseSerializer = nil; 73 | static dispatch_once_t onceToken; 74 | dispatch_once(&onceToken, ^{ 75 | _af_defaultResponseSerializer = [AFHTTPResponseSerializer serializer]; 76 | }); 77 | 78 | #pragma clang diagnostic push 79 | #pragma clang diagnostic ignored "-Wgnu" 80 | return objc_getAssociatedObject(self, @selector(responseSerializer)) ?: _af_defaultResponseSerializer; 81 | #pragma clang diagnostic pop 82 | } 83 | 84 | - (void)setResponseSerializer:(AFHTTPResponseSerializer *)responseSerializer { 85 | objc_setAssociatedObject(self, @selector(responseSerializer), responseSerializer, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 86 | } 87 | 88 | #pragma mark - 89 | 90 | - (void)loadRequest:(NSURLRequest *)request 91 | progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress 92 | success:(NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success 93 | failure:(void (^)(NSError *error))failure 94 | { 95 | [self loadRequest:request MIMEType:nil textEncodingName:nil progress:progress success:^NSData *(NSHTTPURLResponse *response, NSData *data) { 96 | NSStringEncoding stringEncoding = NSUTF8StringEncoding; 97 | if (response.textEncodingName) { 98 | CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)response.textEncodingName); 99 | if (encoding != kCFStringEncodingInvalidId) { 100 | stringEncoding = CFStringConvertEncodingToNSStringEncoding(encoding); 101 | } 102 | } 103 | 104 | NSString *string = [[NSString alloc] initWithData:data encoding:stringEncoding]; 105 | if (success) { 106 | string = success(response, string); 107 | } 108 | 109 | return [string dataUsingEncoding:stringEncoding]; 110 | } failure:failure]; 111 | } 112 | 113 | - (void)loadRequest:(NSURLRequest *)request 114 | MIMEType:(NSString *)MIMEType 115 | textEncodingName:(NSString *)textEncodingName 116 | progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress 117 | success:(NSData * (^)(NSHTTPURLResponse *response, NSData *data))success 118 | failure:(void (^)(NSError *error))failure 119 | { 120 | NSParameterAssert(request); 121 | 122 | if (self.af_URLSessionTask.state == NSURLSessionTaskStateRunning || self.af_URLSessionTask.state == NSURLSessionTaskStateSuspended) { 123 | [self.af_URLSessionTask cancel]; 124 | } 125 | self.af_URLSessionTask = nil; 126 | 127 | __weak __typeof(self)weakSelf = self; 128 | NSURLSessionDataTask *dataTask; 129 | dataTask = [self.sessionManager 130 | GET:request.URL.absoluteString 131 | parameters:nil 132 | progress:nil 133 | success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) { 134 | __strong __typeof(weakSelf) strongSelf = weakSelf; 135 | if (success) { 136 | success((NSHTTPURLResponse *)task.response, responseObject); 137 | } 138 | [strongSelf loadData:responseObject MIMEType:MIMEType textEncodingName:textEncodingName baseURL:[task.currentRequest URL]]; 139 | 140 | if ([strongSelf.delegate respondsToSelector:@selector(webViewDidStartLoad:)]) { 141 | [strongSelf.delegate webViewDidFinishLoad:strongSelf]; 142 | } 143 | } 144 | failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) { 145 | if (failure) { 146 | failure(error); 147 | } 148 | }]; 149 | self.af_URLSessionTask = dataTask; 150 | if (progress != nil) { 151 | *progress = [self.sessionManager downloadProgressForTask:dataTask]; 152 | } 153 | [self.af_URLSessionTask resume]; 154 | 155 | if ([self.delegate respondsToSelector:@selector(webViewDidStartLoad:)]) { 156 | [self.delegate webViewDidStartLoad:self]; 157 | } 158 | } 159 | 160 | @end 161 | 162 | #endif -------------------------------------------------------------------------------- /PPNetworkHelper/AppDelegate.h: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.h 3 | // PPNetworkHelper 4 | // 5 | // Created by AndyPang on 16/8/12. 6 | // Copyright © 2016年 AndyPang. 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 | -------------------------------------------------------------------------------- /PPNetworkHelper/AppDelegate.m: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.m 3 | // PPNetworkHelper 4 | // 5 | // Created by AndyPang on 16/8/12. 6 | // Copyright © 2016年 AndyPang. All rights reserved. 7 | // 8 | 9 | #import "AppDelegate.h" 10 | 11 | @interface AppDelegate () 12 | 13 | @end 14 | 15 | @implementation AppDelegate 16 | 17 | 18 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 19 | // Override point for customization after application launch. 20 | 21 | return YES; 22 | } 23 | 24 | - (void)applicationWillResignActive:(UIApplication *)application { 25 | // 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. 26 | // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. 27 | } 28 | 29 | - (void)applicationDidEnterBackground:(UIApplication *)application { 30 | // 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. 31 | // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 32 | } 33 | 34 | - (void)applicationWillEnterForeground:(UIApplication *)application { 35 | // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. 36 | } 37 | 38 | - (void)applicationDidBecomeActive:(UIApplication *)application { 39 | // 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. 40 | } 41 | 42 | - (void)applicationWillTerminate:(UIApplication *)application { 43 | // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. 44 | } 45 | 46 | @end 47 | -------------------------------------------------------------------------------- /PPNetworkHelper/Assets.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "iphone", 5 | "size" : "29x29", 6 | "scale" : "2x" 7 | }, 8 | { 9 | "idiom" : "iphone", 10 | "size" : "29x29", 11 | "scale" : "3x" 12 | }, 13 | { 14 | "idiom" : "iphone", 15 | "size" : "40x40", 16 | "scale" : "2x" 17 | }, 18 | { 19 | "idiom" : "iphone", 20 | "size" : "40x40", 21 | "scale" : "3x" 22 | }, 23 | { 24 | "idiom" : "iphone", 25 | "size" : "60x60", 26 | "scale" : "2x" 27 | }, 28 | { 29 | "idiom" : "iphone", 30 | "size" : "60x60", 31 | "scale" : "3x" 32 | }, 33 | { 34 | "idiom" : "ipad", 35 | "size" : "29x29", 36 | "scale" : "1x" 37 | }, 38 | { 39 | "idiom" : "ipad", 40 | "size" : "29x29", 41 | "scale" : "2x" 42 | }, 43 | { 44 | "idiom" : "ipad", 45 | "size" : "40x40", 46 | "scale" : "1x" 47 | }, 48 | { 49 | "idiom" : "ipad", 50 | "size" : "40x40", 51 | "scale" : "2x" 52 | }, 53 | { 54 | "idiom" : "ipad", 55 | "size" : "76x76", 56 | "scale" : "1x" 57 | }, 58 | { 59 | "idiom" : "ipad", 60 | "size" : "76x76", 61 | "scale" : "2x" 62 | } 63 | ], 64 | "info" : { 65 | "version" : 1, 66 | "author" : "xcode" 67 | } 68 | } -------------------------------------------------------------------------------- /PPNetworkHelper/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 | -------------------------------------------------------------------------------- /PPNetworkHelper/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 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 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | LSRequiresIPhoneOS 24 | 25 | NSAppTransportSecurity 26 | 27 | NSAllowsArbitraryLoads 28 | 29 | 30 | UILaunchStoryboardName 31 | LaunchScreen 32 | UIMainStoryboardFile 33 | Main 34 | UIRequiredDeviceCapabilities 35 | 36 | armv7 37 | 38 | UISupportedInterfaceOrientations 39 | 40 | UIInterfaceOrientationPortrait 41 | UIInterfaceOrientationLandscapeLeft 42 | UIInterfaceOrientationLandscapeRight 43 | 44 | UISupportedInterfaceOrientations~ipad 45 | 46 | UIInterfaceOrientationPortrait 47 | UIInterfaceOrientationPortraitUpsideDown 48 | UIInterfaceOrientationLandscapeLeft 49 | UIInterfaceOrientationLandscapeRight 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /PPNetworkHelper/PPHTTPRequest.h: -------------------------------------------------------------------------------- 1 | // 2 | // PPHTTPRequest.h 3 | // PPNetworkHelper 4 | // 5 | // Created by AndyPang on 2017/4/10. 6 | // Copyright © 2017年 AndyPang. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | /* 12 | 以下Block的参数你根据自己项目中的需求来指定, 这里仅仅是一个演示的例子 13 | */ 14 | 15 | /** 16 | 请求成功的block 17 | 18 | @param info 返回信息 19 | @param response 响应体数据 20 | */ 21 | typedef void(^PPRequestSuccess)(id response); 22 | /** 23 | 请求失败的block 24 | 25 | @param extInfo 扩展信息 26 | */ 27 | typedef void(^PPRequestFailure)(NSError *error); 28 | 29 | 30 | @interface PPHTTPRequest : NSObject 31 | 32 | #pragma mark - 登陆退出 33 | /** 登录*/ 34 | + (NSURLSessionTask *)getLoginWithParameters:(id)parameters success:(PPRequestSuccess)success failure:(PPRequestFailure)failure; 35 | /** 退出*/ 36 | + (NSURLSessionTask *)getExitWithParameters:(id)parameters success:(PPRequestSuccess)success failure:(PPRequestFailure)failure; 37 | 38 | 39 | @end 40 | -------------------------------------------------------------------------------- /PPNetworkHelper/PPHTTPRequest.m: -------------------------------------------------------------------------------- 1 | // 2 | // PPHTTPRequest.m 3 | // PPNetworkHelper 4 | // 5 | // Created by AndyPang on 2017/4/10. 6 | // Copyright © 2017年 AndyPang. All rights reserved. 7 | // 8 | 9 | #import "PPHTTPRequest.h" 10 | #import "PPInterfacedConst.h" 11 | #import "PPNetworkHelper.h" 12 | 13 | @implementation PPHTTPRequest 14 | /** 登录*/ 15 | + (NSURLSessionTask *)getLoginWithParameters:(id)parameters success:(PPRequestSuccess)success failure:(PPRequestFailure)failure 16 | { 17 | // 将请求前缀与请求路径拼接成一个完整的URL 18 | NSString *url = [NSString stringWithFormat:@"%@%@",kApiPrefix,kLogin]; 19 | return [self requestWithURL:url parameters:parameters success:success failure:failure]; 20 | } 21 | /** 退出*/ 22 | + (NSURLSessionTask *)getExitWithParameters:(id)parameters success:(PPRequestSuccess)success failure:(PPRequestFailure)failure 23 | { 24 | NSString *url = [NSString stringWithFormat:@"%@%@",kApiPrefix,kExit]; 25 | return [self requestWithURL:url parameters:parameters success:success failure:failure]; 26 | } 27 | 28 | 29 | /* 30 | 配置好PPNetworkHelper各项请求参数,封装成一个公共方法,给以上方法调用, 31 | 相比在项目中单个分散的使用PPNetworkHelper/其他网络框架请求,可大大降低耦合度,方便维护 32 | 在项目的后期, 你可以在公共请求方法内任意更换其他的网络请求工具,切换成本小 33 | */ 34 | 35 | #pragma mark - 请求的公共方法 36 | 37 | + (NSURLSessionTask *)requestWithURL:(NSString *)URL parameters:(NSDictionary *)parameter success:(PPRequestSuccess)success failure:(PPRequestFailure)failure 38 | { 39 | // 在请求之前你可以统一配置你请求的相关参数 ,设置请求头, 请求参数的格式, 返回数据的格式....这样你就不需要每次请求都要设置一遍相关参数 40 | // 设置请求头 41 | [PPNetworkHelper setValue:@"9" forHTTPHeaderField:@"fromType"]; 42 | 43 | // 发起请求 44 | return [PPNetworkHelper POST:URL parameters:parameter success:^(id responseObject) { 45 | 46 | // 在这里你可以根据项目自定义其他一些重复操作,比如加载页面时候的等待效果, 提醒弹窗.... 47 | success(responseObject); 48 | 49 | } failure:^(NSError *error) { 50 | // 同上 51 | failure(error); 52 | }]; 53 | } 54 | 55 | @end 56 | -------------------------------------------------------------------------------- /PPNetworkHelper/PPInterfacedConst.h: -------------------------------------------------------------------------------- 1 | // 2 | // PPInterfacedConst.h 3 | // PPNetworkHelper 4 | // 5 | // Created by AndyPang on 2017/4/10. 6 | // Copyright © 2017年 AndyPang. All rights reserved. 7 | // 8 | 9 | #import 10 | /* 11 | 12 | 将项目中所有的接口写在这里,方便统一管理,降低耦合 13 | 14 | 这里通过宏定义来切换你当前的服务器类型, 15 | 将你要切换的服务器类型宏后面置为真(即>0即可),其余为假(置为0) 16 | 如下:现在的状态为测试服务器 17 | 这样做切换方便,不用来回每个网络请求修改请求域名,降低出错事件 18 | */ 19 | 20 | #define DevelopSever 0 21 | #define TestSever 1 22 | #define ProductSever 0 23 | 24 | /** 接口前缀-开发服务器*/ 25 | UIKIT_EXTERN NSString *const kApiPrefix; 26 | 27 | #pragma mark - 详细接口地址 28 | /** 登录*/ 29 | UIKIT_EXTERN NSString *const kLogin; 30 | /** 平台会员退出*/ 31 | UIKIT_EXTERN NSString *const kExit; 32 | 33 | -------------------------------------------------------------------------------- /PPNetworkHelper/PPInterfacedConst.m: -------------------------------------------------------------------------------- 1 | // 2 | // PPInterfacedConst.m 3 | // PPNetworkHelper 4 | // 5 | // Created by YiAi on 2017/7/6. 6 | // Copyright © 2017年 AndyPang. All rights reserved. 7 | // 8 | 9 | #import "PPInterfacedConst.h" 10 | 11 | #if DevelopSever 12 | /** 接口前缀-开发服务器*/ 13 | NSString *const kApiPrefix = @"接口服务器的请求前缀 例: http://192.168.10.10:8080"; 14 | #elif TestSever 15 | /** 接口前缀-测试服务器*/ 16 | NSString *const kApiPrefix = @"https://www.baidu.com"; 17 | #elif ProductSever 18 | /** 接口前缀-生产服务器*/ 19 | NSString *const kApiPrefix = @"https://www.baidu.com"; 20 | #endif 21 | 22 | /** 登录*/ 23 | NSString *const kLogin = @"/login"; 24 | /** 平台会员退出*/ 25 | NSString *const kExit = @"/exit"; 26 | -------------------------------------------------------------------------------- /PPNetworkHelper/PPNetworkHelper/PPNetworkCache.h: -------------------------------------------------------------------------------- 1 | // 2 | // PPNetworkCache.h 3 | // PPNetworkHelper 4 | // 5 | // Created by AndyPang on 16/8/12. 6 | // Copyright © 2016年 AndyPang. All rights reserved. 7 | // 8 | 9 | /* 10 | ********************************************************************************* 11 | * 12 | *⭐️⭐️⭐️ 新建 PP-iOS学习交流群: 323408051 欢迎加入!!! ⭐️⭐️⭐️ 13 | * 14 | * 如果您在使用 PPNetworkHelper 的过程中出现bug或有更好的建议,还请及时以下列方式联系我,我会及 15 | * 时修复bug,解决问题. 16 | * 17 | * Weibo : jkpang-庞 (http://weibo.com/jkpang ) 18 | * Email : jkpang@outlook.com 19 | * QQ 群 : 323408051 20 | * GitHub: https://github.com/jkpang 21 | * Blog : https://www.jkpang.cn 22 | * 23 | * 如果 PPGetAddressBookSwift 好用,希望您能Star支持,你的 ⭐️ 是我持续更新的动力! 24 | ********************************************************************************* 25 | */ 26 | 27 | #import 28 | // 过期提醒 29 | #define PPDeprecated(instead) NS_DEPRECATED(2_0, 2_0, 2_0, 2_0, instead) 30 | 31 | 32 | #pragma mark - 网络数据缓存类 33 | @interface PPNetworkCache : NSObject 34 | 35 | /** 36 | * 异步缓存网络数据,根据请求的 URL与parameters 37 | * 做KEY存储数据, 这样就能缓存多级页面的数据 38 | * 39 | * @param httpData 服务器返回的数据 40 | * @param URL 请求的URL地址 41 | * @param parameters 请求的参数 42 | */ 43 | + (void)setHttpCache:(id)httpData URL:(NSString *)URL parameters:(id)parameters; 44 | 45 | /** 46 | * 根据请求的 URL与parameters 同步取出缓存数据 47 | * 48 | * @param URL 请求的URL 49 | * @param parameters 请求的参数 50 | * 51 | * @return 缓存的服务器数据 52 | */ 53 | + (id)httpCacheForURL:(NSString *)URL parameters:(id)parameters; 54 | 55 | /// 获取网络缓存的总大小 bytes(字节) 56 | + (NSInteger)getAllHttpCacheSize; 57 | 58 | 59 | /// 删除所有网络缓存 60 | + (void)removeAllHttpCache; 61 | 62 | @end 63 | -------------------------------------------------------------------------------- /PPNetworkHelper/PPNetworkHelper/PPNetworkCache.m: -------------------------------------------------------------------------------- 1 | // 2 | // PPNetworkCache.m 3 | // PPNetworkHelper 4 | // 5 | // Created by AndyPang on 16/8/12. 6 | // Copyright © 2016年 AndyPang. All rights reserved. 7 | // 8 | 9 | #import "PPNetworkCache.h" 10 | #import "YYCache.h" 11 | 12 | static NSString *const kPPNetworkResponseCache = @"kPPNetworkResponseCache"; 13 | 14 | @implementation PPNetworkCache 15 | static YYCache *_dataCache; 16 | 17 | + (void)initialize { 18 | _dataCache = [YYCache cacheWithName:kPPNetworkResponseCache]; 19 | } 20 | 21 | + (void)setHttpCache:(id)httpData URL:(NSString *)URL parameters:(NSDictionary *)parameters { 22 | NSString *cacheKey = [self cacheKeyWithURL:URL parameters:parameters]; 23 | //异步缓存,不会阻塞主线程 24 | [_dataCache setObject:httpData forKey:cacheKey withBlock:nil]; 25 | } 26 | 27 | + (id)httpCacheForURL:(NSString *)URL parameters:(NSDictionary *)parameters { 28 | NSString *cacheKey = [self cacheKeyWithURL:URL parameters:parameters]; 29 | return [_dataCache objectForKey:cacheKey]; 30 | } 31 | 32 | + (NSInteger)getAllHttpCacheSize { 33 | return [_dataCache.diskCache totalCost]; 34 | } 35 | 36 | + (void)removeAllHttpCache { 37 | [_dataCache.diskCache removeAllObjects]; 38 | } 39 | 40 | + (NSString *)cacheKeyWithURL:(NSString *)URL parameters:(NSDictionary *)parameters { 41 | if(!parameters || parameters.count == 0){return URL;}; 42 | // 将参数字典转换成字符串 43 | NSData *stringData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil]; 44 | NSString *paraString = [[NSString alloc] initWithData:stringData encoding:NSUTF8StringEncoding]; 45 | return [NSString stringWithFormat:@"%@%@",URL,paraString]; 46 | } 47 | 48 | 49 | @end 50 | 51 | -------------------------------------------------------------------------------- /PPNetworkHelper/PPNetworkHelper/PPNetworkHelper.h: -------------------------------------------------------------------------------- 1 | // 2 | // PPNetworkHelper.h 3 | // PPNetworkHelper 4 | // 5 | // Created by AndyPang on 16/8/12. 6 | // Copyright © 2016年 AndyPang. All rights reserved. 7 | // 8 | 9 | /* 10 | ********************************************************************************* 11 | * 12 | *⭐️⭐️⭐️ 新建 PP-iOS学习交流群: 323408051 欢迎加入!!! ⭐️⭐️⭐️ 13 | * 14 | * 如果您在使用 PPNetworkHelper 的过程中出现bug或有更好的建议,还请及时以下列方式联系我,我会及 15 | * 时修复bug,解决问题. 16 | * 17 | * Weibo : jkpang-庞 (http://weibo.com/jkpang ) 18 | * Email : jkpang@outlook.com 19 | * QQ 群 : 323408051 20 | * GitHub: https://github.com/jkpang 21 | * Blog : https://www.jkpang.cn 22 | * 23 | * 如果 PPGetAddressBookSwift 好用,希望您能Star支持,你的 ⭐️ 是我持续更新的动力! 24 | * 25 | * version: 0.8.0 26 | ********************************************************************************* 27 | */ 28 | 29 | #import 30 | #import 31 | #import "PPNetworkCache.h" 32 | 33 | #ifndef kIsNetwork 34 | #define kIsNetwork [PPNetworkHelper isNetwork] // 一次性判断是否有网的宏 35 | #endif 36 | 37 | #ifndef kIsWWANNetwork 38 | #define kIsWWANNetwork [PPNetworkHelper isWWANNetwork] // 一次性判断是否为手机网络的宏 39 | #endif 40 | 41 | #ifndef kIsWiFiNetwork 42 | #define kIsWiFiNetwork [PPNetworkHelper isWiFiNetwork] // 一次性判断是否为WiFi网络的宏 43 | #endif 44 | 45 | typedef NS_ENUM(NSUInteger, PPNetworkStatusType) { 46 | /// 未知网络 47 | PPNetworkStatusUnknown, 48 | /// 无网络 49 | PPNetworkStatusNotReachable, 50 | /// 手机网络 51 | PPNetworkStatusReachableViaWWAN, 52 | /// WIFI网络 53 | PPNetworkStatusReachableViaWiFi 54 | }; 55 | 56 | typedef NS_ENUM(NSUInteger, PPRequestSerializer) { 57 | /// 设置请求数据为JSON格式 58 | PPRequestSerializerJSON, 59 | /// 设置请求数据为二进制格式 60 | PPRequestSerializerHTTP, 61 | }; 62 | 63 | typedef NS_ENUM(NSUInteger, PPResponseSerializer) { 64 | /// 设置响应数据为JSON格式 65 | PPResponseSerializerJSON, 66 | /// 设置响应数据为二进制格式 67 | PPResponseSerializerHTTP, 68 | }; 69 | 70 | /// 请求成功的Block 71 | typedef void(^PPHttpRequestSuccess)(id responseObject); 72 | 73 | /// 请求失败的Block 74 | typedef void(^PPHttpRequestFailed)(NSError *error); 75 | 76 | /// 缓存的Block 77 | typedef void(^PPHttpRequestCache)(id responseCache); 78 | 79 | /// 上传或者下载的进度, Progress.completedUnitCount:当前大小 - Progress.totalUnitCount:总大小 80 | typedef void (^PPHttpProgress)(NSProgress *progress); 81 | 82 | /// 网络状态的Block 83 | typedef void(^PPNetworkStatus)(PPNetworkStatusType status); 84 | 85 | @class AFHTTPSessionManager; 86 | @interface PPNetworkHelper : NSObject 87 | 88 | /// 有网YES, 无网:NO 89 | + (BOOL)isNetwork; 90 | 91 | /// 手机网络:YES, 反之:NO 92 | + (BOOL)isWWANNetwork; 93 | 94 | /// WiFi网络:YES, 反之:NO 95 | + (BOOL)isWiFiNetwork; 96 | 97 | /// 取消所有HTTP请求 98 | + (void)cancelAllRequest; 99 | 100 | /// 实时获取网络状态,通过Block回调实时获取(此方法可多次调用) 101 | + (void)networkStatusWithBlock:(PPNetworkStatus)networkStatus; 102 | 103 | /// 取消指定URL的HTTP请求 104 | + (void)cancelRequestWithURL:(NSString *)URL; 105 | 106 | /// 开启日志打印 (Debug级别) 107 | + (void)openLog; 108 | 109 | /// 关闭日志打印,默认关闭 110 | + (void)closeLog; 111 | 112 | 113 | /** 114 | * GET请求,无缓存 115 | * 116 | * @param URL 请求地址 117 | * @param parameters 请求参数 118 | * @param success 请求成功的回调 119 | * @param failure 请求失败的回调 120 | * 121 | * @return 返回的对象可取消请求,调用cancel方法 122 | */ 123 | + (__kindof NSURLSessionTask *)GET:(NSString *)URL 124 | parameters:(id)parameters 125 | success:(PPHttpRequestSuccess)success 126 | failure:(PPHttpRequestFailed)failure; 127 | 128 | /** 129 | * GET请求,自动缓存 130 | * 131 | * @param URL 请求地址 132 | * @param parameters 请求参数 133 | * @param responseCache 缓存数据的回调 134 | * @param success 请求成功的回调 135 | * @param failure 请求失败的回调 136 | * 137 | * @return 返回的对象可取消请求,调用cancel方法 138 | */ 139 | + (__kindof NSURLSessionTask *)GET:(NSString *)URL 140 | parameters:(id)parameters 141 | responseCache:(PPHttpRequestCache)responseCache 142 | success:(PPHttpRequestSuccess)success 143 | failure:(PPHttpRequestFailed)failure; 144 | 145 | /** 146 | * POST请求,无缓存 147 | * 148 | * @param URL 请求地址 149 | * @param parameters 请求参数 150 | * @param success 请求成功的回调 151 | * @param failure 请求失败的回调 152 | * 153 | * @return 返回的对象可取消请求,调用cancel方法 154 | */ 155 | + (__kindof NSURLSessionTask *)POST:(NSString *)URL 156 | parameters:(id)parameters 157 | success:(PPHttpRequestSuccess)success 158 | failure:(PPHttpRequestFailed)failure; 159 | 160 | /** 161 | * POST请求,自动缓存 162 | * 163 | * @param URL 请求地址 164 | * @param parameters 请求参数 165 | * @param responseCache 缓存数据的回调 166 | * @param success 请求成功的回调 167 | * @param failure 请求失败的回调 168 | * 169 | * @return 返回的对象可取消请求,调用cancel方法 170 | */ 171 | + (__kindof NSURLSessionTask *)POST:(NSString *)URL 172 | parameters:(id)parameters 173 | responseCache:(PPHttpRequestCache)responseCache 174 | success:(PPHttpRequestSuccess)success 175 | failure:(PPHttpRequestFailed)failure; 176 | 177 | /** 178 | * 上传文件 179 | * 180 | * @param URL 请求地址 181 | * @param parameters 请求参数 182 | * @param name 文件对应服务器上的字段 183 | * @param filePath 文件本地的沙盒路径 184 | * @param progress 上传进度信息 185 | * @param success 请求成功的回调 186 | * @param failure 请求失败的回调 187 | * 188 | * @return 返回的对象可取消请求,调用cancel方法 189 | */ 190 | + (__kindof NSURLSessionTask *)uploadFileWithURL:(NSString *)URL 191 | parameters:(id)parameters 192 | name:(NSString *)name 193 | filePath:(NSString *)filePath 194 | progress:(PPHttpProgress)progress 195 | success:(PPHttpRequestSuccess)success 196 | failure:(PPHttpRequestFailed)failure; 197 | 198 | /** 199 | * 上传单/多张图片 200 | * 201 | * @param URL 请求地址 202 | * @param parameters 请求参数 203 | * @param name 图片对应服务器上的字段 204 | * @param images 图片数组 205 | * @param fileNames 图片文件名数组, 可以为nil, 数组内的文件名默认为当前日期时间"yyyyMMddHHmmss" 206 | * @param imageScale 图片文件压缩比 范围 (0.f ~ 1.f) 207 | * @param imageType 图片文件的类型,例:png、jpg(默认类型).... 208 | * @param progress 上传进度信息 209 | * @param success 请求成功的回调 210 | * @param failure 请求失败的回调 211 | * 212 | * @return 返回的对象可取消请求,调用cancel方法 213 | */ 214 | + (__kindof NSURLSessionTask *)uploadImagesWithURL:(NSString *)URL 215 | parameters:(id)parameters 216 | name:(NSString *)name 217 | images:(NSArray *)images 218 | fileNames:(NSArray *)fileNames 219 | imageScale:(CGFloat)imageScale 220 | imageType:(NSString *)imageType 221 | progress:(PPHttpProgress)progress 222 | success:(PPHttpRequestSuccess)success 223 | failure:(PPHttpRequestFailed)failure; 224 | 225 | /** 226 | * 下载文件 227 | * 228 | * @param URL 请求地址 229 | * @param fileDir 文件存储目录(默认存储目录为Download) 230 | * @param progress 文件下载的进度信息 231 | * @param success 下载成功的回调(回调参数filePath:文件的路径) 232 | * @param failure 下载失败的回调 233 | * 234 | * @return 返回NSURLSessionDownloadTask实例,可用于暂停继续,暂停调用suspend方法,开始下载调用resume方法 235 | */ 236 | + (__kindof NSURLSessionTask *)downloadWithURL:(NSString *)URL 237 | fileDir:(NSString *)fileDir 238 | progress:(PPHttpProgress)progress 239 | success:(void(^)(NSString *filePath))success 240 | failure:(PPHttpRequestFailed)failure; 241 | 242 | 243 | /* 244 | ************************************** 说明 ********************************************** 245 | * 246 | * 在一开始设计接口的时候就想着方法接口越少越好,越简单越好,只有GET,POST,上传,下载,监测网络状态就够了. 247 | * 248 | * 无奈的是在实际开发中,每个APP与后台服务器的数据交互都有不同的请求格式,如果要修改请求格式,就要在此封装 249 | * 内修改,再加上此封装在支持CocoaPods后,如果使用者pod update最新PPNetworkHelper,那又要重新修改此 250 | * 封装内的相关参数. 251 | * 252 | * 依个人经验,在项目的开发中,一般都会将网络请求部分封装 2~3 层,第2层配置好网络请求工具的在本项目中的各项 253 | * 参数,其暴露出的方法接口只需留出请求URL与参数的入口就行,第3层就是对整个项目请求API的封装,其对外暴露出的 254 | * 的方法接口只留出请求参数的入口.这样如果以后项目要更换网络请求库或者修改请求URL,在单个文件内完成配置就好 255 | * 了,大大降低了项目的后期维护难度 256 | * 257 | * 综上所述,最终还是将设置参数的接口暴露出来,如果通过CocoaPods方式使用PPNetworkHelper,在设置项目网络 258 | * 请求参数的时候,强烈建议开发者在此基础上再封装一层,通过以下方法配置好各种参数与请求的URL,便于维护 259 | * 260 | ************************************** 说明 ********************************************** 261 | */ 262 | 263 | #pragma mark - 设置AFHTTPSessionManager相关属性 264 | #pragma mark 注意: 因为全局只有一个AFHTTPSessionManager实例,所以以下设置方式全局生效 265 | /** 266 | 在开发中,如果以下的设置方式不满足项目的需求,就调用此方法获取AFHTTPSessionManager实例进行自定义设置 267 | (注意: 调用此方法时在要导入AFNetworking.h头文件,否则可能会报找不到AFHTTPSessionManager的❌) 268 | @param sessionManager AFHTTPSessionManager的实例 269 | */ 270 | + (void)setAFHTTPSessionManagerProperty:(void(^)(AFHTTPSessionManager *sessionManager))sessionManager; 271 | 272 | /** 273 | * 设置网络请求参数的格式:默认为二进制格式 274 | * 275 | * @param requestSerializer PPRequestSerializerJSON(JSON格式),PPRequestSerializerHTTP(二进制格式), 276 | */ 277 | + (void)setRequestSerializer:(PPRequestSerializer)requestSerializer; 278 | 279 | /** 280 | * 设置服务器响应数据格式:默认为JSON格式 281 | * 282 | * @param responseSerializer PPResponseSerializerJSON(JSON格式),PPResponseSerializerHTTP(二进制格式) 283 | */ 284 | + (void)setResponseSerializer:(PPResponseSerializer)responseSerializer; 285 | 286 | /** 287 | * 设置请求超时时间:默认为30S 288 | * 289 | * @param time 时长 290 | */ 291 | + (void)setRequestTimeoutInterval:(NSTimeInterval)time; 292 | 293 | /// 设置请求头 294 | + (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field; 295 | 296 | /** 297 | * 是否打开网络状态转圈菊花:默认打开 298 | * 299 | * @param open YES(打开), NO(关闭) 300 | */ 301 | + (void)openNetworkActivityIndicator:(BOOL)open; 302 | 303 | /** 304 | 配置自建证书的Https请求, 参考链接: http://blog.csdn.net/syg90178aw/article/details/52839103 305 | 306 | @param cerPath 自建Https证书的路径 307 | @param validatesDomainName 是否需要验证域名,默认为YES. 如果证书的域名与请求的域名不一致,需设置为NO; 即服务器使用其他可信任机构颁发 308 | 的证书,也可以建立连接,这个非常危险, 建议打开.validatesDomainName=NO, 主要用于这种情况:客户端请求的是子域名, 而证书上的是另外 309 | 一个域名。因为SSL证书上的域名是独立的,假如证书上注册的域名是www.google.com, 那么mail.google.com是无法验证通过的. 310 | */ 311 | + (void)setSecurityPolicyWithCerPath:(NSString *)cerPath validatesDomainName:(BOOL)validatesDomainName; 312 | 313 | @end 314 | 315 | -------------------------------------------------------------------------------- /PPNetworkHelper/ViewController.h: -------------------------------------------------------------------------------- 1 | // 2 | // ViewController.h 3 | // PPNetworkHelper 4 | // 5 | // Created by AndyPang on 16/8/12. 6 | // Copyright © 2016年 AndyPang. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface ViewController : UIViewController 12 | 13 | 14 | @end 15 | 16 | -------------------------------------------------------------------------------- /PPNetworkHelper/ViewController.m: -------------------------------------------------------------------------------- 1 | // 2 | // ViewController.m 3 | // PPNetworkHelper 4 | // 5 | // Created by AndyPang on 16/8/12. 6 | // Copyright © 2016年 AndyPang. All rights reserved. 7 | // 8 | 9 | /* 10 | ********************************************************************************* 11 | * 12 | *⭐️⭐️⭐️ 新建 PP-iOS学习交流群: 323408051 欢迎加入!!! ⭐️⭐️⭐️ 13 | * 14 | * 如果您在使用 PPNetworkHelper 的过程中出现bug或有更好的建议,还请及时以下列方式联系我,我会及 15 | * 时修复bug,解决问题. 16 | * 17 | * Weibo : jkpang-庞 18 | * Email : jkpang@outlook.com 19 | * QQ 群 : 323408051 20 | * GitHub: https://github.com/jkpang 21 | * 22 | * PS:我的另外两个很好用的封装,欢迎使用! 23 | * 1.一行代码获取通讯录联系人,并进行A~Z精准排序(已处理姓名所有字符的排序问题): 24 | * GitHub:https://github.com/jkpang/PPGetAddressBook 25 | * 2.iOS中一款高度可定制性商品计数按钮(京东/淘宝/饿了么/美团外卖/百度外卖样式): 26 | * GitHub:https://github.com/jkpang/PPNumberButton 27 | * 28 | * 如果 PPGetAddressBookSwift 好用,希望您能Star支持,你的 ⭐️ 是我持续更新的动力! 29 | ********************************************************************************* 30 | */ 31 | 32 | #import "ViewController.h" 33 | #import "PPNetworkHelper.h" 34 | #import "PPHTTPRequest.h" 35 | #import "AFNetworking.h" 36 | 37 | 38 | #ifdef DEBUG 39 | #define PPLog(...) printf("[%s] %s [第%d行]: %s\n", __TIME__ ,__PRETTY_FUNCTION__ ,__LINE__, [[NSString stringWithFormat:__VA_ARGS__] UTF8String]) 40 | #else 41 | #define PPLog(...) 42 | #endif 43 | 44 | 45 | static NSString *const dataUrl = @"http://api.budejie.com/api/api_open.php"; 46 | static NSString *const downloadUrl = @"http://wvideo.spriteapp.cn/video/2016/0328/56f8ec01d9bfe_wpd.mp4"; 47 | 48 | @interface ViewController () 49 | 50 | @property (weak, nonatomic) IBOutlet UITextView *networkData; 51 | @property (weak, nonatomic) IBOutlet UITextView *cacheData; 52 | @property (weak, nonatomic) IBOutlet UILabel *cacheStatus; 53 | @property (weak, nonatomic) IBOutlet UISwitch *cacheSwitch; 54 | @property (weak, nonatomic) IBOutlet UIProgressView *progress; 55 | @property (weak, nonatomic) IBOutlet UIButton *downloadBtn; 56 | 57 | /** 是否开启缓存*/ 58 | @property (nonatomic, assign, getter=isCache) BOOL cache; 59 | 60 | /** 是否开始下载*/ 61 | @property (nonatomic, assign, getter=isDownload) BOOL download; 62 | @end 63 | 64 | @implementation ViewController 65 | 66 | - (void)viewDidLoad { 67 | [super viewDidLoad]; 68 | 69 | /** 70 | 设置网络请求参数的格式:默认为二进制格式 71 | PPRequestSerializerJSON(JSON格式), 72 | PPRequestSerializerHTTP(二进制格式) 73 | 74 | 设置方式 : [PPNetworkHelper setRequestSerializer:PPRequestSerializerHTTP]; 75 | */ 76 | 77 | /** 78 | 设置服务器响应数据格式:默认为JSON格式 79 | PPResponseSerializerJSON(JSON格式), 80 | PPResponseSerializerHTTP(二进制格式) 81 | 82 | 设置方式 : [PPNetworkHelper setResponseSerializer:PPResponseSerializerJSON]; 83 | */ 84 | 85 | /** 86 | 设置请求头 : [PPNetworkHelper setValue:@"value" forHTTPHeaderField:@"header"]; 87 | */ 88 | 89 | // 开启日志打印 90 | [PPNetworkHelper openLog]; 91 | 92 | // 获取网络缓存大小 93 | PPLog(@"网络缓存大小cache = %fKB",[PPNetworkCache getAllHttpCacheSize]/1024.f); 94 | 95 | // 清理缓存 [PPNetworkCache removeAllHttpCache]; 96 | 97 | // 实时监测网络状态 98 | [self monitorNetworkStatus]; 99 | 100 | /* 101 | * 一次性获取当前网络状态 102 | 这里延时0.1s再执行是因为程序刚刚启动,可能相关的网络服务还没有初始化完成(也有可能是AFN的BUG), 103 | 导致此demo检测的网络状态不正确,这仅仅只是为了演示demo的功能性, 在实际使用中可直接使用一次性网络判断,不用延时 104 | */ 105 | dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ 106 | [self getCurrentNetworkStatus]; 107 | }); 108 | 109 | [self PPHTTPRequestLayerDemo]; 110 | } 111 | 112 | /** 113 | 114 | 通过封装好的网络层进行请求配 , 我目前的项目是这样做的,在工程中的 PPHTTPRequestLayer 文件夹可以看到 115 | 当然,不同的项目可以有不同的做法,没有最好的做法,只有最合适的做法, 116 | 这仅仅是我抛砖引玉, 希望大家能各显神通. 117 | */ 118 | - (void)PPHTTPRequestLayerDemo 119 | { 120 | // 登陆 121 | [PPHTTPRequest getLoginWithParameters:@"参数" success:^(id response) { 122 | 123 | } failure:^(NSError *error) { 124 | 125 | }]; 126 | 127 | // 退出 128 | [PPHTTPRequest getExitWithParameters:@"参数" success:^(id response) { 129 | 130 | } failure:^(NSError *error) { 131 | 132 | }]; 133 | } 134 | 135 | 136 | #pragma mark - 获取数据请求示例 GET请求自动缓存与无缓存 137 | #pragma mark - 这里的请求只是一个演示, 在真实的项目中建议不要这样做, 具体做法可以参照PPHTTPRequestLayer文件夹的例子 138 | - (void)getData:(BOOL)isOn url:(NSString *)url 139 | { 140 | 141 | NSDictionary *para = @{ @"a":@"list", @"c":@"data",@"client":@"iphone",@"page":@"0",@"per":@"10", @"type":@"29"}; 142 | // 自动缓存 143 | if(isOn) 144 | { 145 | self.cacheStatus.text = @"缓存打开"; 146 | self.cacheSwitch.on = YES; 147 | [PPNetworkHelper GET:url parameters:para responseCache:^(id responseCache) { 148 | // 1.先加载缓存数据 149 | self.cacheData.text = [self jsonToString:responseCache]; 150 | } success:^(id responseObject) { 151 | // 2.再请求网络数据 152 | self.networkData.text = [self jsonToString:responseObject]; 153 | } failure:^(NSError *error) { 154 | 155 | }]; 156 | 157 | } 158 | // 无缓存 159 | else 160 | { 161 | self.cacheStatus.text = @"缓存关闭"; 162 | self.cacheSwitch.on = NO; 163 | self.cacheData.text = @""; 164 | 165 | [PPNetworkHelper GET:url parameters:para success:^(id responseObject) { 166 | self.networkData.text = [self jsonToString:responseObject]; 167 | } failure:^(NSError *error) { 168 | 169 | }]; 170 | 171 | } 172 | 173 | } 174 | #pragma mark - 实时监测网络状态 175 | - (void)monitorNetworkStatus 176 | { 177 | // 网络状态改变一次, networkStatusWithBlock就会响应一次 178 | [PPNetworkHelper networkStatusWithBlock:^(PPNetworkStatusType networkStatus) { 179 | 180 | switch (networkStatus) { 181 | // 未知网络 182 | case PPNetworkStatusUnknown: 183 | // 无网络 184 | case PPNetworkStatusNotReachable: 185 | self.networkData.text = @"没有网络"; 186 | [self getData:YES url:dataUrl]; 187 | PPLog(@"无网络,加载缓存数据"); 188 | break; 189 | // 手机网络 190 | case PPNetworkStatusReachableViaWWAN: 191 | // 无线网络 192 | case PPNetworkStatusReachableViaWiFi: 193 | [self getData:[[NSUserDefaults standardUserDefaults] boolForKey:@"isOn"] url:dataUrl]; 194 | PPLog(@"有网络,请求网络数据"); 195 | break; 196 | } 197 | 198 | }]; 199 | 200 | } 201 | 202 | #pragma mark - 一次性获取当前最新网络状态 203 | - (void)getCurrentNetworkStatus 204 | { 205 | if (kIsNetwork) { 206 | PPLog(@"有网络"); 207 | if (kIsWWANNetwork) { 208 | PPLog(@"手机网络"); 209 | }else if (kIsWiFiNetwork){ 210 | PPLog(@"WiFi网络"); 211 | } 212 | } else { 213 | PPLog(@"无网络"); 214 | } 215 | // 或 216 | // if ([PPNetworkHelper isNetwork]) { 217 | // PPLog(@"有网络"); 218 | // if ([PPNetworkHelper isWWANNetwork]) { 219 | // PPLog(@"手机网络"); 220 | // }else if ([PPNetworkHelper isWiFiNetwork]){ 221 | // PPLog(@"WiFi网络"); 222 | // } 223 | // } else { 224 | // PPLog(@"无网络"); 225 | // } 226 | } 227 | 228 | #pragma mark - 下载 229 | 230 | - (IBAction)download:(UIButton *)sender { 231 | 232 | static NSURLSessionTask *task = nil; 233 | //开始下载 234 | if(!self.isDownload) 235 | { 236 | self.download = YES; 237 | [self.downloadBtn setTitle:@"取消下载" forState:UIControlStateNormal]; 238 | 239 | task = [PPNetworkHelper downloadWithURL:downloadUrl fileDir:@"Download" progress:^(NSProgress *progress) { 240 | 241 | CGFloat stauts = 100.f * progress.completedUnitCount/progress.totalUnitCount; 242 | self.progress.progress = stauts/100.f; 243 | 244 | PPLog(@"下载进度 :%.2f%%,,%@",stauts,[NSThread currentThread]); 245 | } success:^(NSString *filePath) { 246 | 247 | UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"下载完成!" 248 | message:[NSString stringWithFormat:@"文件路径:%@",filePath] 249 | delegate:nil 250 | cancelButtonTitle:@"确定" 251 | otherButtonTitles:nil]; 252 | [alertView show]; 253 | [self.downloadBtn setTitle:@"重新下载" forState:UIControlStateNormal]; 254 | PPLog(@"filePath = %@",filePath); 255 | 256 | } failure:^(NSError *error) { 257 | UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"下载失败" 258 | message:[NSString stringWithFormat:@"%@",error] 259 | delegate:nil 260 | cancelButtonTitle:@"确定" 261 | otherButtonTitles:nil]; 262 | [alertView show]; 263 | PPLog(@"error = %@",error); 264 | }]; 265 | 266 | } 267 | //暂停下载 268 | else 269 | { 270 | self.download = NO; 271 | [task suspend]; 272 | self.progress.progress = 0; 273 | [self.downloadBtn setTitle:@"开始下载" forState:UIControlStateNormal]; 274 | } 275 | 276 | 277 | 278 | } 279 | 280 | #pragma mark - 缓存开关 281 | - (IBAction)isCache:(UISwitch *)sender { 282 | [[NSUserDefaults standardUserDefaults] setBool:sender.isOn forKey:@"isOn"]; 283 | 284 | [self getData:sender.isOn url:dataUrl]; 285 | } 286 | 287 | /** 288 | * json转字符串 289 | */ 290 | - (NSString *)jsonToString:(NSDictionary *)dic 291 | { 292 | if(!dic){ 293 | return nil; 294 | } 295 | NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil]; 296 | return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; 297 | } 298 | 299 | - (void)didReceiveMemoryWarning { 300 | [super didReceiveMemoryWarning]; 301 | // Dispose of any resources that can be recreated. 302 | } 303 | @end 304 | -------------------------------------------------------------------------------- /PPNetworkHelper/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 | -------------------------------------------------------------------------------- /PPNetworkHelper/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 [[YYCache alloc] initWithName:name]; 47 | } 48 | 49 | + (instancetype)cacheWithPath:(NSString *)path { 50 | return [[YYCache 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:block]; 89 | } 90 | } 91 | 92 | - (void)setObject:(id)object forKey:(NSString *)key { 93 | [_memoryCache setObject:object forKey:key]; 94 | [_diskCache setObject:object forKey:key]; 95 | } 96 | 97 | - (void)setObject:(id)object forKey:(NSString *)key withBlock:(void (^)(void))block { 98 | [_memoryCache setObject:object forKey:key]; 99 | [_diskCache setObject:object forKey:key withBlock:block]; 100 | } 101 | 102 | - (void)removeObjectForKey:(NSString *)key { 103 | [_memoryCache removeObjectForKey:key]; 104 | [_diskCache removeObjectForKey:key]; 105 | } 106 | 107 | - (void)removeObjectForKey:(NSString *)key withBlock:(void (^)(NSString *key))block { 108 | [_memoryCache removeObjectForKey:key]; 109 | [_diskCache removeObjectForKey:key withBlock:block]; 110 | } 111 | 112 | - (void)removeAllObjects { 113 | [_memoryCache removeAllObjects]; 114 | [_diskCache removeAllObjects]; 115 | } 116 | 117 | - (void)removeAllObjectsWithBlock:(void(^)(void))block { 118 | [_memoryCache removeAllObjects]; 119 | [_diskCache removeAllObjectsWithBlock:block]; 120 | } 121 | 122 | - (void)removeAllObjectsWithProgressBlock:(void(^)(int removedCount, int totalCount))progress 123 | endBlock:(void(^)(BOOL error))end { 124 | [_memoryCache removeAllObjects]; 125 | [_diskCache removeAllObjectsWithProgressBlock:progress endBlock:end]; 126 | 127 | } 128 | 129 | - (NSString *)description { 130 | if (_name) return [NSString stringWithFormat:@"<%@: %p> (%@)", self.class, self, _name]; 131 | else return [NSString stringWithFormat:@"<%@: %p>", self.class, self]; 132 | } 133 | 134 | @end 135 | -------------------------------------------------------------------------------- /PPNetworkHelper/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 | -------------------------------------------------------------------------------- /PPNetworkHelper/main.m: -------------------------------------------------------------------------------- 1 | // 2 | // main.m 3 | // PPNetworkHelper 4 | // 5 | // Created by AndyPang on 16/8/12. 6 | // Copyright © 2016年 AndyPang. 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 | -------------------------------------------------------------------------------- /PPNetworkHelperTests/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | BNDL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | 24 | 25 | -------------------------------------------------------------------------------- /PPNetworkHelperTests/PPNetworkHelperTests.m: -------------------------------------------------------------------------------- 1 | // 2 | // PPNetworkHelperTests.m 3 | // PPNetworkHelperTests 4 | // 5 | // Created by AndyPang on 16/8/12. 6 | // Copyright © 2016年 AndyPang. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface PPNetworkHelperTests : XCTestCase 12 | 13 | @end 14 | 15 | @implementation PPNetworkHelperTests 16 | 17 | - (void)setUp { 18 | [super setUp]; 19 | // Put setup code here. This method is called before the invocation of each test method in the class. 20 | } 21 | 22 | - (void)tearDown { 23 | // Put teardown code here. This method is called after the invocation of each test method in the class. 24 | [super tearDown]; 25 | } 26 | 27 | - (void)testExample { 28 | // This is an example of a functional test case. 29 | // Use XCTAssert and related functions to verify your tests produce the correct results. 30 | } 31 | 32 | - (void)testPerformanceExample { 33 | // This is an example of a performance test case. 34 | [self measureBlock:^{ 35 | // Put the code you want to measure the time of here. 36 | }]; 37 | } 38 | 39 | @end 40 | -------------------------------------------------------------------------------- /Picture/PPNetworkHelper.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jkpang/PPNetworkHelper/54505979e1522fed07cc0a4ecba057010b0d8c6b/Picture/PPNetworkHelper.png -------------------------------------------------------------------------------- /Picture/network.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jkpang/PPNetworkHelper/54505979e1522fed07cc0a4ecba057010b0d8c6b/Picture/network.gif -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![image](https://github.com/jkpang/PPNetworkHelper/blob/master/Picture/PPNetworkHelper.png) 2 | 3 | ![](https://img.shields.io/badge/platform-iOS-red.svg) ![](https://img.shields.io/badge/language-Objective--C-orange.svg) ![](https://img.shields.io/cocoapods/v/PPNetworkHelper.svg?style=flat) ![](https://img.shields.io/cocoapods/dt/PPNetworkHelper.svg 4 | ) ![](https://img.shields.io/badge/license-MIT%20License-brightgreen.svg) [![](https://img.shields.io/badge/weibo-jkpang--%E5%BA%9E-red.svg)](http://weibo.com/5743737098/profile?rightmod=1&wvr=6&mod=personinfo&is_all=1) 5 | 6 | 对AFNetworking 3.x 与YYCache的二次封装,封装常见的GET、POST、文件上传/下载、网络状态监测的功能、方法接口简洁明了,并结合YYCache实现对网络数据的缓存,简单易用,不用再写FMDB那烦人的SQL语句,一句代码搞定网络数据的请求与缓存. 7 | 无需设置,无需插件,控制台可直接打印json中文字符,调试更方便 8 | 9 | ### 新建 PP-iOS学习交流群 : 323408051 有关于PP系列封装的问题和iOS技术可以在此群讨论 10 | 11 | [简书地址](http://www.jianshu.com/p/c695d20d95cb) ; 12 | 13 | ![image](https://github.com/jkpang/PPNetworkHelper/blob/master/Picture/network.gif) 14 | 15 | ## Requirements 要求 16 | * iOS 7+ 17 | * Xcode 8+ 18 | 19 | ## Installation 安装 20 | ### 1.手动安装: 21 | `下载DEMO后,将子文件夹PPNetworkHelper拖入到项目中, 导入头文件PPNetworkHelper.h开始使用, 注意: 项目中需要有AFN3.x , YYCache第三方库! 在工程中链接sqlite3依赖库` 22 | ### 2.CocoaPods安装: 23 | first 24 | `pod 'PPNetworkHelper',:git => 'https://github.com/jkpang/PPNetworkHelper.git'` 25 | then 26 | `pod install或pod install --no-repo-update` 27 | 28 | 如果发现pod search PPNetworkHelper 不是最新版本,在终端执行pod setup命令更新本地spec镜像缓存(时间可能有点长),重新搜索就OK了 29 | ## Usage 使用方法 30 | ### 1. 无自动缓存(GET与POST请求用法相同) 31 | #### 1.1 无缓存 32 | ```objc 33 | [PPNetworkHelper GET:url parameters:nil success:^(id responseObject) { 34 | //请求成功 35 | } failure:^(NSError *error) { 36 | //请求失败 37 | }]; 38 | ``` 39 | #### 1.2 无缓存,手动缓存 40 | 41 | ```objc 42 | [PPNetworkHelper GET:url parameters:nil success:^(id responseObject) { 43 | //请求成功 44 | //手动缓存 45 | [PPNetworkCache setHttpCache:responseObject URL:url parameters:parameters]; 46 | } failure:^(NSError *error) { 47 | //请求失败 48 | }]; 49 | ``` 50 | ### 2. 自动缓存(GET与POST请求用法相同) 51 | 52 | ```objc 53 | [PPNetworkHelper GET:url parameters:nil responseCache:^(id responseCache) { 54 | //加载缓存数据 55 | } success:^(id responseObject) { 56 | //请求成功 57 | } failure:^(NSError *error) { 58 | //请求失败 59 | }]; 60 | ``` 61 | ### 3.单/多图片上传 62 | 63 | ```objc 64 | [PPNetworkHelper uploadImagesWithURL:url 65 | parameters:@{@"参数":@"参数"} 66 | images:@[@"UIImage数组"] 67 | name:@"文件对应服务器上的字段" 68 | fileNames:@"文件名称数组" 69 | imageType:@"图片的类型,png,jpeg" 70 | imageScale:@"图片文件压缩比 范围 (0.f ~ 1.f)" 71 | progress:^(NSProgress *progress) { 72 | //上传进度 73 | NSLog(@"上传进度:%.2f%%",100.0 * progress.completedUnitCount/progress.totalUnitCount); 74 | } success:^(id responseObject) { 75 | //上传成功 76 | } failure:^(NSError *error) { 77 | //上传失败 78 | }]; 79 | 80 | ``` 81 | ### 4.文件上传 82 | ```objc 83 | [PPNetworkHelper uploadFileWithURL:url 84 | parameters:@{@"参数":@"参数"} 85 | name:@"文件对应服务器上的字段" 86 | filePath:@"文件本地的沙盒路径" 87 | progress:^(NSProgress *progress) { 88 | //上传进度 89 | NSLog(@"上传进度:%.2f%%",100.0 * progress.completedUnitCount/progress.totalUnitCount); 90 | } success:^(id responseObject) { 91 | //上传成功 92 | } failure:^(NSError *error) { 93 | //上传失败 94 | }]; 95 | 96 | ``` 97 | ### 5.文件下载 98 | 99 | ```objc 100 | NSURLSessionTask *task = [PPNetworkHelper downloadWithURL:url fileDir:@"下载至沙盒中的制定文件夹(默认为Download)" progress:^(NSProgress *progress) { 101 | //下载进度,如果要配合UI进度条显示,必须在主线程更新UI 102 | NSLog(@"下载进度:%.2f%%",100.0 * progress.completedUnitCount/progress.totalUnitCount); 103 | } success:^(NSString *filePath) { 104 | //下载成功 105 | } failure:^(NSError *error) { 106 | //下载失败 107 | }]; 108 | 109 | //暂停下载,暂不支持断点下载 110 | [task suspend]; 111 | //开始下载 112 | [task resume]; 113 | ``` 114 | ### 6.网络状态监测 115 | 116 | ```objc 117 | // 1.实时获取网络状态,通过Block回调实时获取(此方法可多次调用) 118 | [PPNetworkHelper networkStatusWithBlock:^(PPNetworkStatus status) { 119 | switch (status) { 120 | case PPNetworkStatusUnknown: //未知网络 121 | break; 122 | case PPNetworkStatusNotReachable: //无网络 123 | break; 124 | case PPNetworkStatusReachableViaWWAN://手机网络 125 | break; 126 | case PPNetworkStatusReachableViaWiFi://WIFI 127 | break; 128 | } 129 | }]; 130 | 131 | // 2.一次性获取当前网络状态 132 | if (kIsNetwork) { 133 | NSLog(@"有网络"); 134 | if (kIsWWANNetwork) { 135 | NSLog(@"手机网络"); 136 | }else if (kIsWiFiNetwork){ 137 | NSLog(@"WiFi网络"); 138 | } 139 | } else { 140 | NSLog(@"无网络"); 141 | } 142 | ``` 143 | ### 7. 网络缓存 144 | #### 7.1 自动缓存的逻辑 145 | 146 | **1.从本地获取缓存(不管有无数据) --> 2.请求服务器数据 --> 3.更新本地数据** 147 | 148 | #### 7.2 获取缓存总大小 149 | ```objc 150 | NSInteger totalBytes = [PPNetworkCache getAllHttpCacheSize]; 151 | NSLog(@"网络缓存大小cache = %.2fMB",totalBytes/1024/1024.f); 152 | ``` 153 | #### 7.3 删除所有缓存 154 | 155 | ```objc 156 | [PPNetworkCache removeAllHttpCache]; 157 | ``` 158 | ### 8.网络参数设置(附说明) 159 | 160 | ```objc 161 | /* 162 | ************************************** 说明 ********************************************** 163 | * 164 | * 在一开始设计接口的时候就想着方法接口越少越好,越简单越好,只有GET,POST,上传,下载,监测网络状态就够了. 165 | * 166 | * 无奈的是在实际开发中,每个APP与后台服务器的数据交互都有不同的请求格式,如果要修改请求格式,就要在此封装 167 | * 内修改,再加上此封装在支持CocoaPods后,如果使用者pod update最新PPNetworkHelper,那又要重新修改此 168 | * 封装内的相关参数. 169 | * 170 | * 依个人经验,在项目的开发中,一般都会将网络请求部分封装 2~3 层,第2层配置好网络请求工具的在本项目中的各项 171 | * 参数,其暴露出的方法接口只需留出请求URL与参数的入口就行,第3层就是对整个项目请求API的封装,其对外暴露出的 172 | * 的方法接口只留出请求参数的入口.这样如果以后项目要更换网络请求库或者修改请求URL,在单个文件内完成配置就好 173 | * 了,大大降低了项目的后期维护难度 174 | * 175 | * 综上所述,最终还是将设置参数的接口暴露出来,如果通过CocoaPods方式使用PPNetworkHelper,在设置项目网络 176 | * 请求参数的时候,强烈建议开发者在此基础上再封装一层,通过以下方法配置好各种参数与请求的URL,便于维护 177 | * 178 | ************************************** 说明 ********************************************** 179 | */ 180 | 181 | #pragma mark - 重置AFHTTPSessionManager相关属性 182 | /** 183 | * 设置网络请求参数的格式:默认为二进制格式 184 | * 185 | * @param requestSerializer PPRequestSerializerJSON(JSON格式),PPRequestSerializerHTTP(二进制格式), 186 | */ 187 | + (void)setRequestSerializer:(PPRequestSerializer)requestSerializer; 188 | 189 | /** 190 | * 设置服务器响应数据格式:默认为JSON格式 191 | * 192 | * @param responseSerializer PPResponseSerializerJSON(JSON格式),PPResponseSerializerHTTP(二进制格式) 193 | */ 194 | + (void)setResponseSerializer:(PPResponseSerializer)responseSerializer; 195 | 196 | /** 197 | * 设置请求超时时间:默认为30S 198 | * 199 | * @param time 时长 200 | */ 201 | + (void)setRequestTimeoutInterval:(NSTimeInterval)time; 202 | 203 | /** 204 | * 设置请求头 205 | */ 206 | + (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field; 207 | 208 | /** 209 | * 是否打开网络状态转圈菊花:默认打开 210 | * 211 | * @param open YES(打开), NO(关闭) 212 | */ 213 | + (void)openNetworkActivityIndicator:(BOOL)open; 214 | 215 | /** 216 | 配置自建证书的Https请求, 参考链接: http://blog.csdn.net/syg90178aw/article/details/52839103 217 | 218 | @param cerPath 自建Https证书的路径 219 | @param validatesDomainName 是否需要验证域名,默认为YES. 如果证书的域名与请求的域名不一致,需设置为NO; 即服务器使用其他可信任机构颁发 220 | 的证书,也可以建立连接,这个非常危险, 建议打开.validatesDomainName=NO, 主要用于这种情况:客户端请求的是子域名, 而证书上的是另外 221 | 一个域名。因为SSL证书上的域名是独立的,假如证书上注册的域名是www.google.com, 那么mail.google.com是无法验证通过的. 222 | */ 223 | + (void)setSecurityPolicyWithCerPath:(NSString *)cerPath validatesDomainName:(BOOL)validatesDomainName; 224 | ``` 225 | 226 | PPNetworkHelper全部以类方法调用,使用简单,麻麻再也不用担心我一句一句地写SQLite啦~~~如果你有更好的建议,希望不吝赐教! 227 | ### 你的star是我持续更新的动力! 228 | === 229 | ## CocoaPods更新日志 230 | 231 | ``` 232 | • 2017.04.10(tag:0.8.0): 233 | 1.新增 + (void)setAFHTTPSessionManagerProperty方法,可获得AFHTTPSessionManager实例进行相关设置; 234 | 2.关闭日志状态下彻底关闭日志的打印; 235 | 3.Demo中增加对项目中网络层的构建,抛砖引玉,在工程的PPHTTPRequestLayer文件夹可以看到; 236 | 237 | • 2017.02.15(tag:0.7.0): 238 | 1.新增 日志打印打开/关闭接口; 239 | 2.修复 单/多图上传BUG; 240 | 3.优化代码规范; 241 | 242 | • 2017.02.06(tag:0.6.0): 243 | 1.重构 "单/多图片上传"部分 244 | 2.新增 "上传文件接口 245 | 246 | • 2017.01.02(tag:0.5.0): 247 | 1.添加配置自建证书的Https请求的接口; 248 | 2.修复一次性网络判断需要先调网络监测方法才能生效的BUG, 现在可直接调用一次性网络判断即可生效! 249 | 3.修改在POST请求时,请求参数的默认格式二进制(之前是JSON格式),**注意,如果有同学在升级此版本后导致获取不到服务器数据,请将设置请求参数格式的代码注释掉即可! 250 | 4.将NetworkStatu-->PPNetworkStatus, 避免与其他第三方库产生冲突! 251 | 5.修改缓存的读取为异步读取,不会阻塞主线程; 252 | 6.其他一些代码优化与修改. 253 | 254 | • 2016.11.22(tag:0.4.0): 255 | 1.一次性判断当前网络状态值更加准确; 256 | 2.添加手机网络,WiFi的当前网络状态. 257 | 258 | • 2016.11.18(tag:0.3.1): 259 | 1.新增取消所有http请求; 260 | 2.新增取消指定URL请求 的方法. 261 | 262 | • 2016.09.26(tag:0.3.0): 控制台直接打印json中文字符,无需插件 263 | • 2016.09.18(tag:0.2.5): 264 | 1.支持单个页面的多级数据缓存; 265 | 2.简化网络状态监测的方法调用 266 | 267 | • 2016.09.12(tag:0.2.1): 小细节优化 268 | • 2016.09.10(tag:0.2.0): 增加网络请求设置接口(详情见:7.网络参数设置) 269 | • 2016.09.06(tag:0.1.2): 修复在无网络进行下载时,会触发下载成功回调的Bug. 270 | • 2016.09.05(tag:0.1.1): 多个请求的情况下采取一个共享的AFHTTPSessionManager; 271 | • 2016.08.26(tag:0.1.0): 初始化到CocoaPods; 272 | ``` 273 | 274 | ## 我的App 275 | - [PPHub](https://github.com/jkpang/PPHub-Feedback):一个简洁漂亮的 GitHub iOS客户端 276 | [![App_Store](https://github.com/jkpang/PPHub-Feedback/blob/master/Resource/Download_on_the_App_Store_135x40.svg)](https://itunes.apple.com/cn/app/PPHub%20For%20GitHub/id1314212521?mt=8) 277 | 278 | ## 联系方式: 279 | * Weibo : [@jkpang-庞](http://weibo.com/5743737098/profile?rightmod=1&wvr=6&mod=personinfo&is_all=1) 280 | * Email : jkpang@outlook.com 281 | * QQ群 : 323408051 282 | * Blog : https://www.jkpang.cn 283 | 284 | ![PP-iOS学习交流群群二维码](https://github.com/jkpang/PPCounter/blob/master/PP-iOS%E5%AD%A6%E4%B9%A0%E4%BA%A4%E6%B5%81%E7%BE%A4%E7%BE%A4%E4%BA%8C%E7%BB%B4%E7%A0%81.png) 285 | 286 | ## 许可证 287 | PPNetworkHelper 使用 MIT 许可证,详情见 LICENSE 文件。 288 | 289 | --------------------------------------------------------------------------------