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

unable to load data from webservice into id type of variable

我正在尝试将数据从服务器加载到 id 结果变量中,我的 url 工作正常我可以在浏览器上看到数据,但是数据加载过程非常慢(15 秒)和结果获取输出数据 id 结果为 nil

Class:我的网络服务:-

-(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]; 

Class: 网络服务调用Class

 - (void)viewDidLoad
  {

id result =  [AppDelegate.MyWebservices  getResponseFromServer:urlString] ;

}

使用异步请求。

1) 使用 NSURLConnectionDelegate 并声明 在你的界面 class 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];