提问者:小点点

无法将数据从webservice加载到id类型的变量中


我正在尝试从服务器加载数据到id结果变量,我的url运行良好,我可以在浏览器上看到数据,但是数据加载过程非常慢(15秒),结果得到的输出数据id结果为零

Class: 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] ;

}


共1个答案

匿名用户

使用异步请求。

1)使用NSURLConnection代理并在您的接口类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];