jimbob
jimbob

Reputation: 3298

dispatch async hangs on main thread while encoding image

So I am taking this UIImage data and and converting to a string in base64. the problem is that it hangs on the UI thread whilst converting and I am not sure why.

- (void)processImage:(UIImage*)image{


    dispatch_queue_t myQueue = dispatch_queue_create("My Queue",NULL);
    [self.spinnerOutlet setAlpha:0.0f];
    [self.spinnerOutlet startAnimating];
    dispatch_async(myQueue, ^{

        // Convert image
        NSData *myData = [UIImagePNGRepresentation(image) base64EncodedDataWithOptions:NSDataBase64Encoding64CharacterLineLength];
        NSString *myString = [NSString stringWithUTF8String:[myData bytes]];

        dispatch_async(dispatch_get_main_queue(), ^{
            // Update the UI

            [self showSuccessAlertView:@"Success!" message:@"Submitting Image..."];
            snapShotInBase64 = myString;
            [self sendImagePostRequest];
        });

    });



}

Upvotes: 2

Views: 631

Answers (1)

user2828120
user2828120

Reputation: 233

Try this code:

- (void)processImage:(UIImage*)image{

    dispatch_queue_t myQueue = dispatch_queue_create("My Queue",NULL);
    [self.spinnerOutlet setAlpha:0.0f];
    [self.spinnerOutlet startAnimating];
    dispatch_async(myQueue, ^{

        // Convert image
        NSData *myData = [UIImagePNGRepresentation(image) base64EncodedDataWithOptions:NSDataBase64Encoding64CharacterLineLength];
        NSString *myString = [NSString stringWithUTF8String:[myData bytes]];
        snapShotInBase64 = myString;

        dispatch_async(dispatch_get_main_queue(), ^{
            // Update the UI
            [self showSuccessAlertView:@"Success!" message:@"Submitting Image..."];
        });
    });

    dispatch_barrier_async(myQueue, ^{
        [self sendImagePostRequest];
    }); 
}

or

- (void)processImage:(UIImage*)image{

        dispatch_queue_t myQueue = dispatch_queue_create("My Queue",NULL);
        [self.spinnerOutlet setAlpha:0.0f];
        [self.spinnerOutlet startAnimating];
        dispatch_async(myQueue, ^{

            // Convert image
            NSData *myData = [UIImagePNGRepresentation(image) base64EncodedDataWithOptions:NSDataBase64Encoding64CharacterLineLength];
            NSString *myString = [NSString stringWithUTF8String:[myData bytes]];
            snapShotInBase64 = myString;

            dispatch_async(dispatch_get_main_queue(), ^{
                // Update the UI
                [self showSuccessAlertView:@"Success!" message:@"Submitting Image..."];
                dispatch_async(myQueue, ^{
                      [self sendImagePostRequest];
                });
            });
        }); 
    }

hope will help. If you upload image in server, why you don`t use AFNetworking library

Upvotes: 1

Related Questions