iOS 處理緩衝的三種方法

來源:互聯網
上載者:User

標籤: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 處理緩衝的三種方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.