iOS, NSURLConnection: Delegate Callbacks on Different Thread?

后端 未结 4 1421
借酒劲吻你
借酒劲吻你 2020-12-28 10:20

How can I get NSURLConnection to call it\'s delegate methods from a different thread instead of the main thread. I\'m trying to mess around with the scheduleInRunLoop:forMod

4条回答
  •  误落风尘
    2020-12-28 10:54

    If you want to perform downloads on a separate thread, I'm pretty sure these are the droids you're looking for...

    - (void) dispatchRequest{
        self->finished = NO;
        NSMutableURLRequest* request = //Formulate your request
        NSThread* download_thread = [[NSThread alloc] initWithTarget:self selector:@selector(downloadThreadLoop:) object:request];
        [download_thread start];
    }
    - (void) downloadThreadLoop:(NSMutableURLRequest*) request{
    
        NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    
        while(!self->finished]){
            //This line below is the magic!
            [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
        }
    }
    
    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
        //...
    }
    
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
        //...
    }
    
    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
        //...   
    }
    
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection{
        //...   
        self->finished = YES;
    }
    

提交回复
热议问题