这是我的应用程序的逻辑流程:
首先,当视图控制器完成加载时,NSURLConnection
请求可以开始执行
响应包含xml数据
解析该xml后,我需要发送另一个NSURLConnection
请求。
发送第二个请求后,如果响应正常,我会收到其他xml数据
在解析第二个xml之后,我必须检查第一个和第二个xml数据之间的一些问题。
那么,是否可以发送多个请求?怎么样?我不需要代码,你可以解释一下。
提前谢谢。
答案 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
}
}
}
希望这会帮助你更好地理解......