2012-02-16 12 views
0

私のnsurlrequestデータをキャッシュしようとしています。それ以前は、サーバーからデータを正常にダウンロードしていましたが、このキャッシュを実装しようとして以来、アプリケーションのフォールオーバーを行っていました。誰かが私がこれまでに持っているコードを見て、それをworkigに手伝ってくれることを期待しています。私は、およそ95%が完了したと思います。キャッシュが機能していないNSURLRequest

- (IBAction)setRequestString:(NSString *)string 
{ 
    //Set database address 
    NSMutableString *databaseURL = [[NSMutableString alloc] initWithString:@"http://127.0.0.1:29/"]; // imac development 


    //PHP file name is being set from the parent view 
    [databaseURL appendString:string]; 

    //call ASIHTTP delegates (Used to connect to database) 
    NSURL *url = [NSURL URLWithString:databaseURL]; 

    //SynchronousRequest to grab the data, also setting up the cachePolicy 
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60.0]; //if request dose not finish happen within 60 second timeout. 

    //This nsdata will be used to put the cache into 
    NSData *cacheData = [[NSData alloc] init]; 
    //Create my own NSCachedURLResponse and add it to the cache 
    NSURLResponse *responseToCache = [[NSURLResponse alloc] initWithURL:url MIMEType:@"text/xml" expectedContentLength:[cacheData length] textEncodingName:nil]; 
    //Set up the cache 
    NSCachedURLResponse *cacheResponse = [[NSCachedURLResponse alloc] initWithResponse:responseToCache data:cacheData]; 
    [[NSURLCache sharedURLCache] storeCachedResponse:cacheResponse forRequest:request]; 

    //check if its really there 
    NSLog(@"cache = %@", [[NSURLCache sharedURLCache] cachedResponseForRequest:request]); 


    //If no cache do this stuff, connect to the db and perform these actions. I think this is what i am supposed to be doing. 
    NSOperationQueue *queue = [[NSOperationQueue alloc] init]; 
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) 
    { 
     if ([data length] > 0 && error == nil){ 
      [self receivedData:data]; 
     }else if ([data length] == 0 && error == nil){ 
      [self emptyReply]; 
     }else if (error != nil && error.code == NSURLErrorTimedOut){ 
      [self timedOut]; 
     }else if (error != nil){ 
      [self downloadError:error]; 
     } 
    }]; 
} 

答えて

-3

Follow this link NSURLConnectionのカテゴリのメソッドを使用してこれを行うの死者簡単な方法のために。これは非同期要求に対してですが、同期要求に対しては容易に適用できます。

また、すべての要求が同じ操作キューを使用するように、NSOperationQueueにプライベートプロパティまたはインスタンス変数を使用することを強くお勧めします。

+5

リンクを含むアンサーは[悪い習慣とみなされます](http://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-answers)。答えがそれ自身の上に立つことができるように、ここに内容を要約してください(コピー/貼り付けはしないでください)。あなたがしない場合は、特にリンクが死ぬ場合は、あなたの答えが削除されるリスクを実行します。 –

+3

リンクはちょうど死んだ(とゼルダからのものではない)。 –

+1

リンクが死んでいる – TrekOnTV2017

7

コードをお寄せいただきありがとうございます。このコードをお寄せいただきありがとうございます。

cacheDataはキャッシュされるデータであり、キャッシュされる場所ではありません。 そして、自分でキャッシュを取得して処理する必要があります。 私はわかりやすくするために、あなたに少し例を与える:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; 

NSCachedURLResponse *cachedURLResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request]; 

NSData *responseData; 

//check if has cache 
if(cachedURLResponse && cachedURLResponse != (id)[NSNull null]) 
{ 
    responseData = [cachedURLResponse data]; 
} 
else //if no cache get it from the server. 
{ 
    __autoreleasing NSError *error = nil; 
    NSHTTPURLResponse *response = nil; 
    responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 

    //..handle response and error 

    //cache received data 
    cachedURLResponse = [[NSCachedURLResponse alloc] initWithResponse:response data:responseData userInfo:nil storagePolicy:NSURLCacheStorageAllowed]; 
    //store in cache 
    [[NSURLCache sharedURLCache] storeCachedResponse:cachedURLResponse forRequest:request]; 
} 

//..handle responseData 
+0

こんにちはJuzzzは、私はいつもあなたが私を助けてくださいすることができ、cachedURLResponseオブジェクトnilを取得しますか?ありがとう – iBhavik

+0

@iBhavikこれは非常に古い(3年)のサンプルコードですが、何を達成しようとしていますか? url/apiリクエストの処理には、 'AFNetworking'のようなフレームワークを使用することを強くお勧めします。 – Justin

0

スウィフト:

let isReachable = NetworkManager.sharedManager().isInternetReachable()//Reachability- to check internet is available 
     let urlRequestCache:NSURLRequest! 
     if isReachable != 0 { //If ther is intenet then load and caching it 
      urlRequestCache = NSURLRequest(URL: NSURL(string: url)!, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 10) 
      let session = NSURLSession.sharedSession() 
        session.dataTaskWithRequest(urlRequestCache, completionHandler: {(data, response, error) in 
         let newCachedResponse = NSCachedURLResponse(response:(response)!, data:(data)!, userInfo:nil, storagePolicy: .Allowed) 
         NSURLCache.sharedURLCache().storeCachedResponse(newCachedResponse, forRequest:urlRequestCache) 

        }).resume() 

     }else{ // check the cache is available 
      urlRequestCache = NSURLRequest(URL: NSURL(string: url)!, cachePolicy: NSURLRequestCachePolicy.ReturnCacheDataElseLoad, timeoutInterval: 60) 
      guard let _ = NSURLCache.sharedURLCache().cachedResponseForRequest(urlRequestCache) else{ //checking cache if false then 
       print(" cache not found:)") 
       return 
      } 
      print(" cache found:)") 
      } 
     browserView?.loadRequest(urlRequestCache!) 
関連する問題