Domanda

I am trying to use some objective c code to upload an image and some text data to my webserver which all works fine. I was just trying to add a basic progress indication "text box" to my display to show the progress i.e say "uploading"

I am using the following code in a buttons IBAction to kick off the upload

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

This effectively stops me from being able to update a text description box (or any screen parameter) until the upload has finished (by the nature of a synchronous action i suppose) How can I update some screen parameters prior to the upload starting (but still within the buttons IBAction)?

È stato utile?

Soluzione

sendSynchronousRequest is, as the name indicates, synchronous and therefore blocks the current thread. Since all UI updates are only done when program control returns to the main event loop, you have to move the upload to a separate thread, for example like this:

self.progressLabel.text = @"Uploading...";
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
        NSData *returnData = [NSURLConnection sendSynchronousRequest:...];

        // UI activity must be done on the main thread again:
        dispatch_async(dispatch_get_main_queue(),^{
            self.progressLabel.text = @"Done.";
        });
    });

Alternatively, you can use [NSURLConnection sendAsynchronousRequest:...].

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top