#pragma mark - 網絡請求代理方式(異步)
- (IBAction)DelegateButtonDidClicked:(UIButton *)sender {
// 1、拼接 urlString,網址裡面必須寫 http://
NSString *urlString = @http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213;
// 2、根據字符串創建 URL(統一資源定位符)
NSURL *url = [NSURL URLWithString:urlString];
// 3、根據 url 創建 request 請求類的對象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 4、請求數據(代理回調方式)遵守代理
[NSURLConnection connectionWithRequest:request delegate:self];
}
代理方法
客戶端收到服務器的響應
#pragma mark | 客戶端收到服務器的響應
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// 只執行一次
// 初始化 receiveData 對象
self.receiveData = [NSMutableData data];
}
客戶端收數據(並非一次性全部拿到)
#pragma mark | 客戶端收數據(並非一次性全部拿到)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// 每次返回的都是新數據
// 拼接數據(請求一點 拼接一點)
[self.receiveData appendData:data];
}
客戶端接收數據完畢
#pragma mark | 客戶端接收數據完畢
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// 解析數據
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:self.receiveData options:(NSJSONReadingMutableContainers) error:nil];
NSArray *array = dict[@news];
self.newsArray = [NSMutableArray array];
for (NSDictionary *smallDict in array) {
NewsModal *modal = [[NewsModal alloc] init];
[modal setValuesForKeysWithDictionary:smallDict];
[self.newsArray addObject:modal];
}
for (NewsModal *modal in self.newsArray) {
NSLog(@%@, modal.title);
}
}
網絡請求失敗
#pragma mark | 網絡請求失敗
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@%@, error);
}