天天看點

iOS開發網絡資料之AFNetworking使用

如何選擇afnetworking版本

首先得下載下傳afnetworking庫檔案,下載下傳時得首先弄清楚,你将要開發的軟體相容的最低版本是多少。afnetworking 2.0或者之後的版本需要xcode5.0版本并且隻能為ios6或更高的手機系統上運作,如果開發mac程式,那麼2.0版本隻能在mac

os x 10.8或者更高的版本上運作。

<a target="_blank" href="https://github.com/afnetworking/afnetworking">afnetworking 2.0的下載下傳位址https://github.com/afnetworking/afnetworking</a>

如果你想要相容ios5或mac os x 10.7,那你需要用最新釋出的1.x版本

<a target="_blank" href="https://github.com/afnetworking/afnetworking/tree/1.x">afnetworking 1.x的下載下傳位址https://github.com/afnetworking/afnetworking/tree/1.x</a>

如果要相容4.3或者mac os x 10.6,需要用最新釋出的0.10.x版本

如何通過url擷取json資料

第一種,利用afjsonrequestoperation,官方網站上給的例子:

nsstring *str=[nsstring stringwithformat:@"https://alpha-api.app.net/stream/0/posts/stream/global"];  

   nsurl *url = [nsurl urlwithstring:[str stringbyaddingpercentescapesusingencoding:nsutf8stringencoding]];  

   nsurlrequest *request = [nsurlrequest requestwithurl:url];  

   //    從url擷取json資料  

   afjsonrequestoperation *operation1 = [afjsonrequestoperation jsonrequestoperationwithrequest:request success:^(nsurlrequest *request, nshttpurlresponse *response, nsdictionary* json) {  

               nslog(@"擷取到的資料為:%@",json);  

   } failure:^(nsurlrequest *request, nshttpurlresponse *response, nserror *error, id data) {  

       nslog(@"發生錯誤!%@",error);  

   }];  

   [operation1 start];  

第二種方法,利用afhttprequestoperation 先擷取到字元串形式的資料,然後轉換成json格式,将nsstring格式的資料轉換成json資料,利用ios5自帶的json解析方法:

  nsurl *url = [nsurl urlwithstring:[str stringbyaddingpercentescapesusingencoding:nsutf8stringencoding]];  

  nsurlrequest *request = [nsurlrequest requestwithurl:url];  

 afhttprequestoperation *operation = [[afhttprequestoperation alloc]initwithrequest:request];  

  [operation setcompletionblockwithsuccess:^(afhttprequestoperation *operation, idresponseobject) {  

      nsstring *html = operation.responsestring;  

           nsdata* data=[html datausingencoding:nsutf8stringencoding];  

           id dict=[nsjsonserialization  jsonobjectwithdata:data options:0 error:nil];  

      nslog(@"擷取到的資料為:%@",dict);  

  }failure:^(afhttprequestoperation *operation, nserror *error) {  

      nslog(@"發生錯誤!%@",error);  

  }];  

  nsoperationqueue *queue = [[nsoperationqueue alloc] init];  

  [queue addoperation:operation];  

如果發生error domain=nsurlerrordomain code=-1000 "bad url" userinfo=0x14defc80 {nsunderlyingerror=0x14deea10 "bad url", nslocalizeddescription=bad url這個錯誤,請檢查url編碼格式。有沒有進行stringbyaddingpercentescapesusingencoding:nsutf8stringencoding

如何通過url擷取圖檔

異步擷取圖檔,通過隊列實作,而且圖檔會有緩存,在下次請求相同的連結時,系統會自動調用緩存,而不從網上請求資料。

uiimageview *imageview = [[uiimageview alloc] initwithframe:cgrectmake(0.0f, 100.0f, 100.0f, 100.0f)];      [imageview setimagewithurl:[nsurl urlwithstring:@"http://i.imgur.com/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 imagerequestoperationwithrequest:request imageprocessingblock: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:會有更多的細節處理,其實實作還是通過afimagerequestoperation處理,可以點選urlwithstring:  placeholderimage:方法進去看一下就一目了然了。是以我覺得還是用第一種好。

如何通過url擷取plist檔案

通過url擷取plist檔案的内容,用的很少,這個方法在官方提供的方法裡面沒有

nsstring *weatherurl = @"http://www.calinks.com.cn/buick/kls/buickhousekeeper.plist";  

  nsurl *url = [nsurl urlwithstring:[weatherurl stringbyaddingpercentescapesusingencoding:nsutf8stringencoding]];  

  [afpropertylistrequestoperation addacceptablecontenttypes:[nsset setwithobject:@"text/plain"]];  

  afpropertylistrequestoperation *operation = [afpropertylistrequestoperation propertylistrequestoperationwithrequest:request success:^(nsurlrequest *request,nshttpurlresponse *response, id propertylist) {  

      nslog(@"%@",(nsdictionary *)propertylist);  

  }failure:^(nsurlrequest *request, nshttpurlresponse *response, nserror *error, idpropertylist) {  

      nslog(@"%@",error);  

  [operation start];  

如何通過url擷取xml資料

xml解析使用afxmlrequestoperation,需要實作蘋果自帶的nsxmlparserdelegate委托方法,xml中有一些不需要的協定格式内容,是以就不能像json那樣解析,還得實作委托。我之前有想過能否所有的xml連結用一個類處理,而且跟服務端做了溝通,結果很不友善,效果不好。xml大多标簽不同,格式也不固定,是以就有問題,使用json就要友善的多。

第一步;在.h檔案中加入委托nsxmlparserdelegate

第二步;在.m檔案方法中加入代碼

nsurl *url = [nsurl urlwithstring:@"http://113.106.90.22:5244/sshopinfo"];  

    nsurlrequest *request = [nsurlrequest requestwithurl:url];  

    afxmlrequestoperation *operation =  

    [afxmlrequestoperation xmlparserrequestoperationwithrequest:request success:^(nsurlrequest*request, nshttpurlresponse *response, nsxmlparser *xmlparser) {  

        xmlparser.delegate = self;  

        [xmlparser setshouldprocessnamespaces:yes];  

        [xmlparser parse];  

    }failure:^(nsurlrequest *request, nshttpurlresponse *response, nserror *error, nsxmlparser*xmlparser) {  

        nslog(@"%@",error);  

第三步;在.m檔案中實作委托方法

    //在文檔開始的時候觸發

-

(void)parserdidstartdocument:(nsxmlparser *)parser{  

    nslog(@"解析開始!");  

}  

//解析起始标記  

- (void)parser:(nsxmlparser *)parser didstartelement:(nsstring *)elementname namespaceuri:(nsstring *)namespaceuri qualifiedname:(nsstring *)qname attributes:(nsdictionary*)attributedict{  

    nslog(@"标記:%@",elementname);  

//解析文本節點  

- (void)parser:(nsxmlparser *)parser foundcharacters:(nsstring *)string{  

    nslog(@"值:%@",string);  

//解析結束标記  

- (void)parser:(nsxmlparser *)parser didendelement:(nsstring *)elementname namespaceuri:(nsstring *)namespaceuri qualifiedname:(nsstring *)qname{  

    nslog(@"結束标記:%@",elementname);  

//文檔結束時觸發  

-(void) parserdidenddocument:(nsxmlparser *)parser{  

    nslog(@"解析結束!");  

運作的結果:

如何使用afhttpclient進行web service操作

afhttpclient處理get 和 post請求.做網頁的朋友們這個方法用的比較多。在要經常調用某個請求時,可以封裝,節省資源。  

   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 registerhttpoperationclass:[afjsonrequestoperation class]];  

    [client setdefaultheader:@"accept" value:@"text/html"];  

    [client postpath:@"weather.php" parameters:parameters success:^(afhttprequestoperation*operation, id responseobject) {  

        nsstring* newstr = [[nsstring alloc] initwithdata:responseobjectencoding:nsutf8stringencoding];  

        nslog(@"post請求:%@",newstr);  

    }failure:^(afhttprequestoperation *operation, nserror *error) {  

    [client getpath:@"weather.php" parameters:parameters success:^(afhttprequestoperation*operation, id responseobject) {  

        nslog(@"get請求:%@",newstr);  

運作結果:

如果需要顯示網絡活動訓示器,可以用下面方法:

[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&amp;servicetype=1, afnetworkingoperationfailinponseerrorkey=

{ url: http://192.168.2.2:8181/ecar/tsp/uploadlocation?cid=781666&amp;servicetype=1 } { status code: 200, headers {

    xxx

} }, nslocalizeddescription=request failed: unacceptable content-type: text/html}

傳回資料格式不對。登出這句話: op.responseserializer = [afjsonresponseserializerserializer];然後将傳回的資料自己轉換。