我正在尝试将服务器中的数据加载到id结果变量中,我的url工作正常,我可以在浏览器上看到数据,但数据加载过程非常慢(15秒),结果得到输出数据的结果是零
类:MyWebservices: -
-(id)getResponseFromServer:(NSString*)requestString
{
id result;
NSError *error;
NSURLResponse *response = nil;
NSURL *url = [NSURL URLWithString:[requestString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
NSData * resultData= [[NSData alloc]init];
resultData = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
类:WebserviceCallingClass
- (void)viewDidLoad
{
id result = [AppDelegate.MyWebservices getResponseFromServer:urlString] ;
}
答案 0 :(得分:1)
使用异步请求。
1)使用NSURLConnectionDelegate并声明 在你的接口类a:
NSMutableData *_responseData;
2)发送异步请求并在超时间隔内设置一个大于15秒的时间
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://uri"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20];
conn = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
[conn scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
[conn start];
3)实施你的委托方法
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// A response has been received, this is where we initialize the instance var you created
// so that we can append data to it in the didReceiveData method
// Furthermore, this method is called each time there is a redirect so reinitializing it
// also serves to clear it
_responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Append the new data to the instance variable you declared
[_responseData appendData:data];
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse*)cachedResponse {
// Return nil to indicate not necessary to store a cached response for this connection
//NSLog(@"cache");
return nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// The request is complete and data has been received
// You can parse the stuff in your instance variable now
}
}
或在同步请求中尝试编辑您的NSMutableURLRequest
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.f];