資料請求:NSURLConnection ,代理方法
//
// ViewController.m
// 3、非同步請求
//
// Created by yongma00 on 15/12/10.
// Copyright © 2015年 yongma. All rights reserved.
//
#import "ViewController.h"
/*
我們可以使用NSMutableData來下載小檔案
如果我們在這裡面去使用NSMutableData來下載大檔案的時候,明顯不合理
*/
@interface ViewController ()<NSURLConnectionDataDelegate>{
NSMutableData *dataM;
}
- (IBAction)btnPressed:(id)sender;
@property (weak, nonatomic) IBOutlet UILabel *label;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
dataM=[[NSMutableData alloc]init];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)btnPressed:(id)sender {
// //1、生成請求的url
// NSString *[email protected]"http://192.168.0.100:8080/MJServer/login
// NSURL *url=[NSURL URLWithString:str];
// NSData *postData=[@"username=123&pwd=123&type=JSON" dataUsingEncoding:NSUTF8StringEncoding];
// //2、根據請求生成對應的Request
// NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
// [request setHTTPMethod:@"POST"];
// [request setHTTPBody:postData];
//1、生成請求的url
NSString *str= @"http://192.168.0.107:8080/MJServer/resources/videos/videos.zip";
NSURL *url=[NSURL URLWithString:str];
//2、根據請求生成對應的Request
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
//3、建立一個連線並且指定代理人為自己
NSURLConnection *connection=[[NSURLConnection alloc]initWithRequest:request delegate:self];
}
//每次請求將要傳送之前呼叫的方法,如果在這個方法裡面不返回請求,那麼就沒有請求
- (nullable NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(nullable NSURLResponse *)response{
NSLog(@"%@---%@",request,response);
return request;
}
//接收到資料的時候呼叫
//會呼叫很多次
//資料是一點點過來的。
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
// NSLog(@"%@",data);
// [dataM appendData:data];
}
//請求完成的時候呼叫這個方法
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(@"結束");
}
@end