如何从NSURLConnection委托发送多个网址请求?

时间:2012-01-24 04:31:14

标签: ios xmlhttprequest xml-parsing nsurlconnection

这是我的应用程序的逻辑流程:

  1. 首先,当视图控制器完成加载时,NSURLConnection请求可以开始执行

  2. 响应包含xml数据

  3. 解析该xml后,我需要发送另一个NSURLConnection请求。

  4. 发送第二个请求后,如果响应正常,我会收到其他xml数据

  5. 在解析第二个xml之后,我必须检查第一个和第二个xml数据之间的一些问题。

  6. 那么,是否可以发送多个请求?怎么样?我不需要代码,你可以解释一下。

    提前谢谢。

3 个答案:

答案 0 :(得分:14)

我使用NSURLConnection创建它们属性,然后检查它是哪一个:

 @property (nonatomic,retain) NSURLConnection *myConnection;
@property (nonatomic,retain) NSURLConnection *mySecondConnection;

然后在代表中:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{

     if (connection == myConnection){
       //do something
    }

    if (connection == mySecondConnection){
       // do something else
        }

}

您可以将NSURLRequest传递给连接:

self.myConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

答案 1 :(得分:1)

有一个第三方库,它是CFNetwork的封装器ASIHTTPREQUEST

这个图书馆应该适合你。这样您就不必从头开始编写代码。另一种方法是创建一个类,负责创建NSURLConnection然后发送请求,最后通过委托或通知向视图控制器发送一个数据。

答案 2 :(得分:0)

- (void)viedDidLoad{

    [super viewDidLoad];
    [self firstRequestMethod];

}

- (void)firstRequestMethod{

    NSString *myFirstRequestURL = @"<URL>";
    NSURL *webURL = [NSURL URLWithString:myFirstRequestURL];        

    NSURLRequest *request = [NSURLRequest requestWithURL:webURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
    NSError *error;
    NSURLResponse *response;
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

    if(returnData)
    {
        NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSASCIIStringEncoding];
        //Parse your response here.
        //Is desired response obtain call the second Request, as described above
        if (TRUE) {  //on success
            [self secondRequestMethod];
        }

    }



}

- (void)secondRequestMethod{

    NSString *mySecondRequestURL = @"<URL>";
    NSURL *webURL = [NSURL URLWithString:mySecondRequestURL];        

    NSURLRequest *request = [NSURLRequest requestWithURL:webURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
    NSError *error;
    NSURLResponse *response;
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

    if(returnData)
    {
        NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSASCIIStringEncoding];
        //Parse your response here.
        //Is desired response obtain call the second Request, as described above
        if (TRUE) {  //on success
            //subsequent calls to other url, same as above
        }

    }



}

希望这会帮助你更好地理解......