How to make program wait for asynchronous NSURLConnection to finish before proceeding with next command?

后端 未结 6 1795
日久生厌
日久生厌 2021-02-01 09:10

How can I make my program wait for an asynchronous NSURLConnection to finish before going to the next line of code?

SetDelegate *sjd= [SetDelegate alloc];
NSURLC         


        
6条回答
  •  逝去的感伤
    2021-02-01 09:19

    This golden nugget helped me! I was using synchronous NSURL just fine until I decided I needed SSL for my connection between my client and my server. I took the approach of key pinning which is comparing the cert on the device to the cert on the server (read more on link above) and in order for it to work I needed to add code to the NSURL methods, which from my research you can't do with NSURL synchronous. Until I found this ridiculously simple solution which worked for me:

    NSString *connectionRunLoopMode = @"connectionRunLoopMode";
    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:urlRequest delegate:urlConnectionDelegate startImmediately:NO];
    NSRunLoop *currentRunLoop = [NSRunLoop currentRunLoop];
    [connection unscheduleFromRunLoop:currentRunLoop forMode:NSDefaultRunLoopMode];
    [connection scheduleInRunLoop:currentRunLoop forMode:connectionRunLoopMode];
    [connection start];
    while ([currentRunLoop runMode:connectionRunLoopMode beforeDate:[NSDate distantFuture]]);
    

提交回复
热议问题