Pregunta

I need to pull data from a website and show that data on the pages.

I have standard PageViewController template.

I am trying to pull the data in my ModelController. In the init method of ModelController I fire the request, but it do not wait the connection to complete returns itself. So my array is empty.

My sample code is as below;

- (id)init
{
self = [super init];
if (self) {
    // Create the data model.

    // Create the request.
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"url"]];

    // Create url connection and fire request
    NSURLConnection *conn = [[NSURLConnection alloc]  initWithRequest:request delegate:self];
   }

  return self;
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

htmlString = [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];

NSArray * myArray = [htmlString  componentsSeparatedByString:@"}"];

_pageData = myArray;

NSLog(@"responsedata %@",htmlString);

}
¿Fue útil?

Solución

If you really want to make it synchronous, something like this is what your after:

NSURLRequest * urlRequest = [NSURLRequest requestWithURL:aURL];
NSURLResponse * response = nil;
NSError * error = nil;
NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];

However synchronous requests are generally not used for this. Its far more common to show some sort of loading to the user so they know whats going on. Network requests can take a long time to return (think crappy 3G signal), Having the user click a button and nothing happen until a netwrok request comes back is a bad idea

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top