描述:
ASIHttpRequest是應用第三方庫的方法,利用代碼快,減少代碼量,提高效率 準備工作:
一、匯入第三方庫ASIHttpRequest
二、會報很多的錯,原因有兩個,一個是要匯入Xcode中內建的四個檔案,一個是他沒有使用自動引用計數
三、解決方案 1.匯入四個系統檔案,分別是 MobileCoreServices.framework SystemConfiguration.framework
CFNetwork.framework libz.1.2.5.dylib 2.手動關掉自動引用計數 在工程的buide phase 中的 compile sources
中,將ASIHhttp類型的,點擊後面,添加上-fno-objc-arc 3.運行一遍,就不會報錯了 實現非同步post請求
#import "ASIHTTPRequest.h"
- (void)viewDidLoad
{
[self requestHttp];
}
-(void)requestHttp
{
//1200792098331
//首先建立一個URL的對象
NSURL * url = [NSURL urlWithString:[NSString stringWithFormat:@"http://api.kuaidi100.com/api?id=d6b9888b0da96f6b&com=%@&nu=%@&show=0&muti=1&order=desc&display=mobile",name]];
NSURL * url =[NSURL URLWithString:[NSString stringWithFormat:@"http://api.kuaidi100.com/api?id=d6b9888b0da96f6b&com=%@&nu=%@&show=0&muti=1&order=desc&display=mobile"]];
NSLog(@"url======%@",url);
再建立一個請求對象
ASIHTTPRequest * request = [ASIHTTPRequest requestWithURL:url];
發送請求,並返回相應的JSon資料
[request setCompletionBlock:
^{
NSError * error = nil;
//建立一個字典,接收返回的JSON資料
NSDictionary * dictionary = [NSJSONSerialization JSONObjectWithData:request.responseData options:kNilOptions error:&error];
NSLog(@"%@",dictionary);
//建立一個數組,並將字典中的資料存放再數組中
NSArray * arr = [dictionary objectForKey:@"data"];
//將數組中的資料變例一下,並將變例後的資料存放在一個可變的數組中
for (NSDictionary * temp in arr)
{
[self.array addObject:[NSString stringWithFormat:@"%@ \n%@",[temp objectForKey:@"time"],[temp objectForKey:@"context"]]];
}
// 將變例後的可變數組中的資料以字串的形勢賦給一個可變字串對象,同時變例字串
for(NSString* temp in self.array)
{
[self.mutableString appendString:[NSString stringWithFormat:@"%@\n",temp]];
NSLog(@" temp==== %@",temp);
}
//我這裡是將變例後的可變字串賦給了一個lable
self.jieGuoLale.text = self.mutableString;
NSLog(@"self.jieGuoLale.text======%@",self.jieGuoLale.text);
}];
//如果請求發送失敗,則調出警告框
[request setFailedBlock:
^{
UIAlertView * alerteView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"問題警告:網路連結異常,請稍後再試" delegate:nil cancelButtonTitle:@"退出" otherButtonTitles: nil];
[alerteView show];
}];
//發送一個非同步請求
[request startAsynchronous];