NSURLConnection - 是否可以等待/阻止请求?

时间:2009-12-13 21:47:16

标签: macos cocoa nsurlconnection blocking

我需要等待SOAP Web服务的响应,我通过NSURLConnection调用,因为我需要操作返回的数据然后将它从我的类返回到调用类..

这是我的代码:

#import <Foundation/Foundation.h>


@interface UsersBLL : NSObject {

 NSMutableData *webData;
 NSMutableString *soapResults;
 NSXMLParser *xmlParser;
 BOOL *recordResults;
 NSNumber *EmailCount;
}

@property(nonatomic, retain) NSMutableData *webData;
@property(nonatomic, retain) NSMutableString *soapResults;
@property(nonatomic, retain) NSXMLParser *xmlParser;



-(int)checkEmailAddress:(NSString*)emailAddress;
@end

#import "UsersBLL.h"


@implementation UsersBLL
@synthesize webData;
@synthesize soapResults;
@synthesize xmlParser;

-(id)init {
 self = [super init];
 return self;
}

-(int)checkEmailAddress:(NSString*)emailAddress {
 // Build the SOAP envelope
 NSString *soapMessage = [NSString stringWithFormat:
        @"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
        "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
        "<soap:Body>\n"
        "<CheckEmailAddress xmlns=\"http://tempuri.org/\">\n"
        "<EmailAddress>%@</EmailAddress>\n"
        "</CheckEmailAddress>\n"
        "</soap:Body>\n"
        "</soap:Envelope>\n", emailAddress];

 NSLog(soapMessage);

 NSURL *url = [NSURL URLWithString:@"http://photoswapper.mick-walker.co.uk/UsersService.asmx?op=CheckEmailAddress"];
 NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
 NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMessage length]];

 [theRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
 [theRequest addValue: @"http://tempuri.org/CheckEmailAddress" forHTTPHeaderField:@"SOAPAction"];
 [theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
 [theRequest setHTTPMethod:@"POST"];
 [theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];

 NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

 if( theConnection )
 {
  webData = [[NSMutableData data] retain];
 }
 else
 {
  NSLog(@"theConnection is NULL");
 }
 NSLog(@"%@", EmailCount);
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
 [webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
 [webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
 NSLog(@"ERROR with theConenction");
 [connection release];
 [webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
 NSLog(@"DONE. Received Bytes: %d", [webData length]);
 NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
 NSLog(theXML);
 [theXML release];

 if( xmlParser )
 {
  [xmlParser release];
 }

 xmlParser = [[NSXMLParser alloc] initWithData: webData];
 [xmlParser setDelegate: self];
 [xmlParser setShouldResolveExternalEntities: YES];
 [xmlParser parse];

 [connection release];
 [webData release];
}

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName
   attributes: (NSDictionary *)attributeDict
{
 if( [elementName isEqualToString:@"CheckEmailAddressResult"])
 {
  if(!soapResults)
  {
   soapResults = [[NSMutableString alloc] init];
  }
  recordResults = TRUE;
 }
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
 if( recordResults )
 {
  [soapResults appendString: string];
 }
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
 if( [elementName isEqualToString:@"CheckEmailAddressResult"])
 {
  recordResults = FALSE;
  NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init];
  EmailCount = [formatter numberFromString:soapResults];
            [formatter release];
  [soapResults release];
  soapResults = nil;
 }
}

@end

CheckEmailAddress被声明为返回一个整数值(我知道它在上面的示例中没有返回任何内容)。

我理想的是,通过CheckEmailAddress方法,返回从Web服务检索到的值。然而,由于调用NSURLConnection不等到请求完成,我不能这样做。

如果有人能给我任何潜在的解决方法,我将不胜感激。

4 个答案:

答案 0 :(得分:2)

最简单的解决方案是使用[NSURLConnection sendSynchronousRequest:returningResponse:error:]

它不会像您采用的方法那样进行控制,但对于大多数应用程序来说通常都足够了。

答案 1 :(得分:1)

我刚刚发布了一个包含异步NSURLConnection的解决方案,以便能够阻止调用线程。如果您需要比标准[NSURLConnection sendSynchronousRequest:returningResponse:error:]更多的控制,您可以在StackOverflow上查看此链接:

NSURLConnection blocking wrapper implemented with semaphores

答案 2 :(得分:0)

您有两种选择:

  • 使用+[NSURLConnection sendSynchronousRequest:returningResponse:error:]

  • 以自定义runloop模式安排连接,并以该模式运行循环,直到数据到达或您需要取消连接

答案 3 :(得分:0)

这一切都取决于你需要的异步水平:

  • 如果在整个请求期间保持阻止是可以的,您可能需要使用

      +[NSURLConnection sendSynchronousRequest:returningResponse:error:]
    

    但是,正如Wade建议的那样,小心为NSURLRequest添加超时,否则连接可能会阻塞,您的应用程序将挂起。

  • 如果没有,您只需使用NSNotificationCenter即可。但是你必须小心数据的竞争条件,特别是如果你正在处理多个请求