Search code examples
objective-cmacosasihttprequestxpc

ASIHTTPRequestDelegate methods not called in XPC service


I am using the excellent ASIHTTPRequest inside an XPC service to fetch some data from the internet.

I am creating a simple request. However, for some reason, it's delegate functions are not called. I have enabled ASIHTTPRequest's debugging log and so I see that the request does execute. After digging in a bit,I found what might be the cause:

inside ASIHTTPRequest.m, in the end of the requestFinished method, there's a call:

[self performSelectorOnMainThread:@selector(reportFinished) withObject:nil waitUntilDone:[NSThread isMainThread]];

the reportFinished method is the method that calls the delegate. For some reason, it is never fired. If I replace this line with:

//[self performSelectorOnMainThread:@selector(reportFinished) withObject:nil waitUntilDone:[NSThread isMainThread]];
[self reportFinished];

then the delegate is called. However, i assume it is called on the wrong thread as im running async requests.

What should I do to adapt the code so that it invokes the delegate's methods, without modifying the logic/threading of it?


Solution

  • I would suggest converting the statement:

    [self performSelectorOnMainThread:@selector(reportFinished) withObject:nil waitUntilDone:[NSThread isMainThread]];
    

    into this, which should be semantically equivalent:

    if ([NSThread isMainThread]) {
        [self reportFinished];
    } else {
        dispatch_sync(dispatch_get_main_queue(),
                       ^{
                           [self reportFinished];
                       });
    }
    

    or simply this, which should also work:

    dispatch_sync(dispatch_get_main_queue(),
                       ^{
                           [self reportFinished];
                       });