NSData writeToFile not fully written while reading

I am writing an iPhone application that allows you to view images in one view and create them in another.

In the view that creates the image, the image will be written to the document folder using the following code (when you click the button to reject the view):

[UIImagePNGRepresentation(image) writeToFile:path atomically:YES]; 

An image will be loaded in the browser using:

 UIImage *image = [UIImage imageWithContentsOfFile:path]; 

Now it works fine 9 out of 10 times. 1 out of 10 the image is not written completely before uploading it so that the bottom half is black. Everything will be recorded in the end - if I reload the image in the browser, the full image will be shown. I thought that these things would always be consistent within the same thread.

Can I do something to prevent this behavior?

Now Iā€™m thinking about transferring the newly created image back to the browser, but this seems like a hack since the browser displays all of your previously created images.

+2
source share
2 answers

If you are sure that the image is saved in the main (UI) stream using writeToFile:atomically: and the image is then loaded into the main stream as well, then there seems to be a problem with this method supporting its contract to complete the operation at the time the call returns. IOS sometimes has bugs, and maybe you found them.

However, I will also note that one of the possible ways of causing such problems occurs when assumptions are made about the order in which viewWillAppear , viewDidDisappear , etc. called, leaving one view to display another. That way, I also made sure that the image is not saved in one of these methods.

Since you said that the problem shows an image that is half visible, I would suggest that it is not, but I am turning on a warning for someone else with a similar problem with the order of operations.

+2
source

The standard solution for a process that does not end in time for the user interface is to split it into a new thread. You may need to create a separate stream to save the image, and then notify the user interface through the delegate method in order to update it.

+1
source

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


All Articles