├── HeaderView.png ├── HomeVM.png ├── MVVMDemo.xcodeproj ├── project.pbxproj ├── project.xcworkspace │ └── contents.xcworkspacedata └── xcuserdata │ └── SLPower.xcuserdatad │ ├── xcdebugger │ └── Breakpoints_v2.xcbkptlist │ └── xcschemes │ ├── MVVMDemo.xcscheme │ └── xcschememanagement.plist ├── MVVMDemo ├── Assets.xcassets │ └── AppIcon.appiconset │ │ └── Contents.json ├── Base.lproj │ ├── LaunchScreen.storyboard │ └── Main.storyboard ├── Base │ ├── AppDelegate.h │ ├── AppDelegate.m │ ├── RTNetworking.h │ ├── RTNetworking.m │ ├── ViewModelClass.h │ └── ViewModelClass.m ├── Info.plist ├── Lib │ ├── 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 │ ├── 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 │ └── YYModel │ │ ├── NSObject+YYModel.h │ │ ├── NSObject+YYModel.m │ │ ├── YYClassInfo.h │ │ ├── YYClassInfo.m │ │ └── YYModel.h ├── Project │ ├── Controller │ │ ├── DetailViewController.h │ │ ├── DetailViewController.m │ │ ├── ViewController.h │ │ └── ViewController.m │ └── ViewModel │ │ ├── DetailModel │ │ ├── DetailModel.h │ │ └── DetailModel.m │ │ ├── DetailViewModel │ │ ├── TopView.h │ │ └── TopView.m │ │ └── HomeViewModel │ │ ├── HeaderView.h │ │ ├── HeaderView.m │ │ ├── HomeVM.h │ │ └── HomeVM.m └── main.m ├── MVVMDemoTests ├── Info.plist └── MVVMDemoTests.m ├── MVVMDemoUITests ├── Info.plist └── MVVMDemoUITests.m ├── README.md ├── ViewModelClass.png ├── 运行.PNG └── 项目目录.png /HeaderView.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CodeRabbitYu/MVVMDemo/8320c4e671a3860ad330f5c08607b826bcd26d33/HeaderView.png -------------------------------------------------------------------------------- /HomeVM.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CodeRabbitYu/MVVMDemo/8320c4e671a3860ad330f5c08607b826bcd26d33/HomeVM.png -------------------------------------------------------------------------------- /MVVMDemo.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /MVVMDemo.xcodeproj/xcuserdata/SLPower.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | -------------------------------------------------------------------------------- /MVVMDemo.xcodeproj/xcuserdata/SLPower.xcuserdatad/xcschemes/MVVMDemo.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 33 | 39 | 40 | 41 | 43 | 49 | 50 | 51 | 52 | 53 | 59 | 60 | 61 | 62 | 63 | 64 | 74 | 76 | 82 | 83 | 84 | 85 | 86 | 87 | 93 | 95 | 101 | 102 | 103 | 104 | 106 | 107 | 110 | 111 | 112 | -------------------------------------------------------------------------------- /MVVMDemo.xcodeproj/xcuserdata/SLPower.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | MVVMDemo.xcscheme 8 | 9 | orderHint 10 | 0 11 | 12 | 13 | SuppressBuildableAutocreation 14 | 15 | 65B5C5B51DDAAE560028459A 16 | 17 | primary 18 | 19 | 20 | 65B5C5CE1DDAAE570028459A 21 | 22 | primary 23 | 24 | 25 | 65B5C5D91DDAAE570028459A 26 | 27 | primary 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /MVVMDemo/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 | } -------------------------------------------------------------------------------- /MVVMDemo/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 | -------------------------------------------------------------------------------- /MVVMDemo/Base.lproj/Main.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /MVVMDemo/Base/AppDelegate.h: -------------------------------------------------------------------------------- 1 | 2 | #import 3 | 4 | @interface AppDelegate : UIResponder 5 | 6 | @property (strong, nonatomic) UIWindow *window; 7 | 8 | 9 | @end 10 | 11 | -------------------------------------------------------------------------------- /MVVMDemo/Base/AppDelegate.m: -------------------------------------------------------------------------------- 1 | 2 | 3 | #import "AppDelegate.h" 4 | #import "ViewController.h" 5 | #import "RTNetworking.h" 6 | @interface AppDelegate () 7 | 8 | @end 9 | 10 | @implementation AppDelegate 11 | 12 | 13 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 14 | // Override point for customization after application launch. 15 | [self loadNetWork]; 16 | 17 | self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds]; 18 | self.window.backgroundColor = [UIColor whiteColor]; 19 | 20 | ViewController *vc = [[ViewController alloc]init]; 21 | UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:vc]; 22 | self.window.rootViewController = nav; 23 | 24 | 25 | [self.window makeKeyAndVisible]; 26 | 27 | return YES; 28 | } 29 | 30 | - (void)loadNetWork{ 31 | [RTNetworking updateBaseUrl:@"https://api.shunliandongli.com"]; 32 | [RTNetworking enableInterfaceDebug:NO]; 33 | 34 | NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys: 35 | @"ShunLian iPhone 9.3.2/1.0.0" , @"User-Agent", 36 | @"C51FEB80-6323-4676-BA4B-A3135B4810E3" , @"X-Device-ID", 37 | @"gzip, deflate" , @"Accept-Encoding", 38 | @"192.168.31.121" , @"X-Ip", 39 | @"application/json" , @"Content-Type", 40 | nil]; 41 | 42 | [RTNetworking configCommonHttpHeaders:dic]; 43 | 44 | [RTNetworking configRequestType:kRTRequestTypePlainText 45 | responseType:RTResponseTypeData 46 | shouldAutoEncodeUrl:YES 47 | callbackOnCancelRequest:NO]; 48 | } 49 | 50 | 51 | - (void)applicationWillResignActive:(UIApplication *)application { 52 | // 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. 53 | // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. 54 | } 55 | 56 | 57 | - (void)applicationDidEnterBackground:(UIApplication *)application { 58 | // 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. 59 | // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 60 | } 61 | 62 | 63 | - (void)applicationWillEnterForeground:(UIApplication *)application { 64 | // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. 65 | } 66 | 67 | 68 | - (void)applicationDidBecomeActive:(UIApplication *)application { 69 | // 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. 70 | } 71 | 72 | 73 | - (void)applicationWillTerminate:(UIApplication *)application { 74 | // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. 75 | } 76 | 77 | 78 | @end 79 | -------------------------------------------------------------------------------- /MVVMDemo/Base/RTNetworking.h: -------------------------------------------------------------------------------- 1 | // 2 | // RTNetworking.h 3 | // RTHttpRequest 4 | // 5 | // Created by on 16/7/4. 6 | // Copyright © 2016年 . All rights reserved. 7 | // 8 | 9 | #import 10 | #import 11 | 12 | // 项目打包上线都不会打印日志,因此可放心。 13 | #ifdef DEBUG 14 | #define RTAppLog(s, ... ) NSLog( @"[%@ in line %d] ===============>%@", [[NSString stringWithUTF8String:__FILE__] lastPathComponent], __LINE__, [NSString stringWithFormat:(s), ##__VA_ARGS__] ) 15 | #else 16 | #define RTAppLog(s, ... ) 17 | #endif 18 | 19 | /*! 20 | * 下载进度 21 | * 22 | * @param bytesRead 已下载的大小 23 | * @param totalBytesRead 文件总大小 24 | * @param totalBytesExpectedToRead 还有多少需要下载 25 | */ 26 | typedef void (^RTDownloadProgress)(int64_t bytesRead, 27 | int64_t totalBytesRead); 28 | 29 | /*! 30 | * 上传进度 31 | * 32 | * @param bytesWritten 已上传的大小 33 | * @param totalBytesWritten 总上传大小 34 | */ 35 | typedef void (^RTUploadProgress)(int64_t bytesWritten, 36 | int64_t totalBytesWritten); 37 | 38 | typedef RTDownloadProgress RTGetProgress; 39 | typedef RTDownloadProgress RTPostProgress; 40 | 41 | typedef NS_ENUM(NSUInteger, RTResponseType) { 42 | kRTResponseTypeJSON = 1, // 默认 43 | kRTResponseTypeXML = 2, // XML 44 | // 特殊情况下,一转换服务器就无法识别的,默认会尝试转换成JSON,若失败则需要自己去转换 45 | RTResponseTypeData = 3 46 | }; 47 | 48 | typedef NS_ENUM(NSUInteger, RTRequestType) { 49 | kRTRequestTypeJSON = 1, // 默认 50 | kRTRequestTypePlainText = 2 // 普通text/html 51 | }; 52 | 53 | typedef NS_ENUM(NSInteger, RTNetworkStatus) { 54 | kRTNetworkStatusUnknown = -1,//未知网络 55 | kRTNetworkStatusNotReachable = 0,//网络无连接 56 | kRTNetworkStatusReachableViaWWAN = 1,//2,3,4G网络 57 | kRTNetworkStatusReachableViaWiFi = 2,//WIFI网络 58 | }; 59 | 60 | @class NSURLSessionTask; 61 | 62 | // 请勿直接使用NSURLSessionDataTask,以减少对第三方的依赖 63 | // 所有接口返回的类型都是基类NSURLSessionTask,若要接收返回值 64 | // 且处理,请转换成对应的子类类型 65 | typedef NSURLSessionTask RTURLSessionTask; 66 | typedef void(^RTResponseSuccess)(id response); 67 | typedef void(^RTResponseFail)(NSError *error); 68 | 69 | /*! 70 | * 基于AFNetworking的网络层封装类. 71 | * 72 | * @note 这里只提供公共api 73 | */ 74 | @interface RTNetworking : NSObject 75 | 76 | /*! 77 | * 用于指定网络请求接口的基础url,如: 78 | * 通常在AppDelegate中启动时就设置一次就可以了。如果接口有来源 79 | * 于多个服务器,可以调用更新 80 | * 81 | * @param baseUrl 网络接口的基础url 82 | */ 83 | + (void)updateBaseUrl:(NSString *)baseUrl; 84 | + (NSString *)baseUrl; 85 | 86 | /** 87 | * 设置请求超时时间,默认为60秒 88 | * 89 | * @param timeout 超时时间 90 | */ 91 | + (void)setTimeout:(NSTimeInterval)timeout; 92 | 93 | /** 94 | * 当检查到网络异常时,是否从从本地提取数据。默认为NO。一旦设置为YES,当设置刷新缓存时, 95 | * 若网络异常也会从缓存中读取数据。同样,如果设置超时不回调,同样也会在网络异常时回调,除非 96 | * 本地没有数据! 97 | * 98 | * @param shouldObtain YES/NO 99 | */ 100 | + (void)obtainDataFromLocalWhenNetworkUnconnected:(BOOL)shouldObtain; 101 | 102 | /** 103 | * 默认只缓存GET请求的数据,对于POST请求是不缓存的。如果要缓存POST获取的数据,需要手动调用设置 104 | * 对JSON类型数据有效,对于PLIST、XML不确定! 105 | * 106 | * @param isCacheGet 默认为YES 107 | * @param shouldCachePost 默认为NO 108 | */ 109 | + (void)cacheGetRequest:(BOOL)isCacheGet shoulCachePost:(BOOL)shouldCachePost; 110 | 111 | /** 112 | * 获取缓存总大小/bytes 113 | * 114 | * @return 缓存大小 115 | */ 116 | + (unsigned long long)totalCacheSize; 117 | 118 | /** 119 | * 默认不会自动清除缓存,如果需要,可以设置自动清除缓存,并且需要指定上限。当指定上限>0M时, 120 | * 若缓存达到了上限值,则每次启动应用则尝试自动去清理缓存。 121 | * 122 | * @param mSize 缓存上限大小,单位为M(兆),默认为0,表示不清理 123 | */ 124 | + (void)autoToClearCacheWithLimitedToSize:(NSUInteger)mSize; 125 | 126 | /** 127 | * 清除缓存 128 | */ 129 | + (void)clearCaches; 130 | 131 | /*! 132 | * 开启或关闭接口打印信息 133 | * 134 | * @param isDebug 开发期,最好打开,默认是NO 135 | */ 136 | + (void)enableInterfaceDebug:(BOOL)isDebug; 137 | 138 | /*! 139 | * 配置请求格式,默认为JSON。如果要求传XML或者PLIST,请在全局配置一下 140 | * 141 | * @param requestType 请求格式,默认为JSON 142 | * @param responseType 响应格式,默认为JSO, 143 | * @param shouldAutoEncode YES or NO,默认为NO,是否自动encode url 144 | * @param shouldCallbackOnCancelRequest 当取消请求时,是否要回调,默认为YES 145 | */ 146 | + (void)configRequestType:(RTRequestType)requestType 147 | responseType:(RTResponseType)responseType 148 | shouldAutoEncodeUrl:(BOOL)shouldAutoEncode 149 | callbackOnCancelRequest:(BOOL)shouldCallbackOnCancelRequest; 150 | 151 | /*! 152 | * 配置公共的请求头,只调用一次即可,通常放在应用启动的时候配置就可以了 153 | * 154 | * @param httpHeaders 只需要将与服务器商定的固定参数设置即可 155 | */ 156 | + (void)configCommonHttpHeaders:(NSDictionary *)httpHeaders; 157 | 158 | /** 159 | * 取消所有请求 160 | */ 161 | + (void)cancelAllRequest; 162 | 163 | /** 164 | * 取消某个请求。如果是要取消某个请求,最好是引用接口所返回来的RTURLSessionTask对象, 165 | * 然后调用对象的cancel方法。如果不想引用对象,这里额外提供了一种方法来实现取消某个请求 166 | * 167 | * @param url URL,可以是绝对URL,也可以是path(也就是不包括baseurl) 168 | */ 169 | + (void)cancelRequestWithURL:(NSString *)url; 170 | 171 | /*! 172 | * 173 | * GET请求接口,若不指定baseurl,可传完整的url 174 | * 175 | * @param url 接口路径,如/path/getArticleList 176 | * @param refreshCache 是否刷新缓存。由于请求成功也可能没有数据,对于业务失败,只能通过人为手动判断 177 | * @param params 接口中所需要的拼接参数,如@{"categoryid" : @(12)} 178 | * @param success 接口成功请求到数据的回调 179 | * @param fail 接口请求数据失败的回调 180 | * 181 | * @return 返回的对象中有可取消请求的API 182 | */ 183 | + (RTURLSessionTask *)getWithUrl:(NSString *)url 184 | refreshCache:(BOOL)refreshCache 185 | success:(RTResponseSuccess)success 186 | fail:(RTResponseFail)fail; 187 | // 多一个params参数 188 | + (RTURLSessionTask *)getWithUrl:(NSString *)url 189 | refreshCache:(BOOL)refreshCache 190 | params:(NSDictionary *)params 191 | success:(RTResponseSuccess)success 192 | fail:(RTResponseFail)fail; 193 | // 多一个带进度回调 194 | + (RTURLSessionTask *)getWithUrl:(NSString *)url 195 | refreshCache:(BOOL)refreshCache 196 | params:(NSDictionary *)params 197 | progress:(RTGetProgress)progress 198 | success:(RTResponseSuccess)success 199 | fail:(RTResponseFail)fail; 200 | 201 | /*! 202 | * 203 | * POST请求接口,若不指定baseurl,可传完整的url 204 | * 205 | * @param url 接口路径,如/path/getArticleList 206 | * @param params 接口中所需的参数,如@{"categoryid" : @(12)} 207 | * @param success 接口成功请求到数据的回调 208 | * @param fail 接口请求数据失败的回调 209 | * 210 | * @return 返回的对象中有可取消请求的API 211 | */ 212 | + (RTURLSessionTask *)postWithUrl:(NSString *)url 213 | refreshCache:(BOOL)refreshCache 214 | params:(NSDictionary *)params 215 | success:(RTResponseSuccess)success 216 | fail:(RTResponseFail)fail; 217 | + (RTURLSessionTask *)postWithUrl:(NSString *)url 218 | refreshCache:(BOOL)refreshCache 219 | params:(NSDictionary *)params 220 | progress:(RTPostProgress)progress 221 | success:(RTResponseSuccess)success 222 | fail:(RTResponseFail)fail; 223 | 224 | /** 225 | * 图片上传接口,若不指定baseurl,可传完整的url 226 | * 227 | * @param image 图片对象 228 | * @param url 上传图片的接口路径,如/path/images/ 229 | * @param filename 给图片起一个名字,默认为当前日期时间,格式为"yyyyMMddHHmmss",后缀为`jpg` 230 | * @param name 与指定的图片相关联的名称,这是由后端写接口的人指定的,如imagefiles 231 | * @param mimeType 默认为image/jpeg 232 | * @param parameters 参数 233 | * @param progress 上传进度 234 | * @param success 上传成功回调 235 | * @param fail 上传失败回调 236 | * 237 | * @return 238 | */ 239 | + (RTURLSessionTask *)uploadWithImage:(UIImage *)image 240 | url:(NSString *)url 241 | filename:(NSString *)filename 242 | name:(NSString *)name 243 | mimeType:(NSString *)mimeType 244 | parameters:(NSDictionary *)parameters 245 | progress:(RTUploadProgress)progress 246 | success:(RTResponseSuccess)success 247 | fail:(RTResponseFail)fail; 248 | 249 | /** 250 | * @author 黄仪标, 16-01-31 00:01:59 251 | * 252 | * 上传文件操作 253 | * 254 | * @param url 上传路径 255 | * @param uploadingFile 待上传文件的路径 256 | * @param progress 上传进度 257 | * @param success 上传成功回调 258 | * @param fail 上传失败回调 259 | * 260 | * @return 261 | */ 262 | + (RTURLSessionTask *)uploadFileWithUrl:(NSString *)url 263 | uploadingFile:(NSString *)uploadingFile 264 | progress:(RTUploadProgress)progress 265 | success:(RTResponseSuccess)success 266 | fail:(RTResponseFail)fail; 267 | 268 | 269 | /*! 270 | * @author 黄仪标, 16-01-08 15:01:11 271 | * 272 | * 下载文件 273 | * 274 | * @param url 下载URL 275 | * @param saveToPath 下载到哪个路径下 276 | * @param progressBlock 下载进度 277 | * @param success 下载成功后的回调 278 | * @param failure 下载失败后的回调 279 | */ 280 | + (RTURLSessionTask *)downloadWithUrl:(NSString *)url 281 | saveToPath:(NSString *)saveToPath 282 | progress:(RTDownloadProgress)progressBlock 283 | success:(RTResponseSuccess)success 284 | failure:(RTResponseFail)failure; 285 | 286 | @end 287 | -------------------------------------------------------------------------------- /MVVMDemo/Base/ViewModelClass.h: -------------------------------------------------------------------------------- 1 | 2 | 3 | #import 4 | #import 5 | 6 | //定义返回请求数据的block类型 7 | typedef void (^ReturnValueBlock) (id returnValue); 8 | typedef void (^ErrorCodeBlock) (id errorCode); 9 | 10 | @interface ViewModelClass : NSObject 11 | 12 | 13 | @property (strong, nonatomic) ReturnValueBlock returnBlock; 14 | @property (strong, nonatomic) ErrorCodeBlock errorBlock; 15 | 16 | // 传入交互的Block块 17 | -(void) setBlockWithReturnBlock: (ReturnValueBlock) returnBlock 18 | WithErrorBlock: (ErrorCodeBlock) errorBlock; 19 | @end 20 | -------------------------------------------------------------------------------- /MVVMDemo/Base/ViewModelClass.m: -------------------------------------------------------------------------------- 1 | 2 | 3 | #import "ViewModelClass.h" 4 | #import "RTNetworking.h" 5 | 6 | @implementation ViewModelClass 7 | 8 | 9 | #pragma 接收传过来的block 10 | -(void) setBlockWithReturnBlock: (ReturnValueBlock) returnBlock 11 | WithErrorBlock: (ErrorCodeBlock) errorBlock 12 | { 13 | _returnBlock = returnBlock; 14 | _errorBlock = errorBlock; 15 | } 16 | @end 17 | -------------------------------------------------------------------------------- /MVVMDemo/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 | CFBundleVersion 20 | 1 21 | LSRequiresIPhoneOS 22 | 23 | UILaunchStoryboardName 24 | LaunchScreen 25 | UIMainStoryboardFile 26 | Main 27 | UIRequiredDeviceCapabilities 28 | 29 | armv7 30 | 31 | UISupportedInterfaceOrientations 32 | 33 | UIInterfaceOrientationPortrait 34 | UIInterfaceOrientationLandscapeLeft 35 | UIInterfaceOrientationLandscapeRight 36 | 37 | UISupportedInterfaceOrientations~ipad 38 | 39 | UIInterfaceOrientationPortrait 40 | UIInterfaceOrientationPortraitUpsideDown 41 | UIInterfaceOrientationLandscapeLeft 42 | UIInterfaceOrientationLandscapeRight 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /MVVMDemo/Lib/AFNetworking/AFNetworkReachabilityManager.h: -------------------------------------------------------------------------------- 1 | // AFNetworkReachabilityManager.h 2 | // Copyright (c) 2011–2015 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 | -------------------------------------------------------------------------------- /MVVMDemo/Lib/AFNetworking/AFNetworkReachabilityManager.m: -------------------------------------------------------------------------------- 1 | // AFNetworkReachabilityManager.m 2 | // Copyright (c) 2011–2015 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 (readwrite, nonatomic, strong) id 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 | #ifndef __clang_analyzer__ 127 | + (instancetype)managerForDomain:(NSString *)domain { 128 | SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [domain UTF8String]); 129 | 130 | AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability]; 131 | 132 | return manager; 133 | } 134 | #endif 135 | 136 | #ifndef __clang_analyzer__ 137 | + (instancetype)managerForAddress:(const void *)address { 138 | SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)address); 139 | AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability]; 140 | 141 | return manager; 142 | } 143 | #endif 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 | self.networkReachability = CFBridgingRelease(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 | 182 | #pragma mark - 183 | 184 | - (BOOL)isReachable { 185 | return [self isReachableViaWWAN] || [self isReachableViaWiFi]; 186 | } 187 | 188 | - (BOOL)isReachableViaWWAN { 189 | return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN; 190 | } 191 | 192 | - (BOOL)isReachableViaWiFi { 193 | return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi; 194 | } 195 | 196 | #pragma mark - 197 | 198 | - (void)startMonitoring { 199 | [self stopMonitoring]; 200 | 201 | if (!self.networkReachability) { 202 | return; 203 | } 204 | 205 | __weak __typeof(self)weakSelf = self; 206 | AFNetworkReachabilityStatusBlock callback = ^(AFNetworkReachabilityStatus status) { 207 | __strong __typeof(weakSelf)strongSelf = weakSelf; 208 | 209 | strongSelf.networkReachabilityStatus = status; 210 | if (strongSelf.networkReachabilityStatusBlock) { 211 | strongSelf.networkReachabilityStatusBlock(status); 212 | } 213 | 214 | }; 215 | 216 | id networkReachability = self.networkReachability; 217 | SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL}; 218 | SCNetworkReachabilitySetCallback((__bridge SCNetworkReachabilityRef)networkReachability, AFNetworkReachabilityCallback, &context); 219 | SCNetworkReachabilityScheduleWithRunLoop((__bridge SCNetworkReachabilityRef)networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes); 220 | 221 | dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),^{ 222 | SCNetworkReachabilityFlags flags; 223 | if (SCNetworkReachabilityGetFlags((__bridge SCNetworkReachabilityRef)networkReachability, &flags)) { 224 | AFPostReachabilityStatusChange(flags, callback); 225 | } 226 | }); 227 | } 228 | 229 | - (void)stopMonitoring { 230 | if (!self.networkReachability) { 231 | return; 232 | } 233 | 234 | SCNetworkReachabilityUnscheduleFromRunLoop((__bridge SCNetworkReachabilityRef)self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes); 235 | } 236 | 237 | #pragma mark - 238 | 239 | - (NSString *)localizedNetworkReachabilityStatusString { 240 | return AFStringFromNetworkReachabilityStatus(self.networkReachabilityStatus); 241 | } 242 | 243 | #pragma mark - 244 | 245 | - (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block { 246 | self.networkReachabilityStatusBlock = block; 247 | } 248 | 249 | #pragma mark - NSKeyValueObserving 250 | 251 | + (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key { 252 | if ([key isEqualToString:@"reachable"] || [key isEqualToString:@"reachableViaWWAN"] || [key isEqualToString:@"reachableViaWiFi"]) { 253 | return [NSSet setWithObject:@"networkReachabilityStatus"]; 254 | } 255 | 256 | return [super keyPathsForValuesAffectingValueForKey:key]; 257 | } 258 | 259 | @end 260 | #endif 261 | -------------------------------------------------------------------------------- /MVVMDemo/Lib/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 | -------------------------------------------------------------------------------- /MVVMDemo/Lib/AFNetworking/AFSecurityPolicy.h: -------------------------------------------------------------------------------- 1 | // AFSecurityPolicy.h 2 | // Copyright (c) 2011–2015 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 | -------------------------------------------------------------------------------- /MVVMDemo/Lib/AFNetworking/AFURLResponseSerialization.h: -------------------------------------------------------------------------------- 1 | // AFURLResponseSerialization.h 2 | // Copyright (c) 2011–2015 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 | NS_ASSUME_NONNULL_BEGIN 26 | 27 | /** 28 | The `AFURLResponseSerialization` protocol is adopted by an object that decodes data into a more useful object representation, according to details in the server response. Response serializers may additionally perform validation on the incoming response and data. 29 | 30 | For example, a JSON response serializer may check for an acceptable status code (`2XX` range) and content type (`application/json`), decoding a valid JSON response into an object. 31 | */ 32 | @protocol AFURLResponseSerialization 33 | 34 | /** 35 | The response object decoded from the data associated with a specified response. 36 | 37 | @param response The response to be processed. 38 | @param data The response data to be decoded. 39 | @param error The error that occurred while attempting to decode the response data. 40 | 41 | @return The object decoded from the specified response data. 42 | */ 43 | - (nullable id)responseObjectForResponse:(nullable NSURLResponse *)response 44 | data:(nullable NSData *)data 45 | error:(NSError * _Nullable __autoreleasing *)error NS_SWIFT_NOTHROW; 46 | 47 | @end 48 | 49 | #pragma mark - 50 | 51 | /** 52 | `AFHTTPResponseSerializer` conforms to the `AFURLRequestSerialization` & `AFURLResponseSerialization` protocols, offering a concrete base implementation of query string / URL form-encoded parameter serialization and default request headers, as well as response status code and content type validation. 53 | 54 | Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPResponseSerializer` in order to ensure consistent default behavior. 55 | */ 56 | @interface AFHTTPResponseSerializer : NSObject 57 | 58 | - (instancetype)init; 59 | 60 | /** 61 | The string encoding used to serialize data received from the server, when no string encoding is specified by the response. `NSUTF8StringEncoding` by default. 62 | */ 63 | @property (nonatomic, assign) NSStringEncoding stringEncoding; 64 | 65 | /** 66 | Creates and returns a serializer with default configuration. 67 | */ 68 | + (instancetype)serializer; 69 | 70 | ///----------------------------------------- 71 | /// @name Configuring Response Serialization 72 | ///----------------------------------------- 73 | 74 | /** 75 | The acceptable HTTP status codes for responses. When non-`nil`, responses with status codes not contained by the set will result in an error during validation. 76 | 77 | See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html 78 | */ 79 | @property (nonatomic, copy, nullable) NSIndexSet *acceptableStatusCodes; 80 | 81 | /** 82 | The acceptable MIME types for responses. When non-`nil`, responses with a `Content-Type` with MIME types that do not intersect with the set will result in an error during validation. 83 | */ 84 | @property (nonatomic, copy, nullable) NSSet *acceptableContentTypes; 85 | 86 | /** 87 | Validates the specified response and data. 88 | 89 | In its base implementation, this method checks for an acceptable status code and content type. Subclasses may wish to add other domain-specific checks. 90 | 91 | @param response The response to be validated. 92 | @param data The data associated with the response. 93 | @param error The error that occurred while attempting to validate the response. 94 | 95 | @return `YES` if the response is valid, otherwise `NO`. 96 | */ 97 | - (BOOL)validateResponse:(nullable NSHTTPURLResponse *)response 98 | data:(nullable NSData *)data 99 | error:(NSError * _Nullable __autoreleasing *)error; 100 | 101 | @end 102 | 103 | #pragma mark - 104 | 105 | 106 | /** 107 | `AFJSONResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes JSON responses. 108 | 109 | By default, `AFJSONResponseSerializer` accepts the following MIME types, which includes the official standard, `application/json`, as well as other commonly-used types: 110 | 111 | - `application/json` 112 | - `text/json` 113 | - `text/javascript` 114 | */ 115 | @interface AFJSONResponseSerializer : AFHTTPResponseSerializer 116 | 117 | - (instancetype)init; 118 | 119 | /** 120 | Options for reading the response JSON data and creating the Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default. 121 | */ 122 | @property (nonatomic, assign) NSJSONReadingOptions readingOptions; 123 | 124 | /** 125 | Whether to remove keys with `NSNull` values from response JSON. Defaults to `NO`. 126 | */ 127 | @property (nonatomic, assign) BOOL removesKeysWithNullValues; 128 | 129 | /** 130 | Creates and returns a JSON serializer with specified reading and writing options. 131 | 132 | @param readingOptions The specified JSON reading options. 133 | */ 134 | + (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions; 135 | 136 | @end 137 | 138 | #pragma mark - 139 | 140 | /** 141 | `AFXMLParserResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLParser` objects. 142 | 143 | By default, `AFXMLParserResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types: 144 | 145 | - `application/xml` 146 | - `text/xml` 147 | */ 148 | @interface AFXMLParserResponseSerializer : AFHTTPResponseSerializer 149 | 150 | @end 151 | 152 | #pragma mark - 153 | 154 | #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED 155 | 156 | /** 157 | `AFXMLDocumentResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects. 158 | 159 | By default, `AFXMLDocumentResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types: 160 | 161 | - `application/xml` 162 | - `text/xml` 163 | */ 164 | @interface AFXMLDocumentResponseSerializer : AFHTTPResponseSerializer 165 | 166 | - (instancetype)init; 167 | 168 | /** 169 | Input and output options specifically intended for `NSXMLDocument` objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default. 170 | */ 171 | @property (nonatomic, assign) NSUInteger options; 172 | 173 | /** 174 | Creates and returns an XML document serializer with the specified options. 175 | 176 | @param mask The XML document options. 177 | */ 178 | + (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask; 179 | 180 | @end 181 | 182 | #endif 183 | 184 | #pragma mark - 185 | 186 | /** 187 | `AFPropertyListResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects. 188 | 189 | By default, `AFPropertyListResponseSerializer` accepts the following MIME types: 190 | 191 | - `application/x-plist` 192 | */ 193 | @interface AFPropertyListResponseSerializer : AFHTTPResponseSerializer 194 | 195 | - (instancetype)init; 196 | 197 | /** 198 | The property list format. Possible values are described in "NSPropertyListFormat". 199 | */ 200 | @property (nonatomic, assign) NSPropertyListFormat format; 201 | 202 | /** 203 | The property list reading options. Possible values are described in "NSPropertyListMutabilityOptions." 204 | */ 205 | @property (nonatomic, assign) NSPropertyListReadOptions readOptions; 206 | 207 | /** 208 | Creates and returns a property list serializer with a specified format, read options, and write options. 209 | 210 | @param format The property list format. 211 | @param readOptions The property list reading options. 212 | */ 213 | + (instancetype)serializerWithFormat:(NSPropertyListFormat)format 214 | readOptions:(NSPropertyListReadOptions)readOptions; 215 | 216 | @end 217 | 218 | #pragma mark - 219 | 220 | /** 221 | `AFImageResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes image responses. 222 | 223 | By default, `AFImageResponseSerializer` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage: 224 | 225 | - `image/tiff` 226 | - `image/jpeg` 227 | - `image/gif` 228 | - `image/png` 229 | - `image/ico` 230 | - `image/x-icon` 231 | - `image/bmp` 232 | - `image/x-bmp` 233 | - `image/x-xbitmap` 234 | - `image/x-win-bitmap` 235 | */ 236 | @interface AFImageResponseSerializer : AFHTTPResponseSerializer 237 | 238 | #if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH 239 | /** 240 | The scale factor used when interpreting the image data to construct `responseImage`. Specifying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the size property. This is set to the value of scale of the main screen by default, which automatically scales images for retina displays, for instance. 241 | */ 242 | @property (nonatomic, assign) CGFloat imageScale; 243 | 244 | /** 245 | Whether to automatically inflate response image data for compressed formats (such as PNG or JPEG). Enabling this can significantly improve drawing performance on iOS when used with `setCompletionBlockWithSuccess:failure:`, as it allows a bitmap representation to be constructed in the background rather than on the main thread. `YES` by default. 246 | */ 247 | @property (nonatomic, assign) BOOL automaticallyInflatesResponseImage; 248 | #endif 249 | 250 | @end 251 | 252 | #pragma mark - 253 | 254 | /** 255 | `AFCompoundSerializer` is a subclass of `AFHTTPResponseSerializer` that delegates the response serialization to the first `AFHTTPResponseSerializer` object that returns an object for `responseObjectForResponse:data:error:`, falling back on the default behavior of `AFHTTPResponseSerializer`. This is useful for supporting multiple potential types and structures of server responses with a single serializer. 256 | */ 257 | @interface AFCompoundResponseSerializer : AFHTTPResponseSerializer 258 | 259 | /** 260 | The component response serializers. 261 | */ 262 | @property (readonly, nonatomic, copy) NSArray > *responseSerializers; 263 | 264 | /** 265 | Creates and returns a compound serializer comprised of the specified response serializers. 266 | 267 | @warning Each response serializer specified must be a subclass of `AFHTTPResponseSerializer`, and response to `-validateResponse:data:error:`. 268 | */ 269 | + (instancetype)compoundSerializerWithResponseSerializers:(NSArray > *)responseSerializers; 270 | 271 | @end 272 | 273 | ///---------------- 274 | /// @name Constants 275 | ///---------------- 276 | 277 | /** 278 | ## Error Domains 279 | 280 | The following error domain is predefined. 281 | 282 | - `NSString * const AFURLResponseSerializationErrorDomain` 283 | 284 | ### Constants 285 | 286 | `AFURLResponseSerializationErrorDomain` 287 | AFURLResponseSerializer errors. Error codes for `AFURLResponseSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`. 288 | */ 289 | FOUNDATION_EXPORT NSString * const AFURLResponseSerializationErrorDomain; 290 | 291 | /** 292 | ## User info dictionary keys 293 | 294 | These keys may exist in the user info dictionary, in addition to those defined for NSError. 295 | 296 | - `NSString * const AFNetworkingOperationFailingURLResponseErrorKey` 297 | - `NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey` 298 | 299 | ### Constants 300 | 301 | `AFNetworkingOperationFailingURLResponseErrorKey` 302 | The corresponding value is an `NSURLResponse` containing the response of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`. 303 | 304 | `AFNetworkingOperationFailingURLResponseDataErrorKey` 305 | The corresponding value is an `NSData` containing the original data of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`. 306 | */ 307 | FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseErrorKey; 308 | 309 | FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey; 310 | 311 | NS_ASSUME_NONNULL_END 312 | -------------------------------------------------------------------------------- /MVVMDemo/Lib/UIKit+AFNetworking/AFAutoPurgingImageCache.h: -------------------------------------------------------------------------------- 1 | // AFAutoPurgingImageCache.h 2 | // Copyright (c) 2011–2015 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 preferredMemoryUsageAfterPurge 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 | -------------------------------------------------------------------------------- /MVVMDemo/Lib/UIKit+AFNetworking/AFAutoPurgingImageCache.m: -------------------------------------------------------------------------------- 1 | // AFAutoPurgingImageCache.m 2 | // Copyright (c) 2011–2015 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 bytesPerRow = imageSize.width * bytesPerPixel; 48 | self.totalBytes = (UInt64)bytesPerPixel * (UInt64)bytesPerRow; 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 | -------------------------------------------------------------------------------- /MVVMDemo/Lib/UIKit+AFNetworking/AFImageDownloader.h: -------------------------------------------------------------------------------- 1 | // AFImageDownloader.h 2 | // Copyright (c) 2011–2015 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 request 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 | -------------------------------------------------------------------------------- /MVVMDemo/Lib/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h: -------------------------------------------------------------------------------- 1 | // AFNetworkActivityIndicatorManager.h 2 | // Copyright (c) 2011–2015 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 | -------------------------------------------------------------------------------- /MVVMDemo/Lib/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m: -------------------------------------------------------------------------------- 1 | // AFNetworkActivityIndicatorManager.m 2 | // Copyright (c) 2011–2015 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 "AFNetworkActivityIndicatorManager.h" 23 | 24 | #if TARGET_OS_IOS 25 | #import "AFURLSessionManager.h" 26 | 27 | typedef NS_ENUM(NSInteger, AFNetworkActivityManagerState) { 28 | AFNetworkActivityManagerStateNotActive, 29 | AFNetworkActivityManagerStateDelayingStart, 30 | AFNetworkActivityManagerStateActive, 31 | AFNetworkActivityManagerStateDelayingEnd 32 | }; 33 | 34 | static NSTimeInterval const kDefaultAFNetworkActivityManagerActivationDelay = 1.0; 35 | static NSTimeInterval const kDefaultAFNetworkActivityManagerCompletionDelay = 0.17; 36 | 37 | static NSURLRequest * AFNetworkRequestFromNotification(NSNotification *notification) { 38 | if ([[notification object] respondsToSelector:@selector(originalRequest)]) { 39 | return [(NSURLSessionTask *)[notification object] originalRequest]; 40 | } else { 41 | return nil; 42 | } 43 | } 44 | 45 | typedef void (^AFNetworkActivityActionBlock)(BOOL networkActivityIndicatorVisible); 46 | 47 | @interface AFNetworkActivityIndicatorManager () 48 | @property (readwrite, nonatomic, assign) NSInteger activityCount; 49 | @property (readwrite, nonatomic, strong) NSTimer *activationDelayTimer; 50 | @property (readwrite, nonatomic, strong) NSTimer *completionDelayTimer; 51 | @property (readonly, nonatomic, getter = isNetworkActivityOccurring) BOOL networkActivityOccurring; 52 | @property (nonatomic, copy) AFNetworkActivityActionBlock networkActivityActionBlock; 53 | @property (nonatomic, assign) AFNetworkActivityManagerState currentState; 54 | @property (nonatomic, assign, getter=isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible; 55 | 56 | - (void)updateCurrentStateForNetworkActivityChange; 57 | @end 58 | 59 | @implementation AFNetworkActivityIndicatorManager 60 | 61 | + (instancetype)sharedManager { 62 | static AFNetworkActivityIndicatorManager *_sharedManager = nil; 63 | static dispatch_once_t oncePredicate; 64 | dispatch_once(&oncePredicate, ^{ 65 | _sharedManager = [[self alloc] init]; 66 | }); 67 | 68 | return _sharedManager; 69 | } 70 | 71 | - (instancetype)init { 72 | self = [super init]; 73 | if (!self) { 74 | return nil; 75 | } 76 | self.currentState = AFNetworkActivityManagerStateNotActive; 77 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidStart:) name:AFNetworkingTaskDidResumeNotification object:nil]; 78 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingTaskDidSuspendNotification object:nil]; 79 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingTaskDidCompleteNotification object:nil]; 80 | self.activationDelay = kDefaultAFNetworkActivityManagerActivationDelay; 81 | self.completionDelay = kDefaultAFNetworkActivityManagerCompletionDelay; 82 | 83 | return self; 84 | } 85 | 86 | - (void)dealloc { 87 | [[NSNotificationCenter defaultCenter] removeObserver:self]; 88 | 89 | [_activationDelayTimer invalidate]; 90 | [_completionDelayTimer invalidate]; 91 | } 92 | 93 | - (void)setEnabled:(BOOL)enabled { 94 | _enabled = enabled; 95 | if (enabled == NO) { 96 | [self setCurrentState:AFNetworkActivityManagerStateNotActive]; 97 | } 98 | } 99 | 100 | - (void)setNetworkingActivityActionWithBlock:(void (^)(BOOL networkActivityIndicatorVisible))block { 101 | self.networkActivityActionBlock = block; 102 | } 103 | 104 | - (BOOL)isNetworkActivityOccurring { 105 | @synchronized(self) { 106 | return self.activityCount > 0; 107 | } 108 | } 109 | 110 | - (void)setNetworkActivityIndicatorVisible:(BOOL)networkActivityIndicatorVisible { 111 | if (_networkActivityIndicatorVisible != networkActivityIndicatorVisible) { 112 | [self willChangeValueForKey:@"networkActivityIndicatorVisible"]; 113 | @synchronized(self) { 114 | _networkActivityIndicatorVisible = networkActivityIndicatorVisible; 115 | } 116 | [self didChangeValueForKey:@"networkActivityIndicatorVisible"]; 117 | if (self.networkActivityActionBlock) { 118 | self.networkActivityActionBlock(networkActivityIndicatorVisible); 119 | } else { 120 | [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:networkActivityIndicatorVisible]; 121 | } 122 | } 123 | } 124 | 125 | - (void)setActivityCount:(NSInteger)activityCount { 126 | @synchronized(self) { 127 | _activityCount = activityCount; 128 | } 129 | 130 | dispatch_async(dispatch_get_main_queue(), ^{ 131 | [self updateCurrentStateForNetworkActivityChange]; 132 | }); 133 | } 134 | 135 | - (void)incrementActivityCount { 136 | [self willChangeValueForKey:@"activityCount"]; 137 | @synchronized(self) { 138 | _activityCount++; 139 | } 140 | [self didChangeValueForKey:@"activityCount"]; 141 | 142 | dispatch_async(dispatch_get_main_queue(), ^{ 143 | [self updateCurrentStateForNetworkActivityChange]; 144 | }); 145 | } 146 | 147 | - (void)decrementActivityCount { 148 | [self willChangeValueForKey:@"activityCount"]; 149 | @synchronized(self) { 150 | #pragma clang diagnostic push 151 | #pragma clang diagnostic ignored "-Wgnu" 152 | _activityCount = MAX(_activityCount - 1, 0); 153 | #pragma clang diagnostic pop 154 | } 155 | [self didChangeValueForKey:@"activityCount"]; 156 | 157 | dispatch_async(dispatch_get_main_queue(), ^{ 158 | [self updateCurrentStateForNetworkActivityChange]; 159 | }); 160 | } 161 | 162 | - (void)networkRequestDidStart:(NSNotification *)notification { 163 | if ([AFNetworkRequestFromNotification(notification) URL]) { 164 | [self incrementActivityCount]; 165 | } 166 | } 167 | 168 | - (void)networkRequestDidFinish:(NSNotification *)notification { 169 | if ([AFNetworkRequestFromNotification(notification) URL]) { 170 | [self decrementActivityCount]; 171 | } 172 | } 173 | 174 | #pragma mark - Internal State Management 175 | - (void)setCurrentState:(AFNetworkActivityManagerState)currentState { 176 | @synchronized(self) { 177 | if (_currentState != currentState) { 178 | [self willChangeValueForKey:@"currentState"]; 179 | _currentState = currentState; 180 | switch (currentState) { 181 | case AFNetworkActivityManagerStateNotActive: 182 | [self cancelActivationDelayTimer]; 183 | [self cancelCompletionDelayTimer]; 184 | [self setNetworkActivityIndicatorVisible:NO]; 185 | break; 186 | case AFNetworkActivityManagerStateDelayingStart: 187 | [self startActivationDelayTimer]; 188 | break; 189 | case AFNetworkActivityManagerStateActive: 190 | [self cancelCompletionDelayTimer]; 191 | [self setNetworkActivityIndicatorVisible:YES]; 192 | break; 193 | case AFNetworkActivityManagerStateDelayingEnd: 194 | [self startCompletionDelayTimer]; 195 | break; 196 | } 197 | } 198 | [self didChangeValueForKey:@"currentState"]; 199 | } 200 | } 201 | 202 | - (void)updateCurrentStateForNetworkActivityChange { 203 | if (self.enabled) { 204 | switch (self.currentState) { 205 | case AFNetworkActivityManagerStateNotActive: 206 | if (self.isNetworkActivityOccurring) { 207 | [self setCurrentState:AFNetworkActivityManagerStateDelayingStart]; 208 | } 209 | break; 210 | case AFNetworkActivityManagerStateDelayingStart: 211 | //No op. Let the delay timer finish out. 212 | break; 213 | case AFNetworkActivityManagerStateActive: 214 | if (!self.isNetworkActivityOccurring) { 215 | [self setCurrentState:AFNetworkActivityManagerStateDelayingEnd]; 216 | } 217 | break; 218 | case AFNetworkActivityManagerStateDelayingEnd: 219 | if (self.isNetworkActivityOccurring) { 220 | [self setCurrentState:AFNetworkActivityManagerStateActive]; 221 | } 222 | break; 223 | } 224 | } 225 | } 226 | 227 | - (void)startActivationDelayTimer { 228 | self.activationDelayTimer = [NSTimer 229 | timerWithTimeInterval:self.activationDelay target:self selector:@selector(activationDelayTimerFired) userInfo:nil repeats:NO]; 230 | [[NSRunLoop mainRunLoop] addTimer:self.activationDelayTimer forMode:NSRunLoopCommonModes]; 231 | } 232 | 233 | - (void)activationDelayTimerFired { 234 | if (self.networkActivityOccurring) { 235 | [self setCurrentState:AFNetworkActivityManagerStateActive]; 236 | } else { 237 | [self setCurrentState:AFNetworkActivityManagerStateNotActive]; 238 | } 239 | } 240 | 241 | - (void)startCompletionDelayTimer { 242 | [self.completionDelayTimer invalidate]; 243 | self.completionDelayTimer = [NSTimer timerWithTimeInterval:self.completionDelay target:self selector:@selector(completionDelayTimerFired) userInfo:nil repeats:NO]; 244 | [[NSRunLoop mainRunLoop] addTimer:self.completionDelayTimer forMode:NSRunLoopCommonModes]; 245 | } 246 | 247 | - (void)completionDelayTimerFired { 248 | [self setCurrentState:AFNetworkActivityManagerStateNotActive]; 249 | } 250 | 251 | - (void)cancelActivationDelayTimer { 252 | [self.activationDelayTimer invalidate]; 253 | } 254 | 255 | - (void)cancelCompletionDelayTimer { 256 | [self.completionDelayTimer invalidate]; 257 | } 258 | 259 | @end 260 | 261 | #endif 262 | -------------------------------------------------------------------------------- /MVVMDemo/Lib/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h: -------------------------------------------------------------------------------- 1 | // UIActivityIndicatorView+AFNetworking.h 2 | // Copyright (c) 2011–2015 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 | -------------------------------------------------------------------------------- /MVVMDemo/Lib/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m: -------------------------------------------------------------------------------- 1 | // UIActivityIndicatorView+AFNetworking.m 2 | // Copyright (c) 2011–2015 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 | -------------------------------------------------------------------------------- /MVVMDemo/Lib/UIKit+AFNetworking/UIButton+AFNetworking.h: -------------------------------------------------------------------------------- 1 | // UIButton+AFNetworking.h 2 | // Copyright (c) 2011–2015 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 | -------------------------------------------------------------------------------- /MVVMDemo/Lib/UIKit+AFNetworking/UIButton+AFNetworking.m: -------------------------------------------------------------------------------- 1 | // UIButton+AFNetworking.m 2 | // Copyright (c) 2011–2015 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 "UIButton+AFNetworking.h" 23 | 24 | #import 25 | 26 | #if TARGET_OS_IOS || TARGET_OS_TV 27 | 28 | #import "UIImageView+AFNetworking.h" 29 | #import "AFImageDownloader.h" 30 | 31 | @interface UIButton (_AFNetworking) 32 | @end 33 | 34 | @implementation UIButton (_AFNetworking) 35 | 36 | #pragma mark - 37 | 38 | static char AFImageDownloadReceiptNormal; 39 | static char AFImageDownloadReceiptHighlighted; 40 | static char AFImageDownloadReceiptSelected; 41 | static char AFImageDownloadReceiptDisabled; 42 | 43 | static const char * af_imageDownloadReceiptKeyForState(UIControlState state) { 44 | switch (state) { 45 | case UIControlStateHighlighted: 46 | return &AFImageDownloadReceiptHighlighted; 47 | case UIControlStateSelected: 48 | return &AFImageDownloadReceiptSelected; 49 | case UIControlStateDisabled: 50 | return &AFImageDownloadReceiptDisabled; 51 | case UIControlStateNormal: 52 | default: 53 | return &AFImageDownloadReceiptNormal; 54 | } 55 | } 56 | 57 | - (AFImageDownloadReceipt *)af_imageDownloadReceiptForState:(UIControlState)state { 58 | return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, af_imageDownloadReceiptKeyForState(state)); 59 | } 60 | 61 | - (void)af_setImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt 62 | forState:(UIControlState)state 63 | { 64 | objc_setAssociatedObject(self, af_imageDownloadReceiptKeyForState(state), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 65 | } 66 | 67 | #pragma mark - 68 | 69 | static char AFBackgroundImageDownloadReceiptNormal; 70 | static char AFBackgroundImageDownloadReceiptHighlighted; 71 | static char AFBackgroundImageDownloadReceiptSelected; 72 | static char AFBackgroundImageDownloadReceiptDisabled; 73 | 74 | static const char * af_backgroundImageDownloadReceiptKeyForState(UIControlState state) { 75 | switch (state) { 76 | case UIControlStateHighlighted: 77 | return &AFBackgroundImageDownloadReceiptHighlighted; 78 | case UIControlStateSelected: 79 | return &AFBackgroundImageDownloadReceiptSelected; 80 | case UIControlStateDisabled: 81 | return &AFBackgroundImageDownloadReceiptDisabled; 82 | case UIControlStateNormal: 83 | default: 84 | return &AFBackgroundImageDownloadReceiptNormal; 85 | } 86 | } 87 | 88 | - (AFImageDownloadReceipt *)af_backgroundImageDownloadReceiptForState:(UIControlState)state { 89 | return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, af_backgroundImageDownloadReceiptKeyForState(state)); 90 | } 91 | 92 | - (void)af_setBackgroundImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt 93 | forState:(UIControlState)state 94 | { 95 | objc_setAssociatedObject(self, af_backgroundImageDownloadReceiptKeyForState(state), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 96 | } 97 | 98 | @end 99 | 100 | #pragma mark - 101 | 102 | @implementation UIButton (AFNetworking) 103 | 104 | + (AFImageDownloader *)sharedImageDownloader { 105 | 106 | #pragma clang diagnostic push 107 | #pragma clang diagnostic ignored "-Wgnu" 108 | return objc_getAssociatedObject(self, @selector(sharedImageDownloader)) ?: [AFImageDownloader defaultInstance]; 109 | #pragma clang diagnostic pop 110 | } 111 | 112 | + (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader { 113 | objc_setAssociatedObject(self, @selector(sharedImageDownloader), imageDownloader, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 114 | } 115 | 116 | #pragma mark - 117 | 118 | - (void)setImageForState:(UIControlState)state 119 | withURL:(NSURL *)url 120 | { 121 | [self setImageForState:state withURL:url placeholderImage:nil]; 122 | } 123 | 124 | - (void)setImageForState:(UIControlState)state 125 | withURL:(NSURL *)url 126 | placeholderImage:(UIImage *)placeholderImage 127 | { 128 | NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 129 | [request addValue:@"image/*" forHTTPHeaderField:@"Accept"]; 130 | 131 | [self setImageForState:state withURLRequest:request placeholderImage:placeholderImage success:nil failure:nil]; 132 | } 133 | 134 | - (void)setImageForState:(UIControlState)state 135 | withURLRequest:(NSURLRequest *)urlRequest 136 | placeholderImage:(nullable UIImage *)placeholderImage 137 | success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success 138 | failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure 139 | { 140 | if ([self isActiveTaskURLEqualToURLRequest:urlRequest forState:state]) { 141 | return; 142 | } 143 | 144 | [self cancelImageDownloadTaskForState:state]; 145 | 146 | AFImageDownloader *downloader = [[self class] sharedImageDownloader]; 147 | id imageCache = downloader.imageCache; 148 | 149 | //Use the image from the image cache if it exists 150 | UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil]; 151 | if (cachedImage) { 152 | if (success) { 153 | success(urlRequest, nil, cachedImage); 154 | } else { 155 | [self setImage:cachedImage forState:state]; 156 | } 157 | [self af_setImageDownloadReceipt:nil forState:state]; 158 | } else { 159 | if (placeholderImage) { 160 | [self setImage:placeholderImage forState:state]; 161 | } 162 | 163 | __weak __typeof(self)weakSelf = self; 164 | NSUUID *downloadID = [NSUUID UUID]; 165 | AFImageDownloadReceipt *receipt; 166 | receipt = [downloader 167 | downloadImageForURLRequest:urlRequest 168 | withReceiptID:downloadID 169 | success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { 170 | __strong __typeof(weakSelf)strongSelf = weakSelf; 171 | if ([[strongSelf af_imageDownloadReceiptForState:state].receiptID isEqual:downloadID]) { 172 | if (success) { 173 | success(request, response, responseObject); 174 | } else if(responseObject) { 175 | [strongSelf setImage:responseObject forState:state]; 176 | } 177 | [strongSelf af_setImageDownloadReceipt:nil forState:state]; 178 | } 179 | 180 | } 181 | failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) { 182 | __strong __typeof(weakSelf)strongSelf = weakSelf; 183 | if ([[strongSelf af_imageDownloadReceiptForState:state].receiptID isEqual:downloadID]) { 184 | if (failure) { 185 | failure(request, response, error); 186 | } 187 | [strongSelf af_setImageDownloadReceipt:nil forState:state]; 188 | } 189 | }]; 190 | 191 | [self af_setImageDownloadReceipt:receipt forState:state]; 192 | } 193 | } 194 | 195 | #pragma mark - 196 | 197 | - (void)setBackgroundImageForState:(UIControlState)state 198 | withURL:(NSURL *)url 199 | { 200 | [self setBackgroundImageForState:state withURL:url placeholderImage:nil]; 201 | } 202 | 203 | - (void)setBackgroundImageForState:(UIControlState)state 204 | withURL:(NSURL *)url 205 | placeholderImage:(nullable UIImage *)placeholderImage 206 | { 207 | NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 208 | [request addValue:@"image/*" forHTTPHeaderField:@"Accept"]; 209 | 210 | [self setBackgroundImageForState:state withURLRequest:request placeholderImage:placeholderImage success:nil failure:nil]; 211 | } 212 | 213 | - (void)setBackgroundImageForState:(UIControlState)state 214 | withURLRequest:(NSURLRequest *)urlRequest 215 | placeholderImage:(nullable UIImage *)placeholderImage 216 | success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success 217 | failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure 218 | { 219 | if ([self isActiveBackgroundTaskURLEqualToURLRequest:urlRequest forState:state]) { 220 | return; 221 | } 222 | 223 | [self cancelImageDownloadTaskForState:state]; 224 | 225 | AFImageDownloader *downloader = [[self class] sharedImageDownloader]; 226 | id imageCache = downloader.imageCache; 227 | 228 | //Use the image from the image cache if it exists 229 | UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil]; 230 | if (cachedImage) { 231 | if (success) { 232 | success(urlRequest, nil, cachedImage); 233 | } else { 234 | [self setBackgroundImage:cachedImage forState:state]; 235 | } 236 | [self af_setBackgroundImageDownloadReceipt:nil forState:state]; 237 | } else { 238 | if (placeholderImage) { 239 | [self setBackgroundImage:placeholderImage forState:state]; 240 | } 241 | 242 | __weak __typeof(self)weakSelf = self; 243 | NSUUID *downloadID = [NSUUID UUID]; 244 | AFImageDownloadReceipt *receipt; 245 | receipt = [downloader 246 | downloadImageForURLRequest:urlRequest 247 | withReceiptID:downloadID 248 | success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { 249 | __strong __typeof(weakSelf)strongSelf = weakSelf; 250 | if ([[strongSelf af_backgroundImageDownloadReceiptForState:state].receiptID isEqual:downloadID]) { 251 | if (success) { 252 | success(request, response, responseObject); 253 | } else if(responseObject) { 254 | [strongSelf setBackgroundImage:responseObject forState:state]; 255 | } 256 | [strongSelf af_setImageDownloadReceipt:nil forState:state]; 257 | } 258 | 259 | } 260 | failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) { 261 | __strong __typeof(weakSelf)strongSelf = weakSelf; 262 | if ([[strongSelf af_backgroundImageDownloadReceiptForState:state].receiptID isEqual:downloadID]) { 263 | if (failure) { 264 | failure(request, response, error); 265 | } 266 | [strongSelf af_setBackgroundImageDownloadReceipt:nil forState:state]; 267 | } 268 | }]; 269 | 270 | [self af_setBackgroundImageDownloadReceipt:receipt forState:state]; 271 | } 272 | } 273 | 274 | #pragma mark - 275 | 276 | - (void)cancelImageDownloadTaskForState:(UIControlState)state { 277 | AFImageDownloadReceipt *receipt = [self af_imageDownloadReceiptForState:state]; 278 | if (receipt != nil) { 279 | [[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:receipt]; 280 | [self af_setImageDownloadReceipt:nil forState:state]; 281 | } 282 | } 283 | 284 | - (void)cancelBackgroundImageDownloadTaskForState:(UIControlState)state { 285 | AFImageDownloadReceipt *receipt = [self af_backgroundImageDownloadReceiptForState:state]; 286 | if (receipt != nil) { 287 | [[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:receipt]; 288 | [self af_setBackgroundImageDownloadReceipt:nil forState:state]; 289 | } 290 | } 291 | 292 | - (BOOL)isActiveTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest forState:(UIControlState)state { 293 | AFImageDownloadReceipt *receipt = [self af_imageDownloadReceiptForState:state]; 294 | return [receipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString]; 295 | } 296 | 297 | - (BOOL)isActiveBackgroundTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest forState:(UIControlState)state { 298 | AFImageDownloadReceipt *receipt = [self af_backgroundImageDownloadReceiptForState:state]; 299 | return [receipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString]; 300 | } 301 | 302 | 303 | @end 304 | 305 | #endif 306 | -------------------------------------------------------------------------------- /MVVMDemo/Lib/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 | -------------------------------------------------------------------------------- /MVVMDemo/Lib/UIKit+AFNetworking/UIImageView+AFNetworking.h: -------------------------------------------------------------------------------- 1 | // UIImageView+AFNetworking.h 2 | // Copyright (c) 2011–2015 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 | -------------------------------------------------------------------------------- /MVVMDemo/Lib/UIKit+AFNetworking/UIImageView+AFNetworking.m: -------------------------------------------------------------------------------- 1 | // UIImageView+AFNetworking.m 2 | // Copyright (c) 2011–2015 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 | -------------------------------------------------------------------------------- /MVVMDemo/Lib/UIKit+AFNetworking/UIKit+AFNetworking.h: -------------------------------------------------------------------------------- 1 | // UIKit+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 | #if TARGET_OS_IOS || TARGET_OS_TV 24 | 25 | #import 26 | 27 | #ifndef _UIKIT_AFNETWORKING_ 28 | #define _UIKIT_AFNETWORKING_ 29 | 30 | #if TARGET_OS_IOS 31 | #import "AFAutoPurgingImageCache.h" 32 | #import "AFImageDownloader.h" 33 | #import "AFNetworkActivityIndicatorManager.h" 34 | #import "UIRefreshControl+AFNetworking.h" 35 | #import "UIWebView+AFNetworking.h" 36 | #endif 37 | 38 | #import "UIActivityIndicatorView+AFNetworking.h" 39 | #import "UIButton+AFNetworking.h" 40 | #import "UIImageView+AFNetworking.h" 41 | #import "UIProgressView+AFNetworking.h" 42 | #endif /* _UIKIT_AFNETWORKING_ */ 43 | #endif 44 | -------------------------------------------------------------------------------- /MVVMDemo/Lib/UIKit+AFNetworking/UIProgressView+AFNetworking.h: -------------------------------------------------------------------------------- 1 | // UIProgressView+AFNetworking.h 2 | // Copyright (c) 2011–2015 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 | -------------------------------------------------------------------------------- /MVVMDemo/Lib/UIKit+AFNetworking/UIProgressView+AFNetworking.m: -------------------------------------------------------------------------------- 1 | // UIProgressView+AFNetworking.m 2 | // Copyright (c) 2011–2015 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 | -------------------------------------------------------------------------------- /MVVMDemo/Lib/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h: -------------------------------------------------------------------------------- 1 | // UIRefreshControl+AFNetworking.m 2 | // 3 | // Copyright (c) 2014 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 | 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 | -------------------------------------------------------------------------------- /MVVMDemo/Lib/UIKit+AFNetworking/UIRefreshControl+AFNetworking.m: -------------------------------------------------------------------------------- 1 | // UIRefreshControl+AFNetworking.m 2 | // 3 | // Copyright (c) 2014 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 "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 | -------------------------------------------------------------------------------- /MVVMDemo/Lib/UIKit+AFNetworking/UIWebView+AFNetworking.h: -------------------------------------------------------------------------------- 1 | // UIWebView+AFNetworking.h 2 | // Copyright (c) 2011–2015 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 | -------------------------------------------------------------------------------- /MVVMDemo/Lib/UIKit+AFNetworking/UIWebView+AFNetworking.m: -------------------------------------------------------------------------------- 1 | // UIWebView+AFNetworking.m 2 | // Copyright (c) 2011–2015 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 | *progress = [self.sessionManager downloadProgressForTask:dataTask]; 151 | [self.af_URLSessionTask resume]; 152 | 153 | if ([self.delegate respondsToSelector:@selector(webViewDidStartLoad:)]) { 154 | [self.delegate webViewDidStartLoad:self]; 155 | } 156 | } 157 | 158 | @end 159 | 160 | #endif -------------------------------------------------------------------------------- /MVVMDemo/Lib/YYModel/YYClassInfo.h: -------------------------------------------------------------------------------- 1 | // 2 | // YYClassInfo.h 3 | // YYModel 4 | // 5 | // Created by ibireme on 15/5/9. 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 | #import 14 | 15 | NS_ASSUME_NONNULL_BEGIN 16 | 17 | /** 18 | Type encoding's type. 19 | */ 20 | typedef NS_OPTIONS(NSUInteger, YYEncodingType) { 21 | YYEncodingTypeMask = 0xFF, ///< mask of type value 22 | YYEncodingTypeUnknown = 0, ///< unknown 23 | YYEncodingTypeVoid = 1, ///< void 24 | YYEncodingTypeBool = 2, ///< bool 25 | YYEncodingTypeInt8 = 3, ///< char / BOOL 26 | YYEncodingTypeUInt8 = 4, ///< unsigned char 27 | YYEncodingTypeInt16 = 5, ///< short 28 | YYEncodingTypeUInt16 = 6, ///< unsigned short 29 | YYEncodingTypeInt32 = 7, ///< int 30 | YYEncodingTypeUInt32 = 8, ///< unsigned int 31 | YYEncodingTypeInt64 = 9, ///< long long 32 | YYEncodingTypeUInt64 = 10, ///< unsigned long long 33 | YYEncodingTypeFloat = 11, ///< float 34 | YYEncodingTypeDouble = 12, ///< double 35 | YYEncodingTypeLongDouble = 13, ///< long double 36 | YYEncodingTypeObject = 14, ///< id 37 | YYEncodingTypeClass = 15, ///< Class 38 | YYEncodingTypeSEL = 16, ///< SEL 39 | YYEncodingTypeBlock = 17, ///< block 40 | YYEncodingTypePointer = 18, ///< void* 41 | YYEncodingTypeStruct = 19, ///< struct 42 | YYEncodingTypeUnion = 20, ///< union 43 | YYEncodingTypeCString = 21, ///< char* 44 | YYEncodingTypeCArray = 22, ///< char[10] (for example) 45 | 46 | YYEncodingTypeQualifierMask = 0xFF00, ///< mask of qualifier 47 | YYEncodingTypeQualifierConst = 1 << 8, ///< const 48 | YYEncodingTypeQualifierIn = 1 << 9, ///< in 49 | YYEncodingTypeQualifierInout = 1 << 10, ///< inout 50 | YYEncodingTypeQualifierOut = 1 << 11, ///< out 51 | YYEncodingTypeQualifierBycopy = 1 << 12, ///< bycopy 52 | YYEncodingTypeQualifierByref = 1 << 13, ///< byref 53 | YYEncodingTypeQualifierOneway = 1 << 14, ///< oneway 54 | 55 | YYEncodingTypePropertyMask = 0xFF0000, ///< mask of property 56 | YYEncodingTypePropertyReadonly = 1 << 16, ///< readonly 57 | YYEncodingTypePropertyCopy = 1 << 17, ///< copy 58 | YYEncodingTypePropertyRetain = 1 << 18, ///< retain 59 | YYEncodingTypePropertyNonatomic = 1 << 19, ///< nonatomic 60 | YYEncodingTypePropertyWeak = 1 << 20, ///< weak 61 | YYEncodingTypePropertyCustomGetter = 1 << 21, ///< getter= 62 | YYEncodingTypePropertyCustomSetter = 1 << 22, ///< setter= 63 | YYEncodingTypePropertyDynamic = 1 << 23, ///< @dynamic 64 | }; 65 | 66 | /** 67 | Get the type from a Type-Encoding string. 68 | 69 | @discussion See also: 70 | https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html 71 | https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtPropertyIntrospection.html 72 | 73 | @param typeEncoding A Type-Encoding string. 74 | @return The encoding type. 75 | */ 76 | YYEncodingType YYEncodingGetType(const char *typeEncoding); 77 | 78 | 79 | /** 80 | Instance variable information. 81 | */ 82 | @interface YYClassIvarInfo : NSObject 83 | @property (nonatomic, assign, readonly) Ivar ivar; ///< ivar opaque struct 84 | @property (nonatomic, strong, readonly) NSString *name; ///< Ivar's name 85 | @property (nonatomic, assign, readonly) ptrdiff_t offset; ///< Ivar's offset 86 | @property (nonatomic, strong, readonly) NSString *typeEncoding; ///< Ivar's type encoding 87 | @property (nonatomic, assign, readonly) YYEncodingType type; ///< Ivar's type 88 | 89 | /** 90 | Creates and returns an ivar info object. 91 | 92 | @param ivar ivar opaque struct 93 | @return A new object, or nil if an error occurs. 94 | */ 95 | - (instancetype)initWithIvar:(Ivar)ivar; 96 | @end 97 | 98 | 99 | /** 100 | Method information. 101 | */ 102 | @interface YYClassMethodInfo : NSObject 103 | @property (nonatomic, assign, readonly) Method method; ///< method opaque struct 104 | @property (nonatomic, strong, readonly) NSString *name; ///< method name 105 | @property (nonatomic, assign, readonly) SEL sel; ///< method's selector 106 | @property (nonatomic, assign, readonly) IMP imp; ///< method's implementation 107 | @property (nonatomic, strong, readonly) NSString *typeEncoding; ///< method's parameter and return types 108 | @property (nonatomic, strong, readonly) NSString *returnTypeEncoding; ///< return value's type 109 | @property (nullable, nonatomic, strong, readonly) NSArray *argumentTypeEncodings; ///< array of arguments' type 110 | 111 | /** 112 | Creates and returns a method info object. 113 | 114 | @param method method opaque struct 115 | @return A new object, or nil if an error occurs. 116 | */ 117 | - (instancetype)initWithMethod:(Method)method; 118 | @end 119 | 120 | 121 | /** 122 | Property information. 123 | */ 124 | @interface YYClassPropertyInfo : NSObject 125 | @property (nonatomic, assign, readonly) objc_property_t property; ///< property's opaque struct 126 | @property (nonatomic, strong, readonly) NSString *name; ///< property's name 127 | @property (nonatomic, assign, readonly) YYEncodingType type; ///< property's type 128 | @property (nonatomic, strong, readonly) NSString *typeEncoding; ///< property's encoding value 129 | @property (nonatomic, strong, readonly) NSString *ivarName; ///< property's ivar name 130 | @property (nullable, nonatomic, assign, readonly) Class cls; ///< may be nil 131 | @property (nullable, nonatomic, strong, readonly) NSArray *protocols; ///< may nil 132 | @property (nonatomic, assign, readonly) SEL getter; ///< getter (nonnull) 133 | @property (nonatomic, assign, readonly) SEL setter; ///< setter (nonnull) 134 | 135 | /** 136 | Creates and returns a property info object. 137 | 138 | @param property property opaque struct 139 | @return A new object, or nil if an error occurs. 140 | */ 141 | - (instancetype)initWithProperty:(objc_property_t)property; 142 | @end 143 | 144 | 145 | /** 146 | Class information for a class. 147 | */ 148 | @interface YYClassInfo : NSObject 149 | @property (nonatomic, assign, readonly) Class cls; ///< class object 150 | @property (nullable, nonatomic, assign, readonly) Class superCls; ///< super class object 151 | @property (nullable, nonatomic, assign, readonly) Class metaCls; ///< class's meta class object 152 | @property (nonatomic, readonly) BOOL isMeta; ///< whether this class is meta class 153 | @property (nonatomic, strong, readonly) NSString *name; ///< class name 154 | @property (nullable, nonatomic, strong, readonly) YYClassInfo *superClassInfo; ///< super class's class info 155 | @property (nullable, nonatomic, strong, readonly) NSDictionary *ivarInfos; ///< ivars 156 | @property (nullable, nonatomic, strong, readonly) NSDictionary *methodInfos; ///< methods 157 | @property (nullable, nonatomic, strong, readonly) NSDictionary *propertyInfos; ///< properties 158 | 159 | /** 160 | If the class is changed (for example: you add a method to this class with 161 | 'class_addMethod()'), you should call this method to refresh the class info cache. 162 | 163 | After called this method, `needUpdate` will returns `YES`, and you should call 164 | 'classInfoWithClass' or 'classInfoWithClassName' to get the updated class info. 165 | */ 166 | - (void)setNeedUpdate; 167 | 168 | /** 169 | If this method returns `YES`, you should stop using this instance and call 170 | `classInfoWithClass` or `classInfoWithClassName` to get the updated class info. 171 | 172 | @return Whether this class info need update. 173 | */ 174 | - (BOOL)needUpdate; 175 | 176 | /** 177 | Get the class info of a specified Class. 178 | 179 | @discussion This method will cache the class info and super-class info 180 | at the first access to the Class. This method is thread-safe. 181 | 182 | @param cls A class. 183 | @return A class info, or nil if an error occurs. 184 | */ 185 | + (nullable instancetype)classInfoWithClass:(Class)cls; 186 | 187 | /** 188 | Get the class info of a specified Class. 189 | 190 | @discussion This method will cache the class info and super-class info 191 | at the first access to the Class. This method is thread-safe. 192 | 193 | @param className A class name. 194 | @return A class info, or nil if an error occurs. 195 | */ 196 | + (nullable instancetype)classInfoWithClassName:(NSString *)className; 197 | 198 | @end 199 | 200 | NS_ASSUME_NONNULL_END 201 | -------------------------------------------------------------------------------- /MVVMDemo/Lib/YYModel/YYModel.h: -------------------------------------------------------------------------------- 1 | // 2 | // YYModel.h 3 | // YYModel 4 | // 5 | // Created by ibireme on 15/5/10. 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 YYModelVersionNumber; 16 | FOUNDATION_EXPORT const unsigned char YYModelVersionString[]; 17 | #import 18 | #import 19 | #else 20 | #import "NSObject+YYModel.h" 21 | #import "YYClassInfo.h" 22 | #endif 23 | -------------------------------------------------------------------------------- /MVVMDemo/Project/Controller/DetailViewController.h: -------------------------------------------------------------------------------- 1 | 2 | 3 | #import 4 | 5 | @interface DetailViewController : UIViewController 6 | 7 | /** <#type#> */ 8 | @property (nonatomic, strong) NSString *labelText; 9 | 10 | /** <#type#> */ 11 | @property (nonatomic, strong) NSString *shopId; 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /MVVMDemo/Project/Controller/DetailViewController.m: -------------------------------------------------------------------------------- 1 | 2 | 3 | #import "DetailViewController.h" 4 | #import "DetailModel.h" 5 | #import "YYModel.h" 6 | @interface DetailViewController () 7 | 8 | @end 9 | 10 | @implementation DetailViewController 11 | 12 | - (void)viewDidLoad { 13 | [super viewDidLoad]; 14 | 15 | self.view.backgroundColor = [UIColor whiteColor]; 16 | 17 | UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 300)]; 18 | label.text = _labelText; 19 | label.textAlignment = NSTextAlignmentCenter; 20 | label.font = [UIFont systemFontOfSize:20]; 21 | [self.view addSubview:label]; 22 | 23 | } 24 | 25 | 26 | @end 27 | -------------------------------------------------------------------------------- /MVVMDemo/Project/Controller/ViewController.h: -------------------------------------------------------------------------------- 1 | 2 | 3 | #import 4 | 5 | @interface ViewController : UIViewController 6 | 7 | 8 | @end 9 | 10 | -------------------------------------------------------------------------------- /MVVMDemo/Project/Controller/ViewController.m: -------------------------------------------------------------------------------- 1 | 2 | 3 | #import "ViewController.h" 4 | 5 | #import "ViewModelClass.h" 6 | #import "HomeVM.h" 7 | #import "HeaderView.h" 8 | #import "DetailViewController.h" 9 | 10 | #define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width 11 | 12 | @interface ViewController () 13 | /** tableView初始化 */ 14 | @property (nonatomic, strong) UITableView *tableView; 15 | /** 总数据源 */ 16 | @property (nonatomic, strong) NSMutableArray *dataArray; 17 | /** 列表数据 */ 18 | @property (nonatomic, strong) NSMutableArray *listArray; 19 | /** 分类数据 */ 20 | @property (nonatomic, strong) NSMutableArray *categoryArray; 21 | @end 22 | 23 | @implementation ViewController 24 | 25 | - (void)viewDidLoad { 26 | [super viewDidLoad]; 27 | 28 | self.view.backgroundColor = [UIColor whiteColor]; 29 | 30 | self.navigationItem.title = @"MVVMDemo"; 31 | 32 | _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:(UITableViewStyleGrouped)]; 33 | _tableView.dataSource = self; 34 | _tableView.delegate = self; 35 | [self.view addSubview:_tableView]; 36 | 37 | _dataArray = [NSMutableArray array]; 38 | _listArray = [NSMutableArray array]; 39 | _categoryArray = [NSMutableArray array]; 40 | 41 | HomeVM *model = [[HomeVM alloc]init]; 42 | 43 | HeaderView *headerView = [[HeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,SCREEN_WIDTH * 0.17*2+30)]; 44 | 45 | self.tableView.tableHeaderView = headerView; 46 | 47 | DetailViewController *detail = [[DetailViewController alloc]init]; 48 | 49 | __weak __typeof(&*self)weakSelf = self; 50 | 51 | [headerView setBlock:^(NSString *shopId) { 52 | NSLog(@"%@",shopId); 53 | detail.labelText = shopId; 54 | [weakSelf.navigationController pushViewController:detail animated:YES]; 55 | }]; 56 | 57 | [model setBlockWithReturnBlock:^(id returnValue) { 58 | 59 | _dataArray = returnValue; 60 | _listArray = returnValue[@"picList"]; 61 | _categoryArray = returnValue[@"category_new"]; 62 | 63 | [headerView headerViewWithData:_categoryArray]; 64 | 65 | [self.tableView reloadData]; 66 | 67 | } WithErrorBlock:^(id errorCode) { 68 | 69 | NSLog(@"%@",errorCode); 70 | 71 | }]; 72 | 73 | [model fetchShopList]; 74 | 75 | } 76 | 77 | #pragma mark - 返回TableViewCell个数 78 | - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ 79 | return _listArray.count; 80 | } 81 | #pragma mark - 创建TableViewCell 82 | - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 83 | static NSString *cellID = @"cellID"; 84 | UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID]; 85 | if (cell == nil) { 86 | //是用代码创建的Cell 87 | cell = [[UITableViewCell alloc]initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:cellID]; 88 | } 89 | cell.textLabel.text = _listArray[indexPath.row][@"title"]; 90 | return cell; 91 | } 92 | 93 | -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 94 | { 95 | HomeVM *model = [[HomeVM alloc]init]; 96 | [model shopListDetailWithVC:self didSelectRowAtDic:_listArray[indexPath.row]]; 97 | } 98 | 99 | 100 | @end 101 | -------------------------------------------------------------------------------- /MVVMDemo/Project/ViewModel/DetailModel/DetailModel.h: -------------------------------------------------------------------------------- 1 | 2 | 3 | #import 4 | @class ShopInfo; 5 | @interface DetailModel : NSObject 6 | 7 | /** 店铺信息 */ 8 | @property (nonatomic, strong) ShopInfo *shopInfo; 9 | /** 分享链接 */ 10 | @property (nonatomic, strong) NSString *shareLink; 11 | 12 | @end 13 | 14 | @interface ShopInfo : NSObject 15 | 16 | /** <#type#> */ 17 | @property (nonatomic, strong) NSString *banner; 18 | /** <#type#> */ 19 | @property (nonatomic, strong) NSString *shop_name; 20 | 21 | @end 22 | -------------------------------------------------------------------------------- /MVVMDemo/Project/ViewModel/DetailModel/DetailModel.m: -------------------------------------------------------------------------------- 1 | 2 | #import "DetailModel.h" 3 | 4 | @implementation DetailModel 5 | + (NSDictionary *)modelContainerPropertyGenericClass { 6 | return @{@"shopInfo": @"ShopInfo", 7 | }; 8 | } 9 | 10 | @end 11 | 12 | @implementation ShopInfo 13 | 14 | @end 15 | -------------------------------------------------------------------------------- /MVVMDemo/Project/ViewModel/DetailViewModel/TopView.h: -------------------------------------------------------------------------------- 1 | 2 | 3 | #import 4 | #import 5 | @interface TopView : NSObject 6 | 7 | - (UIView *)topViewWith:(id)data; 8 | 9 | @end 10 | -------------------------------------------------------------------------------- /MVVMDemo/Project/ViewModel/DetailViewModel/TopView.m: -------------------------------------------------------------------------------- 1 | 2 | 3 | #import "TopView.h" 4 | #import "UIKit+AFNetworking.h" 5 | 6 | #define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width 7 | 8 | @implementation TopView{ 9 | UIView *topView; 10 | } 11 | 12 | - (UIView *)topViewWith:(id)data{ 13 | topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH)]; 14 | // UIImageView *topImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH)]; 15 | // [topImage setImageWithURL:data[@"banner"]]; 16 | // [topView addSubview:topImage]; 17 | 18 | topView.backgroundColor = [UIColor redColor]; 19 | 20 | return topView; 21 | } 22 | @end 23 | -------------------------------------------------------------------------------- /MVVMDemo/Project/ViewModel/HomeViewModel/HeaderView.h: -------------------------------------------------------------------------------- 1 | 2 | 3 | #import 4 | #import 5 | #import "ViewModelClass.h" 6 | 7 | typedef void(^HeaderViewBlock)(NSString *shopId); 8 | 9 | @interface HeaderView : UIView 10 | 11 | @property (nonatomic, copy) HeaderViewBlock block; 12 | 13 | 14 | // headerView中的数据 15 | - (void)headerViewWithData:(id)data; 16 | 17 | - (void)setBlock:(HeaderViewBlock)block; 18 | 19 | 20 | @end 21 | -------------------------------------------------------------------------------- /MVVMDemo/Project/ViewModel/HomeViewModel/HeaderView.m: -------------------------------------------------------------------------------- 1 | 2 | 3 | #import "HeaderView.h" 4 | #import "UIKit+AFNetworking.h" 5 | 6 | #define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width 7 | 8 | @implementation HeaderView{ 9 | UIImageView *topImage; 10 | NSMutableArray *dataArray; 11 | UIButton *button; 12 | } 13 | 14 | - (void)headerViewWithData:(id)data{ 15 | dataArray = data; 16 | 17 | CGFloat btnWidth = SCREEN_WIDTH * 0.17; 18 | CGFloat btnHeight = SCREEN_WIDTH * 0.17; 19 | CGFloat margin=(SCREEN_WIDTH-5*btnWidth)/6; 20 | 21 | for (int i = 0; i 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 | -------------------------------------------------------------------------------- /MVVMDemoTests/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 | CFBundleVersion 20 | 1 21 | 22 | 23 | -------------------------------------------------------------------------------- /MVVMDemoTests/MVVMDemoTests.m: -------------------------------------------------------------------------------- 1 | // 2 | // MVVMDemoTests.m 3 | // MVVMDemoTests 4 | // 5 | // Created by 郭洪安 on 2016/11/15. 6 | // Copyright © 2016年 ShunLian. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface MVVMDemoTests : XCTestCase 12 | 13 | @end 14 | 15 | @implementation MVVMDemoTests 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 | -------------------------------------------------------------------------------- /MVVMDemoUITests/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 | CFBundleVersion 20 | 1 21 | 22 | 23 | -------------------------------------------------------------------------------- /MVVMDemoUITests/MVVMDemoUITests.m: -------------------------------------------------------------------------------- 1 | // 2 | // MVVMDemoUITests.m 3 | // MVVMDemoUITests 4 | // 5 | // Created by 郭洪安 on 2016/11/15. 6 | // Copyright © 2016年 ShunLian. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface MVVMDemoUITests : XCTestCase 12 | 13 | @end 14 | 15 | @implementation MVVMDemoUITests 16 | 17 | - (void)setUp { 18 | [super setUp]; 19 | 20 | // Put setup code here. This method is called before the invocation of each test method in the class. 21 | 22 | // In UI tests it is usually best to stop immediately when a failure occurs. 23 | self.continueAfterFailure = NO; 24 | // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. 25 | [[[XCUIApplication alloc] init] launch]; 26 | 27 | // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. 28 | } 29 | 30 | - (void)tearDown { 31 | // Put teardown code here. This method is called after the invocation of each test method in the class. 32 | [super tearDown]; 33 | } 34 | 35 | - (void)testExample { 36 | // Use recording to get started writing UI tests. 37 | // Use XCTAssert and related functions to verify your tests produce the correct results. 38 | } 39 | 40 | @end 41 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MVVMDemo 2 | # 我对iOS开发中使用MVVM的理解(初级) 3 | ![运行](https://github.com/RabbitBell/MVVMDemo/raw/master/运行.PNG) 4 | ## 前言 5 | 之前几个月一直在学习react-native,它的组件化开发真的是很棒,控件和页面的组件化在开发中可以很好的复用,节省开发时间。那个时候还不知道react-native开发用到的就是MVVM设计模式。 6 | 前几天,UI给了新的需求,需要添加几个页面(之前的项目一直使用MVC开发的),在给这几个新页面添加入口的时候,感觉之前写的代码真的是好恶心😱😱😱,就在网上搜了搜MVP和MVVM,发现MVVM和我在写RN时的写法很像。就研究了一下,然后写下了这篇文章。(可能会有很多问题,欢迎评论) 7 | ps:这篇文章实用为主,那些理论性的东西,我都没有研究。 8 | 俗话说得好:黑猫白猫,能用在项目中的就是好🐱 9 | ## 使用 10 | MVVM顾名思义,那就是Model,View,ViewModel,所以我们需要创建这些类了。 11 | 12 | ![项目目录](https://github.com/RabbitBell/MVVMDemo/raw/master/项目目录.png) 13 | 14 | 接下来就把我的理解说说。 15 | ### ViewModelClass 16 | ![ViewModelClass](https://github.com/RabbitBell/MVVMDemo/raw/master/ViewModelClass.png) 17 | `ViewModelClass.h`中 18 | 19 | ``` 20 | #import 21 | #import 22 | 23 | //定义返回请求数据的block类型 24 | typedef void (^ReturnValueBlock) (id returnValue); 25 | typedef void (^ErrorCodeBlock) (id errorCode); 26 | 27 | @interface ViewModelClass : NSObject 28 | 29 | @property (strong, nonatomic) ReturnValueBlock returnBlock; 30 | @property (strong, nonatomic) ErrorCodeBlock errorBlock; 31 | 32 | // 传入交互的Block块 33 | -(void) setBlockWithReturnBlock: (ReturnValueBlock) returnBlock 34 | WithErrorBlock: (ErrorCodeBlock) errorBlock; 35 | @end 36 | ``` 37 | `ViewModelClass.m` 38 | 39 | ``` 40 | #import "ViewModelClass.h" 41 | #import "RTNetworking.h" 42 | 43 | @implementation ViewModelClass 44 | 45 | #pragma 接收传过来的block 46 | -(void) setBlockWithReturnBlock: (ReturnValueBlock) returnBlock 47 | WithErrorBlock: (ErrorCodeBlock) errorBlock 48 | { 49 | _returnBlock = returnBlock; 50 | _errorBlock = errorBlock; 51 | } 52 | @end 53 | ``` 54 | 上面的两个类放着的就是ViewModel的基类,用下面的方法承接之后继承于这个基类的VM中的回调数据。 55 | 56 | ``` 57 | - (void)setBlockWithReturnBlock: (ReturnValueBlock) returnBlock 58 | WithErrorBlock: (ErrorCodeBlock) errorBlock; 59 | ``` 60 | ### ViewController 61 | 我之前的项目用的MVC设计模式,C指的就是这个ViewController了,之前写的垃圾代码,一个Controller里面最多放过1000多行代码,现在去找个方法需要N久。但虽然这是个简单的例子,但其实并不简单。 62 | `ViewController.m` 63 | 64 | 65 | ``` 66 | // 初始化HeaderVM 67 | HeaderVM *headerView = [[HeaderVM alloc] init]; 68 | // 初始化HomeVM 69 | HomeVM *model = [[HomeVM alloc]init]; 70 | // 调用ViewModelClass基类的方法,来获取数据 71 | [model setBlockWithReturnBlock:^(id returnValue) { 72 | 73 | _dataArray = returnValue; 74 | _listArray = returnValue[@"picList"]; 75 | _categoryArray = returnValue[@"category_new"]; 76 | 77 | UIView *view = [headerView headerViewWithData:_categoryArray]; 78 | self.tableView.tableHeaderView = view; 79 | 80 | [self.tableView reloadData]; 81 | 82 | } WithErrorBlock:^(id errorCode) { 83 | 84 | NSLog(@"%@",errorCode); 85 | 86 | }]; 87 | 88 | ``` 89 | 上面的代码虽短,但最重要的东西都在里面,通过Block回调,将需要的数据在VM页面回传了回来。具体内容可以在Demo 90 | 91 | ### HomeVM 92 | ![HomeVM](https://github.com/RabbitBell/MVVMDemo/raw/master/HomeVM.png) 93 | `HomeVM.h` 94 | 95 | ``` 96 | #import "ViewModelClass.h" 97 | 98 | @interface HomeVM : ViewModelClass 99 | 100 | // 获取商品列表 101 | - (void)fetchShopList; 102 | // 跳转到商品详情页 103 | - (void)shopListDetailWithVC:(UIViewController *)vc didSelectRowAtDic:(NSDictionary *)dic; 104 | 105 | @end 106 | ``` 107 | `HomeVM.m` 108 | 109 | ``` 110 | #import "HomeVM.h" 111 | #import "RTNetworking.h" 112 | #import "DetailViewController.h" 113 | 114 | @implementation HomeVM 115 | 116 | - (void)fetchShopList{ 117 | [RTNetworking getWithUrl:@"/v1/Home/all.json" refreshCache:NO success:^(id response) { 118 | [self loadDataWithSuccessDic:response]; 119 | } fail:^(NSError *error) { 120 | self.errorBlock(error); 121 | }]; 122 | } 123 | - (void)loadDataWithSuccessDic:(NSDictionary *)dic{ 124 | NSMutableArray *arr = dic[@"data"]; 125 | self.returnBlock(arr); 126 | } 127 | - (void)shopListDetailWithVC:(UIViewController *)vc didSelectRowAtDic:(NSDictionary *)dic{ 128 | DetailViewController *view = [[DetailViewController alloc]init]; 129 | view.labelText = dic[@"title"]; 130 | [vc.navigationController pushViewController:view animated:YES]; 131 | } 132 | @end 133 | ``` 134 | 135 | 可以明显看出`HomeVM`是继承于`ViewModelClass`,在这个VM中,将Push到新页面的方法也写在了里面。 136 | 137 | ### HeaderVM 138 | 这个是一个tableView的headerView。 139 | ![HeaderV](https://github.com/RabbitBell/MVVMDemo/raw/master/HeaderView.png) 140 | 141 | `HeaderView.h` 142 | 143 | 144 | ``` 145 | #import 146 | #import 147 | #import "ViewModelClass.h" 148 | 149 | @interface HeaderView : ViewModelClass 150 | 151 | // headerView中的数据 152 | - (UIView *)headerViewWithData:(id)data; 153 | 154 | // headerView中的按钮的点击事件 155 | - (void)headerViewDidSeletced:(UIViewController *)vc indexPath:(NSString *)string; 156 | 157 | @end 158 | ``` 159 | `HeaderView.m` 160 | 161 | ``` 162 | #import "HeaderView.h" 163 | #import "UIKit+AFNetworking.h" 164 | #import "DetailViewController.h" 165 | 166 | #define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width 167 | 168 | @implementation HeaderView{ 169 | UIImageView *topImage; 170 | NSMutableArray *dataArray; 171 | UIButton *button; 172 | } 173 | 174 | - (UIView *)headerViewWithData:(id)data{ 175 | dataArray = data; 176 | UIView * view=[[UIView alloc]initWithFrame:CGRectMake(0, 0,SCREEN_WIDTH,SCREEN_WIDTH/5*2)]; 177 | view.userInteractionEnabled = YES; 178 | 179 | CGFloat btnWidth = SCREEN_WIDTH/5; 180 | CGFloat btnHeight = SCREEN_WIDTH/5; 181 | CGFloat margin=(SCREEN_WIDTH-5*btnWidth)/6; 182 | 183 | for (int i = 0; i