【问题标题】:how call nsurlconnection delegate methods continuosly in iphone如何在 iphone 中连续调用 nsurlconnection 委托方法
【发布时间】:2012-08-21 06:17:46
【问题描述】:

您好,在我的一个申请中。我必须连续多次向服务器(json服务器)发送请求。我的网址将如下所述

@"http://185.185.116.51/servername/serverjspfilesname.jsp?filterID=21&ticket=65675656565656567"

实际上我有很多过滤器 ID(过滤器 ID,您可以在顶部找到)。为了不断更改过滤器 ID,我使用了如下所述的循环

for(int i=0;i<[appdelegate.listOfFiltersArray count];i++)
    {

        filtersDataModelObject=[[ListOfFiltersDataModel alloc]init];

        filtersDataModelObject=[appdelegate.listOfFiltersArray objectAtIndex:i];

       homescreenstring=[NSString stringWithFormat:@"http://%@/servername/serverjspfilesname.jsp?filterID=%@&ticket=%@",Ip,filtersDataModelObject.filterID,[storeData stringForKey:@"securityTicket"]];


        NSLog(@"url is %@",homescreenstring);

        NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:homescreenstring]];

        connection=[[NSURLConnection alloc]initWithRequest:request delegate:self];

        if(connection)
        {

            homeScreenResponseData=[[NSMutableData alloc]init];

        }
        else
        {

            NSLog(@"connection failed");
        }

    }

实际上,在 for 循环中满足每个条件后,我必须连接服务器以使用 nsurlconnection 委托方法从服务器获取数据。但是在这里,在完全执行 for 循环之后,只有 nsurlconnection 委托方法使用从 appdelegate.listOfFiltersArray 数组获取的最后一个 filterid 执行。

但我想为每个 filterid 调用服务器。

如果有人知道请告诉我。提前谢谢。

【问题讨论】:

    标签: iphone json


    【解决方案1】:

    在.h文件中创建一个计数变量int count。

     int count = 0 //in .m file
    

    现在使用这个方法:

    - (void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
      //one request finished
      count ++;
      //request another using count
    }
    

    【讨论】:

    • 嗨,王子,我需要你的更多帮助。实际上,我会从服务器获得不同过滤器的响应。我不知道过滤器的数量。基于filterid的计数,我必须根据filterid的数量在运行时动态创建许多数组,以存储有关每个过滤器的信息(信息可能是图像或元数据,无论我必须将其存储在数组中)。我可以知道我们如何动态创建数组。提前谢谢。
    【解决方案2】:

    Prince 提出的解决方案并不通用,因为您将面临定义 每个请求的“filterid”。

    而你正在做的是一个糟糕的方法。不要将 Web 请求与您的业务逻辑代码混合。Web 内容应由一个单独的文件处理,该文件处理整个应用程序中的所有请求。该类将实现委托。

    对于委派,您需要执行以下操作。 在您的网络类标头 (Networkclass.h) 中添加协议

    @protocol NetworkControllerDelegate <NSObject>
    -(void) UrlResponseRecieved :(NSData *)responseData;
    -(void) UrlResponseFailed:(NSError *)error;
    @end
    

    并在 NetworkClass.m(实现文件)中执行以下操作

    - (void)connectionDidFinishLoading:(NSURLConnection *)connection 
    {
        if (receivedData != nil) 
        {
           if([delegate respondsToSelector:@selector(UrlResponseRecieved:)])
            [self.delegate UrlResponseRecieved:receivedData];
            [receivedData release];
            receivedData = nil;
        }
        [connection release];
    }
    

    如果还是卡住,可以参考以下 What's wrong on following URLConnection?

    或者您可以先阅读任何异步下载教程。

    【讨论】:

      猜你喜欢
      • 2011-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-29
      • 1970-01-01
      相关资源
      最近更新 更多