Discussion of the 'didReceiveData' Method for an HTTP Connection

I created an independent class for an HTTP connection. All connection is working fine. The problem is that I find the “didReceiveData” method that will be called AFTER the method that calls the connection. (the "didReceiveData" method will be called after the IBAction "accept")


- (IBAction)accept:(id)sender {
    [self connect:url];
    //labelStr = ReturnStr; Cannot be written here. 
}

-(void)connect:(NSString *)strURL
{
    NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:strURL]
                                              cachePolicy:NSURLRequestUseProtocolCachePolicy
                                          timeoutInterval:60.0];

    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    if (theConnection) 
    {
        // receivedData is declared as a method instance elsewhere
        receivedData = [[NSMutableData data] retain];
    } 
    else 
    { 
        // inform the user that the download could not be made
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // append the new data to the receivedData
    [receivedData appendData:data];
    ReturnStr = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
}

This will cause a problem: if I want to change the label text to the received string, the code cannot be written in the IBAction "accept", but must be written in the "didReceiveData" method as follows:


    MainViewController *mainView = [[MainViewController alloc] initWithNibName:@"MainView" bundle:nil];
    AMEAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    [delegate.navController pushViewController:mainView animated:YES];
    mainView.labelStr.text = ReturnStr;

Another problem is that the data in the MainView will be overwritten if I initialize the MainView to 'didReceiveData'. Is it possible to change labelStr text without initializing MainView?

+3
4

, , NSURLConnection sendSynchronousRequest:returningResponse:error:. , , , , , , .

+1

, 'didReceiveData', , . ( "didReceiveData" IBAction "accept" )

, connection:didReceiveData:, ?

: , IBAction "accept", "didReceiveData"...

. , , .

, MainView , MainView 'didReceiveData'. labelStr MainView?

connection:didReceiveData: . , connection:didReceiveData: , labelStr.text.

BTW, connection:didReceiveData:, ReturnStr. , .

+2

NSURLConnection and other similar classes are intended to be used asynchronously.

initWithRequest: delegate: returns immediately and you are not annoyed by the connection material until it sends delegate methods to its delegate.

0
source

Using NSMutableData instead of NSData.

0
source

Source: https://habr.com/ru/post/1704810/


All Articles