同步加载有两种,一个是直接加载方式,另一个是发送标准同步请求后生成页面的方式。
直接方式的实现是requestWithURL:url,这种方案基本上已经很少有人用了。它可以向服务器发送普通请求,也可以向服务器下载图片。现在一般只有部分人用它下载图片。
发送标准同步请求的方式就是通过sendSynchronousRequest这个函数实现。
咱们的这个标准同步请求模块是通过代理来实现,就只贴代码,步贴使用方法了。
chttpSendSynchronousRequest.h文件
#import <Foundation/Foundation.h>
@interface chttpSendSynchronousRequest : NSObject
- (void)sendHttpRequest:(NSString*)sendString : (NSInteger *)resultCode : (NSString **)recvData;
@end
chttpSendSynchronousRequest.m文件
- (void)sendHttpRequest:(NSString*)sendString : (NSInteger *)resultCode : (NSString **)recvData
{
if(nil == serverUrl) //|| (nil == sendString))
{
*resultCode = -1;
recvData = nil;
return;
}
NSURL *serverNUSUrl = [NSURL URLWithString:serverUrl];
NSLog(@"%@", sendString);
NSError *error = nil;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:serverNUSUrl
cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
[request setHTTPMethod:@"POST"];
[request setValue:@"text.html" forHTTPHeaderField:@"Content-Type"];
NSString * sendData = sendString;
NSData *postData = [sendData dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
NSInputStream *is = [NSInputStream inputStreamWithData:postData];
[request setHTTPBodyStream:is];
NSData *nsRecvData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
if(nil != error)
{
*resultCode = -1;
recvData = nil;
return;
}
NSString * recvStrData = [[NSString alloc] initWithData:nsRecvData encoding:NSUTF8StringEncoding];
if(nil == recvStrData)
{
*resultCode = -1;
recvData = nil;
return;
}
NSLog(@"recvStrData[%@]",recvStrData);
*recvData = recvStrData;
*resultCode = 0;
return;
}
@end
通过requestWithURL:url实现直接同步加载图像代码示例:
- (void)loadImageFromURL:(NSURL*)url {
NSURLRequest* request = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[_data setLength:0];
_connection = [[NSURLConnection alloc]
initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)theConnection
didReceiveData:(NSData *)incrementalData {
NSData * da = [[NSData alloc] initWithData:incrementalData];
[_data appendData:da];
LogInfo(@"succeeded %d byte received", [_data length]);
NSString* fileName2 = [self filePath:@"image23.jpg"];
[da writeToFile:fileName2 atomically:YES];
}
- (void)connection:(NSURLConnection *)theConnection didFailWithError:(NSError *)error{
// 当请求失败时的相关操作;
[_data setLength:0];
}
- (void)connectionDidFinishLoading:(NSURLConnection*)theConnection {
LogInfo(@"succeeded %d byte received", [_data length]);
}