// // Remote.m // codeChallengeDemo // // Created by Scar on 14-8-21. // Copyright (c) 2014年 scar1900. All rights reserved. // #import "Remote.h" #import "AppDelegate.h" #import "Reachability.h" @interface Remote() @property(nonatomic, strong)UIView *waitBackView; @property(nonatomic, strong)MBProgressHUD *hud; @end static Remote* g_remoteInstance; @implementation Remote @synthesize remoteQueue; @synthesize sessionTaskList = _sessionTaskList; + (Remote *)instance { @synchronized(self) { if (nil == g_remoteInstance) { g_remoteInstance = [[Remote alloc] init]; //设置网络超时时间 [ASIHTTPRequest setDefaultTimeOutSeconds:15]; } } return g_remoteInstance; } + (NSURLSession *)session { static NSURLSession *session = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ BOOL ios8 = isIOS8; if (!ios8) { NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:@"cn.thepaper.paper"]; [configuration setHTTPMaximumConnectionsPerHost:5]; [configuration setSessionSendsLaunchEvents:YES]; [configuration setDiscretionary:YES]; session = [NSURLSession sessionWithConfiguration:configuration delegate:[Remote instance] delegateQueue:nil]; }else { NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"cn.thepaper.paper"]; [configuration setHTTPMaximumConnectionsPerHost:5]; [configuration setSessionSendsLaunchEvents:YES]; [configuration setDiscretionary:YES]; session = [NSURLSession sessionWithConfiguration:configuration delegate:[Remote instance] delegateQueue:nil]; } }); return session; } + (BOOL) IsEnable3G { return ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable); } + (BOOL) IsEnableWIFI { return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable); } + (void)resetRemoteQueue{ [[Remote instance] resetQue]; } + (void)pauseQueue { [[Remote instance] clearRequestInQueue]; } +(BOOL)IsEableNetwork { return [[Remote instance] connectedToNetwork]; } - (BOOL) connectedToNetwork { // 创建零地址,0.0.0.0地址表示查询本机的网络连接状态 struct sockaddr_in zeroAddress; bzero(&zeroAddress, sizeof(zeroAddress)); zeroAddress.sin_len = sizeof(zeroAddress); zeroAddress.sin_family = AF_INET; // Recover reachability flags SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress); SCNetworkReachabilityFlags flags; // Get connect flags BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags); CFRelease(defaultRouteReachability); // 如果不能获取连接标志,则不能连接网络,直接返回 if (!didRetrieveFlags) { return NO; } // 根据获得的连接标志进行判断 BOOL isReachable = flags & kSCNetworkFlagsReachable; BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired; return (isReachable && !needsConnection) ? YES : NO; } - (NSMutableArray*)sessionTaskList { if (!_sessionTaskList) { _sessionTaskList = [NSMutableArray array]; } return _sessionTaskList; } - (void)clearRequestInQueue { [self.remoteQueue.operations enumerateObjectsUsingBlock:^(ASIHTTPRequest* obj, NSUInteger idx, BOOL *stop) { [obj clearDelegatesAndCancel]; }]; } - (void)resetQue { self.remoteQueue = [[ASINetworkQueue alloc]init]; [self.remoteQueue reset]; [self.remoteQueue setDelegate:self]; [self.remoteQueue setQueueDidFinishSelector:@selector(queDidFinish)]; [self.remoteQueue setShowAccurateProgress:YES]; [self.remoteQueue setMaxConcurrentOperationCount:5]; [self.remoteQueue go]; } + (void)pauseUrlSessionURLDownload { [[Remote instance] pauseSessionTask]; } - (void)pauseSessionTask { NSMutableDictionary *pauseDic = [NSMutableDictionary dictionaryWithDictionary:[TPUserDefault instance].pauseDataDic]; [self.sessionTaskList enumerateObjectsUsingBlock:^(NSMutableDictionary *obj, NSUInteger idx, BOOL *stop) { id task = obj[@"task"]; if ([task isKindOfClass:[NSURLSessionDownloadTask class]]) { NSURLSessionDownloadTask* downLoadTask = task; [downLoadTask cancelByProducingResumeData:^(NSData *resumeData) { NSData *partialData = resumeData; [obj setValue:partialData forKey:@"partialData"]; [obj setValue:nil forKey:@"task"]; [obj setValue:@"0" forKey:@"finish"]; NSString *actionTag = obj[@"actionTag"]; if (resumeData && resumeData.length > 0) { NSLog(@"===********%@******======",actionTag); [pauseDic setValue:partialData forKey:[NSString stringWithFormat:@"%@",actionTag]]; [TPUserDefault instance].pauseDataDic = [NSMutableDictionary dictionaryWithDictionary:pauseDic]; } }]; } }]; } + (BOOL)clearPartialDataCache { return [[Remote instance] clearPartialDataCache]; } - (BOOL)clearPartialDataCache{ __block BOOL isHavePartial = NO; [self.sessionTaskList enumerateObjectsUsingBlock:^(NSMutableDictionary *obj, NSUInteger idx, BOOL *stop) { id task = obj[@"task"]; if (obj[@"partialData"]) { isHavePartial = YES; [obj setValue:nil forKey:@"partialData"]; } if ([task isKindOfClass:[NSURLSessionDownloadTask class]]) { NSURLSessionDownloadTask* downLoadTask = task; [downLoadTask cancel]; [obj setValue:@"0" forKey:@"finish"]; [obj setValue:nil forKey:@"task"]; } }]; return isHavePartial; } - (UIView*)waitBackView { if (!_waitBackView) { AppDelegate *delegate=(AppDelegate*)[[UIApplication sharedApplication]delegate]; _waitBackView = [[UIView alloc]initWithFrame:[delegate window].bounds]; _waitBackView.backgroundColor = [UIColor clearColor]; _waitBackView.userInteractionEnabled = NO; [_waitBackView addSubview:self.waitCursor]; } return _waitBackView; } - (SCGIFImageView*)waitCursor { if (!_waitCursor) { NSString *filePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingFormat:@"/%@", Bundle(@"frontPage/loading.gif")]; NSData* imageData = [NSData dataWithContentsOfFile:filePath]; _waitCursor = [[SCGIFImageView alloc]initWithFrame:CGRectMake(CGRectGetWidth(self.waitBackView.bounds)/2-25/2, (CGRectGetHeight(self.waitBackView.bounds))/2-25/2, 25, 25)]; _waitCursor.animating = YES; [_waitCursor setData:imageData]; _waitCursor.hidden = NO; } return _waitCursor; } - (void) startWaitCursor:(NSDictionary*)userInfo { id delegate = userInfo[@"delegate"]; if ([delegate conformsToProtocol:@protocol(RemoteDelegate)] && [delegate respondsToSelector:@selector(startWaitCursor:)]) { [delegate startWaitCursor:[userInfo[@"actionTag"] intValue]]; }else { if (!self.hud) { self.hud = [MBProgressHUD showHUDAddedTo:KEY_WINDOW animated:YES]; self.hud.mode = MBProgressHUDModeIndeterminate; self.hud.userInteractionEnabled = YES; self.hud.dimBackground = NO; UIColor *hudColor = [UIColor colorWithRed:76.5f/255.f green:76.5f/255.f blue:76.5f/255.f alpha:0.9f]; self.hud.color = hudColor; self.hud.cornerRadius = 4; self.hud.removeFromSuperViewOnHide = YES; } } } - (void) stopWaitCursor:(NSDictionary*)userInfo { id delegate = userInfo[@"delegate"]; if ([delegate conformsToProtocol:@protocol(RemoteDelegate)] && [delegate respondsToSelector:@selector(stopWaitCursor:)]) { [delegate stopWaitCursor:[userInfo[@"actionTag"] intValue]]; }else { if (self.hud) { [self.hud hide:YES]; self.hud = nil; } } } - (void)onError:(NSString*)message userInfo:(NSDictionary*)userInfo{ id delegate = userInfo[@"delegate"]; int actionTag = [userInfo[@"actionTag"] intValue]; void(^completeHandler)(BOOL success,NSString *message,id responseData); completeHandler = [userInfo objectForKey:@"completeHandler"]; if (delegate) { if ([delegate conformsToProtocol:@protocol(RemoteDelegate)] && [delegate respondsToSelector:@selector(remoteResponsFailed:withMessage:resultCode:)]) { [delegate remoteResponsFailed:actionTag withMessage:message resultCode:@""]; } } if (self.downloadFinishHanlder) { self.downloadFinishHanlder(NO,message,nil); self.downloadFinishHanlder = nil; } if (completeHandler) { completeHandler(NO,message,nil); completeHandler = nil; } } - (void)onNsError:(NSError*)error userInfo:(NSDictionary*)userInfo{ id delegate = userInfo[@"delegate"]; int actionTag = [userInfo[@"actionTag"] intValue]; void(^completeHandler)(BOOL success,NSString *message,id responseData); completeHandler = [userInfo objectForKey:@"completeHandler"]; if (delegate) { if ([delegate conformsToProtocol:@protocol(RemoteDelegate)] && [delegate respondsToSelector:@selector(remoteResponsFailed:withMessage:resultCode:)]) { [delegate remoteResponsFailed:actionTag withMessage:[error localizedDescription] resultCode:[NSString stringWithFormat:@"%ld",(long)[error code]]]; } } if (self.downloadFinishHanlder) { self.downloadFinishHanlder(NO,[error localizedDescription],nil); self.downloadFinishHanlder = nil; } if (completeHandler) { completeHandler(NO,[error localizedDescription],nil); completeHandler = nil; } } -(BOOL) copyTempFileAtURL:(NSURL *)location toDestination:(NSURL *)destination { NSError *error; NSFileManager *fileManager = [NSFileManager defaultManager]; [fileManager removeItemAtURL:destination error:NULL]; [fileManager copyItemAtURL:location toURL:destination error:&error]; if (error == nil) { return true; }else{ NSLog(@"%@",error); return false; } } @end