2012-07-10 122 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