因此,我正在获取此UIImage数据并将其转换为base64中的字符串。问题是它在转换时卡在UI线程上,我不确定为什么。

- (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];
        });

    });



}

最佳答案

试试下面的代码:

- (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];
    });
}

或者
- (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];
                });
            });
        });
    }

希望会有所帮助。如果您在服务器中上传图片,为什么不使用AFNetworking

关于ios - 编码图像时, dispatch 异步卡在主线程上,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19794936/

10-10 23:07