{
//注意:當這個頁面被銷燬的時候如果請求還沒有完成需要終止這個鏈接
[_connectioncancel];
[_connectionrelease];
[superdealloc];
#define kSearchURL @"http://api.map.baidu.com/place/v2/search?query=公廁®ion=上海&output=json&ak=6E823f587c95f0148c19993539b99295"
#define kNewsListURL @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"
#define kNewsListParam @"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213"
NSURL *url = [NSURLURLWithString:newStr];
//創建一個請求
//timeoutInterval請求超時的時間 秒爲單位
NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:urlcachePolicy:(NSURLRequestUseProtocolCachePolicy)timeoutInterval:10];
//設置一個請求標識
NSError *error = nil;
//創建空的,服務器響應信息
NSURLResponse *response = nil;
//建立同步鏈接並得到返回的數據(data)
NSMutableDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
NSLog(@"%@",dataDic);
NSLog(@"%@",response);
NSLog(@"%@",data);
//獲取網址對象 (有中文 需要轉碼)
NSString *urlStr = [kSearchURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
//利用網址創建網址對象
NSURL *url = [NSURL URLWithString:urlStr];
//利用網址對象創建一個請求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:10];
//標識請求類型
//注意:加標識符
#pragma mark -- 代理方法異步鏈接
//利用請求創建一個異步鏈接
self.connection = [NSURLConnection connectionWithRequest:requestdelegate:self];
//開始鏈接
[self.connectionstart];
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//鏈接成功時創建data
self.receiveData = [NSMutableData data];
NSLog(@"已經接收到服務器的響應信息,說明鏈接成功");
NSLog(@"%@",response);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
//多次觸發這個方法才能接收到完整的data
//所以這個時候需要拼接一下data
//拼接data
[self.receiveData appendData:data];
NSLog(@"接收到數據觸發的方法");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"%@",self.receiveData);
//解析數據
NSMutableDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:self.receiveData options:(NSJSONReadingMutableContainers)error:nil];
NSLog(@"%@",dataDic);
//如果在tableView上展示的話
//注意:要刷新界面
NSLog(@"已經完成數據加載觸發的方法");
}
//請求失敗時觸發
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"請求失敗時觸發 %@",error);