2012-07-10 193 views
0

我有這樣的功能,將通過一個請求操作得到的xml:返回字符串

-(id)xmlRequest:(NSString *)xmlurl 
{ 
    AFKissXMLRequestOperation *operation = [AFKissXMLRequestOperation XMLDocumentRequestOperationWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:xmlurl]] success:^(NSURLRequest *request, NSHTTPURLResponse *response, DDXMLDocument *XMLDocument) { 
     NSLog(@"XMLDocument: %@", XMLDocument); 
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, DDXMLDocument *XMLDocument) { 
     NSLog(@"Failure!"); 
    }]; 
    [operation start]; 
    return operation; 
} 

這是我的代碼調用該函數:

Request *http=[[Request alloc] init]; 
NSString *data=[http xmlRequest:@"http://legalindexes.indoff.com/sitemap.xml"]; 
NSError *error; 
DDXMLDocument *ddDoc=[[DDXMLDocument alloc] initWithXMLString:data options:0 error:&error]; 
NSArray *xmlItems=[ddDoc nodesForXPath:@"//url" error:&error]; 
NSMutableArray *returnArray = [[NSMutableArray alloc] initWithCapacity:[xmlItems count]]; 
for(DDXMLElement* itemElement in xmlItems){ 
    DDXMLElement *element = [[itemElement nodesForXPath:@"loc" error:&error] objectAtIndex:0]; 
    NSLog(@"valueasstring %@", element); 
    [returnArray addObject:element]; 
} 

我需要的xmlRequest到返回一個字符串,所以我可以得到的XML,但[操作開始]創建正確的輸出,但我不能把它放在一個字符串。我怎樣才能將輸出導入字符串?

+0

你試過'返回[操作開始]'? – 2012-07-10 19:22:38

+0

(我不知道AFKissXMLRequestOperation是什麼,或者它的'operation'方法。) – 2012-07-10 19:23:51

+2

好吧,它是NSOperation的子類。所以你開始一個NSOperation,並且沒有辦法同步獲得異步操作的結果。您需要監視完成的操作,然後在此例程之外獲取結果。 – 2012-07-10 19:27:14

回答

1

在該代碼中,網絡請求異步發生 - 您無法從該方法返回其結果。

NSLog(@"XMLDocument: %@", XMLDocument);位於成功處理程序塊內部 - 將在請求實際完成時調用。您應該用代碼替換日誌語句以將字符串保存在某處,然後才能調用代碼的其餘部分。

有你能做到這幾個方面:

  1. 創建的類的屬性一樣@property (strong) DDXMLDocument *XMLDocument;

    然後,您可以用self.XMLDocument = XMLDocument;

    替換日誌聲明之後,再拍方法它會完成剩下的處理。

  2. 或者,只需製作另一種方法,如-processWithXMLDocument:(DDXMLDocument *)XMLDocument;,您可以從該塊中調用,只需將其作爲參數傳遞即可。

    我不記得是什麼調度隊列的成功處理程序將被調用,所以你可能要小心運行代碼背面的主線程上dispatch_async(dispatch_get_main_queue(), ^(){…

+0

非常感謝您的回覆。我相信這會起作用,我只是不知道該怎麼做。我嘗試將XMLDocument設置爲等於一個變量,但是我無法返回任何成功塊中的任何內容,也無法識別成功塊外的變量。 – Becksters 2012-07-12 13:16:56

+0

查看更新答案獲取更多幫助。 – DouglasHeriot 2012-07-12 13:23:44