Wednesday, May 1, 2013

NSURLRequest requestWithURL example ios


requestWithURL:

Creates and returns a URL request for a specified URL with default cache policy and timeout value.
+ (id)requestWithURL:(NSURL *)theURL
Parameters of [NSURLRequest requestWithURL]
theURL
The URL for the new request.
Return Value
The newly created URL request.
Discussion of [NSURLRequest requestWithURL]
The default cache policy is NSURLRequestUseProtocolCachePolicy and the default timeout interval is 60 seconds.
Example of [NSURLRequest requestWithURL]
- (void)loadAboutHTML {
UIWebView *aboutHTML = [[UIWebView alloc] init];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"yourFileName" ofType:@"html"]]];
[aboutHTML loadRequest:urlRequest;
[self addSubview:aboutHTML];
}
Example of [NSURLRequest requestWithURL]
NSString* url = [NSString stringWithFormat:@"http://www.lenniedevilliers.net/mail.php?subject=%@&to=%@&body=%@", subjectLine, toAddress, emailBody ];

NSLog(@"web service URL: %@", url);

//add the following or something like
[url setString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; 

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];

//modify the following    
connection = [[NSURLConnection alloc] initWithRequest: request delegate:self startImmediately:YES]; 
NSLog(@"connection: %@", [connection debugDescription]);
if (connection) {
    NSLog(@"Connection succeeded");
} else {
    NSLog(@"Connection failed");
}
Example of [NSURLRequest requestWithURL]
UIWebView *web = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
[web loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] 
                            pathForResource:@"help" ofType:@"html"]isDirectory:NO]]];
web.backgroundColor = [UIColor clearColor];