首先得下載AFNetworking庫文件,下載時(shí)得首先弄清楚,你將要開發(fā)的軟件兼容的最低版本是多少。AFNetworking 2.0或者之后的版本需要xcode5.0版本并且只能為IOS6或更高的手機(jī)系統(tǒng)上運(yùn)行,如果開發(fā)MAC程序,那么2.0版本只能在MAC OS X 10.8或者更高的版本上運(yùn)行。
AFNetworking 2.0的下載地址https://github.com/AFNetworking/AFNetworking如果你想要兼容IOS5或MAC OS X 10.7,那你需要用最新發(fā)布的1.x版本AFNetworking 1.x的下載地址https://github.com/AFNetworking/AFNetworking/tree/1.x如果要兼容4.3或者M(jìn)AC OS X 10.6,需要用最新發(fā)布的0.10.x版本AFNetworking 0.10.xhttps://github.com/AFNetworking/AFNetworking/tree/0.10.x2013年大多數(shù)軟件兼容的最低版本為4.3,而2014年,估計(jì)大多數(shù)軟件兼容的最低版本將會是5.0甚至6.0;所以,目前最好的選擇還是1.x版本,兼容到IOS5.0。如何通過URL獲取json數(shù)據(jù)第一種,利用AFJSONRequestOperation,官方網(wǎng)站上給的例子: 
 
 
 
 
 
 
 
 
 
第二種方法,利用AFHTTPRequestOperation 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
如果發(fā)生Error Domain=NSURLErrorDomain Code=-1000 "bad URL" UserInfo=0x14defc80 {NSUnderlyingError=0x14deea10 "bad URL", NSLocalizedDescription=bad URL這個(gè)錯(cuò)誤,請檢查URL編碼格式。有沒有進(jìn)行stringByAddingPercentEsc
如何通過URL獲取圖片
異步獲取圖片,通過隊(duì)列實(shí)現(xiàn),而且圖片會有緩存,在下次請求相同的鏈接時(shí),系統(tǒng)會自動調(diào)用緩存,而不從網(wǎng)上請求數(shù)據(jù)。
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 100.0f, 100.0f, 100.0f)];[imageView setImageWithURL:[NSURL URLWithString:@"http://i./r4uwx.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder-avatar"]]; [self.view addSubview:imageView]; 上面的方法是官方提供的,還有一種方法,
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.scott-sherwood.com/wp-content/uploads/2013/01/scene.png"]];
AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWit hRequest:requestimageProcessingBlock:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) { 
self.backgroundImageView.image = image; 
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) { 
NSLog(@"Error %@",error); 
}]; 
[operation start]; 如果使用第一種URLWithString:
placeholderImage:會有更多的細(xì)節(jié)處理,其實(shí)實(shí)現(xiàn)還是通過AFImageRequestOperation處理,可以點(diǎn)擊URLWithString: placeholderImage:方法進(jìn)去看一下就一目了然了。所以我覺得還是用第一種好。 如何通過URL獲取plist文件
通過url獲取plist文件的內(nèi)容,用的很少,這個(gè)方法在官方提供的方法里面沒有
NSString *weatherUrl = @"http://www.calinks.com.cn/buick/kls/Buickhousekeeper.plist"; 
NSURL *url = [NSURL URLWithString:[weatherUrl stringByAddingPercentEsc apesUsingEncoding:NSUTF8StringEncoding]]; 
NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
[AFPropertyListRequestOpe ration addAcceptableContentType s:[NSSet setWithObject:@"text/plain"]]; 
AFPropertyListRequestOpe ration *operation = [AFPropertyListRequestOpe ration propertyListRequestOpera tionWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id propertyList) { 
NSLog(@"%@",(NSDictionary *)propertyList); 
}failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id propertyList) { 
NSLog(@"%@",error); 
}]; 
[operation start]; 如果稍不留神,可能就出現(xiàn)Error Domain=AFNetworkingErrorDomain Code=-1016 "Expected content type {(
"application/x-plist" )}, got text/plain" UserInfo=0x16e91ce0 {NSLocalizedRecoverySugge
stion= 
...
...
, AFNetworkingOperationFai
lingURLRequestErrorKey= { }, NSErrorFailingURLKey=, NSLocalizedDescription=Expected content type {( 
"application/x-plist" )}, got text/plain, AFNetworkingOperationFai
linponseErrorKey= { URL: } { status code: 200, headers { 
"Accept-Ranges" = bytes; 
Connection = "keep-alive"; 
"Content-Length" = 974; 
"Content-Type" = "text/plain"; 
Date = "Sat, 25 Jan 2014 07:29:26 GMT"; 
Etag = ""1014c2-3ce-4ee63e1c80e00""; 
"Last-Modified" = "Wed, 25 Dec 2013 23:04:24 GMT"; 
Server = "nginx/1.4.2"; 
} }}
可能還會出現(xiàn)亂碼,解決辦法就是[AFPropertyListRequestOpe
ration addAcceptableContentType s:[NSSet setWithObject:@"text/plain"]]; 如何通過URL獲取XML數(shù)據(jù)
xml解析使用AFXMLRequestOperation,需要實(shí)現(xiàn)蘋果自帶的NSXMLParserDelegate委托方法,XML中有一些不需要的協(xié)議格式內(nèi)容,所以就不能像json那樣解析,還得實(shí)現(xiàn)委托。我之前有想過能否所有的XML鏈接用一個(gè)類處理,而且跟服務(wù)端做了溝通,結(jié)果很不方便,效果不好。XML大多標(biāo)簽不同,格式也不固定,所以就有問題,使用json就要方便的多。
第一步;在.h文件中加入委托NSXMLParserDelegate
第二步;在.m文件方法中加入代碼
NSURL *url = [NSURL URLWithString:@"http://113.106.90.22:5244/sshopinfo"]; 
NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
AFXMLRequestOperation *operation = 
[AFXMLRequestOperation XMLParserRequestOperatio nWithRequest:request success:^(NSURLRequest *request,NSHTTPURLResponse *response, NSXMLParser *XMLParser) { 
XMLParser.delegate = self; 
[XMLParser setShouldProcessNamespac es:YES]; 
[XMLParser parse]; 
}failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLParser *XMLParser) { 
NSLog(@"%@",error); 
}]; 
[operation start]; 第三步;在.m文件中實(shí)現(xiàn)委托方法
//在文檔開始的時(shí)候觸發(fā) -(void)parserDidStartDocument:(NSXMLParser *)parser{
NSLog(@"解析開始!"); }
//解析起始標(biāo)記
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
NSLog(@"標(biāo)記:%@",elementName); 
}
//解析文本節(jié)點(diǎn)
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
NSLog(@"值:%@",string); }
//解析結(jié)束標(biāo)記
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
NSLog(@"結(jié)束標(biāo)記:%@",elementName); }
//文檔結(jié)束時(shí)觸發(fā)
-(void) parserDidEndDocument:(NSXMLParser *)parser{
NSLog(@"解析結(jié)束!"); }
運(yùn)行的結(jié)果:
如何使用AFHTTPClient進(jìn)行web service操作AFHTTPClient處理GET 和 POST請求.做網(wǎng)頁的朋友們這個(gè)方法用的比較多。在要經(jīng)常調(diào)用某個(gè)請求時(shí),可以封裝,節(jié)省資源。
BaseURLString = @"http://www.raywenderlich.com/downloads/weather_sample/"; 
NSURL *baseURL = [NSURL URLWithString:[NSString stringWithFormat:BaseURLString]]; 
NSDictionary *parameters = [NSDictionary dictionaryWithObject:@"json" forKey:@"format"]; 
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:baseURL]; 
[client registerHTTPOperationCla ss:[AFJSONRequestOperation class]]; 
[client setDefaultHeader:@"Accept" value:@"text/html"]; 
[client postPath:@"weather.php" parameters:parameters success:^(AFHTTPRequestOperation *operation, idresponseObject) { 
NSString* newStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]; 
NSLog(@"POST請求:%@",newStr); 
}failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
NSLog(@"%@",error); 
}]; 
[client getPath:@"weather.php" parameters:parameters success:^(AFHTTPRequestOperation *operation, idresponseObject) { 
NSString* newStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]; 
NSLog(@"GET請求:%@",newStr); 
}failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
NSLog(@"%@",error); 
}]; 運(yùn)行結(jié)果:
如果需要顯示網(wǎng)絡(luò)活動指示器,可以用下面方法:[AFNetworkActivityIndicatorManager sharedManager].enabled = YES; Error: Error Domain=AFNetworkingErrorDomain Code=-1016 "Request failed: unacceptable content-type: text/html" UserInfo=0x16774de0 {NSErrorFailingURLKey=http://192.168.2.2:8181/ecar/tsp/uploadLocation?CID=781666&serviceType=1, AFNetworkingOperationFai
linponseErrorKey= { URL: http://192.168.2.2:8181/ecar/tsp/uploadLocation?CID=781666&serviceType=1 } { status code: 200, headers { 
XXX 
} }, NSLocalizedDescription=Request failed: unacceptable content-type: text/html}
返回?cái)?shù)據(jù)格式不對。注銷這句話:
op.responseSerializer = [AFJSONResponseSerializer serializer];然后將返回的數(shù)據(jù)自己轉(zhuǎn)換。 error = Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: text/html" UserInfo=0x1740f2c00 {com.alamofire.serialization.response.error.response= { URL: http://192.168.5.132/api/cats?type=apps } { status code: 200, headers {
Connection = "keep-alive"; 
"Content-Type" = "text/html; charset=utf-8"; 
Date = "Thu, 05 Nov 2015 10:27:42 GMT"; 
Server = nginx; 
"Transfer-Encoding" = Identity; } }
AF可以接受json以外的數(shù)據(jù)
自己隨意定義的格式都可以 只不過要使用AFNetwork提供的解析方法的話 它只對通用的格式做處理 你返回的數(shù)據(jù)不是那種格式 他就無法解析出來 那要你自己處理 改變AFNetWork的庫文件 找到他判斷錯(cuò)誤的那個(gè)函數(shù) 讓他從正確的方法返回 如果你不會的話 就在返回錯(cuò)誤的方法處理也可以 反正數(shù)據(jù)已經(jīng)到了 網(wǎng)絡(luò)的目的 是為了得到數(shù)據(jù) 你的數(shù)據(jù)已經(jīng)到了 只不過AFNetwork認(rèn)定你的數(shù)據(jù)不符合常用的格式 確實(shí)也不符合 因?yàn)槟愕臄?shù)據(jù)是加密的東西 而且是對整個(gè)json格式加密 而不是只對值加密 所以要實(shí)現(xiàn)這種格式的傳輸 只能修改AFNetwork的庫 而你不會 那就先這么用著 舉個(gè)例子
你們現(xiàn)在的做法是對整個(gè)字符串加密 如果你不這么做 只將值部分加密 而不對鍵加密 就是{“message”:“值的密文”} 那么這個(gè)數(shù)據(jù)仍然符合json格式 AFNetwork依然能解析出來 你們對整個(gè)json字符串都加密了 那密文就不是json格式了 所以你們可以按我說的改 僅加密值部分 也就按照現(xiàn)在的方法 在錯(cuò)誤的返回方法里面處理數(shù)據(jù) 但是你自己知道數(shù)據(jù)是正確的 只不過AFNetwork誤判了而已 這個(gè)屬于原理上東西 改不了 要么就是不讓AFNetwork解析 他只透傳 你自己解析 如果讓他幫你解析 你就要指定一個(gè)格式給他 指定了格式 而你的數(shù)據(jù)不符合格式 那就是按錯(cuò)誤的方法返回 AFNetworking關(guān)于HTTP認(rèn)證的問題
AFNetwork實(shí)現(xiàn)basic認(rèn)證的方法很簡單
http://stackoverflow.com/questions/12440059/using-afnetworking-and-http-basic-authentication
AFNetwork實(shí)現(xiàn)digest認(rèn)證
創(chuàng)建一個(gè)NSURLCredential對象,然后將對象賦值到請求
https://github.com/AFNetworking/AFNetworking/issues/551http://stackoverflow.com/questions/31784319/digest-access-authentication-for-afnetworking
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationMa nager manager]; NSURLCredential *credential = [[NSURLCredential alloc] initWithUser:@"Username" passWord:@"Password" persistence:NSURLCredentialPersisten ceForSession]; [manager setCredential:credential]; 2015年10月26。關(guān)于AFNetWork2.0的demo已經(jīng)完成,有需要的朋友到QQ群:460325065 下載。 
新聞熱點(diǎn)
疑難解答
圖片精選