標籤:des style blog http io ar color os 使用
緩衝處理是個相當頭疼的事情,要根據需要綜合應用不同的策略。總的來說有以下幾種情況:
1.URL緩衝,例如社交應用的文章瀏覽,要在viewDidAppear:裡面進行URL緩衝。簡單來說就是用NSURLCache類,首先在AppDelegate.m裡面的
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;方法裡面建立一個NSURLCache的單例:
//設定記憶體緩衝大小
NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024 diskCapacity:10 * 1024 * 1024 diskPath:nil];
[NSURLCache setSharedURLCache:URLCache];
然後的ViewController.m裡面實現方法:
//網路緩衝回應程式法
- (IBAction)senderButton:(id)sender { //天氣Api介面 NSString* path = @"http://www.weather.com.cn/data/sk/101110101.html"; [self getByURL:path andCallBack:^(id obj) { NSString *str = [[NSString alloc]initWithData:obj encoding:NSUTF8StringEncoding]; NSLog(@"=========================================================\n"); NSLog(@"post緩衝測試:%@",str); NSLog(@"=========================================================\n"); }];
}
//網路請求的記憶體緩衝方法
-(void)getByURL:(NSString *)path andCallBack:(CallBack)callback{ NSString* pathStr = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString:pathStr]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setCachePolicy:NSURLRequestReloadRevalidatingCacheData]; NSCachedURLResponse* response = [[NSURLCache sharedURLCache] cachedResponseForRequest:request]; //判斷是否有緩衝 if (response != nil) { NSLog(@"有緩衝"); [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; }else{ NSLog(@"沒有緩衝"); } //建立NSURLConnection NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; callback(data); }
2.檔案快取,例如使用者資訊等基本不會變化的資訊儲存在本地沙箱
//使用者資訊緩衝用檔案儲存在沙箱
- (IBAction)userCache:(UIButton *)sender { self.UserPath = [self saveFileToDocuments:@"http://www.weather.com.cn/data/sk/101020100.html"];}
//儲存檔案到沙箱- (NSString *)saveFileToDocuments:(NSString *)url{ NSString *resultFilePath = @""; NSString *destFilePath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:url]; // 加上url,組合成本地檔案PATH NSString *destFolderPath = [destFilePath stringByDeletingLastPathComponent]; // 判斷路徑檔案夾是否存在不存在則建立 if (! [[NSFileManager defaultManager] fileExistsAtPath:destFolderPath]) { NSLog(@"檔案夾不存在,建立檔案夾"); [[NSFileManager defaultManager] createDirectoryAtPath:destFolderPath withIntermediateDirectories:YES attributes:nil error:nil]; } // 判斷該檔案是否已經下載過 if ([[NSFileManager defaultManager] fileExistsAtPath:destFilePath]) { NSLog(@"檔案已下載\n"); resultFilePath = destFilePath; } else { NSLog(@"沒有緩衝,請求資料\n"); NSData *userInfoData = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]]; if ([userInfoData writeToFile:destFilePath atomically:YES]) { resultFilePath = destFilePath; } } NSData *userInfoData=[[NSFileManager defaultManager] contentsAtPath:resultFilePath]; NSString* str = [[NSString alloc]initWithData:userInfoData encoding:NSUTF8StringEncoding]; NSLog(@"=========================================================\n"); NSLog(@"user:%@",str); NSLog(@"=========================================================\n"); return resultFilePath;}
3.圖片緩衝是最重要的,費流量還佔記憶體,所以推薦使用第三方SDWebImage
最簡單的就是用這個方法:
[self.imageView sd_setImageWithURL:url completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { if (cacheType==SDImageCacheTypeNone) { NSLog(@"沒有緩衝,從網路下載"); }else if (cacheType==SDImageCacheTypeDisk){ NSLog(@"有緩衝,從磁碟讀取"); }else{ NSLog(@"有緩衝,從記憶體讀取"); } }];
想知道這個方法的內部機制請看這裡。
想要demo的去這裡下載。
轉載請註明出處!
iOS 處理緩衝的三種方法