Asynchronous request to the server from background thread

前端 未结 3 1169
北海茫月
北海茫月 2020-12-04 07:01

I\'ve got the problem when I tried to do asynchronous requests to server from background thread. I\'ve never got results of those requests. Simple example which shows the pr

3条回答
  •  自闭症患者
    2020-12-04 08:02

    You can start the connection on a background thread but you have to ensure the delegate methods are called on main thread. This cannot be done with

    [[NSURLConnection alloc] initWithRequest:urlRequest 
                                    delegate:self];
    

    since it starts immediately.

    Do this to configure the delegate queue and it works even on secondary threads:

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:urlRequest 
                                                                  delegate:self 
                                                          startImmediately:NO];
    [connection setDelegateQueue:[NSOperationQueue mainQueue]];
    [connection start];
    

提交回复
热议问题