开发者

Wait for code to finish execution

开发者 https://www.devze.com 2023-01-14 14:51 出处:网络
I would like to know the easiest way to wait for code to finish execution within an objective c project because I am calling a webservice and retrieving the results and instead it is retrieving the re

I would like to know the easiest way to wait for code to finish execution within an objective c project because I am calling a webservice and retrieving the results and instead it is retrieving the results befor开发者_运维技巧e the webservice has finished being called and filled.

Any suggestions please?

Btw this is my webservice code:

    NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:tmpURl];

[theRequest addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

[theRequest addValue:@"http://tempuri.org/GetCategory" forHTTPHeaderField:@"SOAPAction"];

NSString *msgLength=[NSString stringWithFormat:@"%i",[soapMessage length]];

[theRequest addValue:msgLength forHTTPHeaderField:@"Content-Length"];

[theRequest setHTTPMethod:@"POST"];

[theRequest setHTTPBody:[soapMessage dataUsingEncoding:NSUTF8StringEncoding]];

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

and the code I am using to call this method from the other class:

images = [ws callWebService:api :data];

        images = [ws returnArray];

now the problem is, that the second line is being executed before the first has finished


You do it easily as below,

-(void)aFunc {

Do Asynchronous A job...

while (A is not finished) {
// If A job is finished, a flag should be set. and the flag can be a exit condition of this while loop

// This executes another run loop.
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];

}

Do things using the A's result.

}


You could use one of many of the Cocoa design patterns (Delegate, Notification, etc).

For instance you would trigger the method and wait until you receive a response back.

It looks like you are using an asynchronous request and for this case, you would need to wait until one of the delegate methods get notified that the request has finished (with error or success).

BTW, what does your request look like? Could you share some code to explain how you do the request and when and what you want to do?

Edited after the code was inserted:

You set self as the delegate of the request, and so you should be able to handle the responses.

Have a look at the NSURLConnection Class Reference. You will need to trigger your parser when the request finishes on these methos, for example:

– connection:didReceiveResponse:
– connection:didReceiveData:
– connection:didFailWithError:

Cheers,

vfn

0

精彩评论

暂无评论...
验证码 换一张
取 消