Does NSURLConnection take advantage of NSURLCache?

前端 未结 3 778
旧时难觅i
旧时难觅i 2020-12-28 21:12

I\'m trying to figure out how to use the URL loading framework to load URLs taking advantage of caching.

I am using NSURLConnections and feeding them NSURLRequests.

3条回答
  •  暖寄归人
    2020-12-28 21:25

    It will indeed use NSURLCache automatically, at least in some circumstances. Certainly it does in the following code:

    EDIT - works in a OS X 10.6 Cocoa app, not iPhone (misread question)

    #import 
    
    int main (int argc, const char * argv[]) {
    
        // run request with default cache policy
     NSMutableURLRequest *req=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://en.wikipedia.org/"]];
     NSData *data=[NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil];
     NSLog(@"Received %d bytes", [data length]);
    
     sleep(10);
    
        // now run it asking it to use the cache
     [req setCachePolicy:NSURLRequestReturnCacheDataElseLoad];
     data=[NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil];
     NSLog(@"Received %d bytes", [data length]);
    
        return 0;
    }
    

提交回复
热议问题