@interface AppDelegate () <NSURLConnectionDataDelegate> {
NSMutableData *mData;
}
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
// 第二个参数指定的委托用于处理服务器的响应
// 当服务器返回一个响应、发送数据以及完成响应时会回调委托中的方法
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
// 执行start方法时才真正连接服务器
[conn start];
return YES;
}
#pragma mark NSURLConnectionDataDelegate回调方法
// 收到服务器的响应
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
if (!mData) {
mData = [NSMutableData data];
}
else {
mData.length = 0;
}
}
// 收到服务器发送的数据(该方法可能被调用很多次)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// 将收到的数据拼接起来
[mData appendData:data];
}
// 服务器响应完成(结束从服务器加载数据)
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *str = [[NSString alloc] initWithData:mData encoding:NSUTF8StringEncoding];
// 获得应用程序的沙箱路径
NSString *homeDir = NSHomeDirectory();
NSLog(@"%@", homeDir);
NSString *filename = [homeDir stringByAppendingPathComponent:@"Documents/index.html"];
[str writeToFile:filename atomically:NO encoding:NSUTF8StringEncoding error:nil];
NSLog(@"文件已保存!!!");
}