long polling in objective-C

前端 未结 2 1381
心在旅途
心在旅途 2020-11-30 22:25

I have an application that uses an API to get real time updates on the website. They use what they call a long-polling technique:

Long polling is a v

2条回答
  •  日久生厌
    2020-11-30 22:49

    This is exactly the sort of use-case that NSURLConnection sendSynchronousRequest is perfect for:

    - (void) longPoll {
        //create an autorelease pool for the thread
        NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    
        //compose the request
        NSError* error = nil;
        NSURLResponse* response = nil;
        NSURL* requestUrl = [NSURL URLWithString:@"http://www.mysite.com/pollUrl"];
        NSURLRequest* request = [NSURLRequest requestWithURL:requestUrl];
    
        //send the request (will block until a response comes back)
        NSData* responseData = [NSURLConnection sendSynchronousRequest:request
                                returningResponse:&response error:&error];
    
        //pass the response on to the handler (can also check for errors here, if you want)
        [self performSelectorOnMainThread:@selector(dataReceived:) 
              withObject:responseData waitUntilDone:YES];
    
        //clear the pool 
        [pool drain];
    
        //send the next poll request
        [self performSelectorInBackground:@selector(longPoll) withObject: nil];
    }
    
    - (void) startPoll {
        //not covered in this example:  stopping the poll or ensuring that only 1 poll is active at any given time
        [self performSelectorInBackground:@selector(longPoll) withObject: nil];
    }
    
    - (void) dataReceived: (NSData*) theData {
        //process the response here
    }
    

    Alternately, you could use async I/O and delegate callbacks to accomplish the same thing, but that would really be kind of silly in this case.

提交回复
热议问题