如何调用forloop内的web服务?

时间:2015-06-02 13:35:09

标签: ios objective-c web-services

如何在for循环内调用Web服务?我有两个Web服务。首先,我调用一个Web服务,并返回一些数据(名称,用户ID等)。我使用此用户标识来调用下一个服务。我想在一个卷轴中显示骆驼的所有数据(例如两个骆驼每个都有这么多的照片和视频),我想列出新滚动视图中的所有图像和视频。

我的代码正在向您展示:

-(void)listiingNewCamels
{
    int numberOfCamels = [msgArray count];
    for (int i = 0; i < numberOfCamels; i++)
    {
        camObject=(IZCamelObject *)[msgArray objectAtIndex:i];
        CGFloat yOrigin = i * 395;
        UIView*mySampleview = [[UIView alloc] initWithFrame:CGRectMake(34,yOrigin+20,702,365)];
        mySamplev.backgroundColor=[UIColor redColor];
        camelIDStr=camObject.CamelID;

        UIScrollView *myCamelImagesScroll=[[UIScrollView alloc]initWithFrame:CGRectMake(34,30,640,180)];
        myCamelImagesScroll.backgroundColor=[UIColor greenColor];
        [mySampleview addSubview:myCamelImagesScroll];
        [_camelListingScrol mySampleview];
    }
    _camelListingScrol.contentSize = CGSizeMake(395, numberOfCamels * 400);
}

1 个答案:

答案 0 :(得分:1)

如果连接速度很慢或服务器没有立即响应,Web服务调用可能需要几秒钟才能完成每个调用,甚至更长时间。

您无法将GUI代码和同步代码组合在一起,例如假设您的for循环在伪代码中是这样的:

for (int i = 0; i < numberOfCamels; i++)
{
    get camel info from camObject
    make synchronous web service call 1
    make synchronous web service call 2
    create scroll view
 }

假设每个Web服务调用需要2秒钟,并且您有10个骆驼,这意味着for循环完成需要20秒。您的应用GUI将挂起20秒,用户将无法使用它。

因此,您必须使您的Web服务调用异步,并且您还必须决定如何相应地设计程序。

如何做到这一点取决于您,您可以做的一件事就是立即使用IZCamelObject中的camel信息绘制滚动视图,并在每个Web服务调用完成后更新滚动视图。

当应用程序启动你的模型时(你知道MVC吗?)立即开始进行Web服务调用,这样当你的GUI滚动视图调用驼峰数据的模型时它已经(或者大部分都有)下载。

您的思维方式以及程序的设计需要从同步变为异步。在找到解决方案之前,您需要首先确定如何处理异步数据下载。

GUI代码不应该进行Web服务调用,这应该是模型组件的责任,但为了说明以异步方式更新滚动视图的概念,它可能在伪代码中看起来像这样:

   create scroll view
   for (int i = 0; i < numberOfCamels; i++)
    {
        get camel info from camObject
        add a subview with info from camObject
        make asynchronous web service call 1 with completion block: {update subview with data from web service call 1}
        make asynchronous web service call 2 with completion block: {update subview with data from web service call 2
     }