Serg Metelin
Serg Metelin

Reputation: 1114

HTML/JS upload of images from camera on iOS6

I have this snippet:

<script>
        var reader = new FileReader();
        reader.onload = (function(theFile) {
            return function(e) {
                // Render thumbnail.
                var span = document.createElement('span');
                span.innerHTML = ['<div id="wrap"><img id="image" class="thumb draggable" src="', e.target.result,
                    '" title="', escape(theFile.name), '" draggable="true" /></div>'].join('');
                document.getElementById('list').insertBefore(span, null);
            };
        })(f);

        // Read in the image file as a data URL.
        reader.readAsDataURL(f);

I'm using it in a mobile app for iOS, that captures the data from camera and shows a preview in a div. Everything works fine except first time I'm loading an app on new device without approval to access photos (it prompts for it the first time you're trying to take a photo).

The problem here is that when I call reader.readAsDataURL(f); before the user approved access to user's photos, reader.onload is not triggered.

Is there any listener for user's approval or maybe there is a way to prompt a user with access to camera on page load?

Thanks

Upvotes: 2

Views: 157

Answers (1)

Graham Robertson
Graham Robertson

Reputation: 818

I believe the issue here is two fold.

First, I assume we're listening to some sort of onchange event on the <input type="file" /> tag that invokes the camera/user photos to then invoke this code that reads the file. If not, we should definitely be doing that as that's what will wait for the proper event.

Lastly, we're passing f as an argument to the anonymous function which, in some sort of code inception, returns another anonymous function that becomes our actual event listener. The problem wouldn't be at invoking the file at reader.readAsDataURL(f); seeing that you use f as an argument first in reader.onload.

Seeing that f is in a higher scope than the reader.onload event, we should be able to do the following:

reader.onload = function(e) {
    // Render thumbnail.
    var span = document.createElement('span');
    span.innerHTML =
        ['<div id="wrap"><img id="image" class="thumb draggable" src="',
        e.target.result, '" title="', escape(f.name), // we use f, not theFile
        '" draggable="true" /></div>'].join('');
    document.getElementById('list').insertBefore(span, null);
};

Above, we eliminate our function inception and simply reference the f that's already in scope. This function also won't execute unless we have permission, so this should clear up your initial use-case issue.

Upvotes: 1

Related Questions