Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Start with creating an empty Alloy project by executing this command: appc new

Permissions

For security reasons, both Android and iOS platforms need to ask the user access the camera. Android, the build system will automatically add the needed "android.permission.CAMERA" and "android.permission.WRITE_EXTERNAL_STORAGE" permissions to the AndroidManifest.xml for you. So, you don't need to edit the tiapp.xml file.

For iOS, you need to add a the following key(s) to the tiapp.xml:

Code Block
linenumberstrue
languagexml
<ios>
    <plist>
        <dict>
            <key>NSCameraUsageDescription</key>
            <string>To<string>Need takecamera a picture we want access to usetake the camera<pictures</string>

            <!-- Only needed for video when recording audio, such as via camera video capture. -->
            <key>NSCameraUsageDescription<<key>NSMicrophoneUsageDescription</key>
            <string>For<string>Need Videomicrophone recordingaccess weto wantrecord tovideo usewith the microphone<audio</string>
        </div>
    </plist>
</ios>

For Android, the following needs to be added to the manifest:

...

Say cheese

It is time to open the camera! We add a simple button to our view and add a click event to it, so we can open the camera.

Code Block
titleSimple button
linenumberstrue
languagexml
<android xmlns:android="http://schemas.android.com/apk/res/android"><Alloy>
    <Window>
<manifest>         <uses-permission android:name="android.permission.CAMERA"/>

        <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"<Button id="btn_record" title="Take a picture" onClick="onClickRecord" />
    </manifest>Window>
</android>

Then, inside the app itself, we need to ask for permission again which the users has to accept or decline.

Titanium has built-in functions to request these permissions. Since it might be handy to use this in other apps too, we need to create an external library and include the code there, so we can use this file in other apps as well. To do this, you have to create a lib folder at /app/lib/ and inside this folder, create a new file called helper.js.

There we add our getPermissions() script:

Code Block
languagejs
exports.getPermissions = function(opt) {
	//
}

The code for Android and iOS is a bit different. We need to check for the platform and ask for the specific platform permission.

Code Block
linenumberstrue
languagejs
exports.getPermissions = function(opt) {
    if (OS_ANDROIDAlloy>

The below code implements the button click event to request camera permission (if not currently granted) and then show the camera.

Code Block
titleClick event
languagejs
function onClickRecord(e) {
        // AndroidRequest part
        var permissions = ['android.permission.CAMERA', 'android.permission.READ_EXTERNAL_STORAGE'];
        var hasPermission = Ti.Android.hasPermission(permissions);the user's permission to use the camera.
         // checkIf ifalready thegranted, permissionsthen arecallback alreadywill allowedbe invoked without showing dialog.
    ifTi.Media.requestCameraPermissions(function (hasPermissione) {
            // runDo callbacknot continue            opt();
            return;
        }
        // no permission - request it
        Ti.Android.requestPermissions(permissions, function(e) {if permission was denied.
              if (!e.successssuccess) {
            alert('This app does not //have runpermission callbackto use the camera.');
             opt()return;
            }
else
{                 // askShow againthe camera for taking a picture.
           exports.getPermissions(opt);Ti.Media.showCamera({
            }success:         });
    } else function (e) {
        // iOS part         var map = {};
        map[Ti.Media.CAMERA_AUTHORIZATION_AUTHORIZED] = 'CAMERA_AUTHORIZATION_AUTHORIZED';
        map[Ti.Media.CAMERA_AUTHORIZATION_DENIED] = 'CAMERA_AUTHORIZATION_DENIED'console.log('Photo was successfully taken via camera.');
        map[Ti.Media.CAMERA_AUTHORIZATION_RESTRICTED] = 'CAMERA_AUTHORIZATION_RESTRICTED';         map[Ti.Media.CAMERA_AUTHORIZATION_NOT_DETERMINED] = 'CAMERA_AUTHORIZATION_NOT_DETERMINED';

        var cameraAuthorization = Ti.Media.cameraAuthorization;
   // $.imageView.image = e.media; // do this to
    if (cameraAuthorization === Ti.Media.CAMERA_AUTHORIZATION_RESTRICTED) {    },
        return;    cancel:     } else if (cameraAuthorization === Ti.Media.CAMERA_AUTHORIZATION_DENIEDfunction (e) {
            return;         }
        Ti.Media.requestCameraPermissions(function(e) {
            if (e.success) {console.log('Camera canceled.');
            },
    // run callback      error:           opt();
            } else function (e) {
                // ask again
                exports.getPermissions(optconsole.error('Failed to show camera. Reason: ' + e.error);
            }         });
    }
}

Say cheese

Now that we can ask for the permission, it is time to open the camera! We add a simple button to our view and add a click event to it, so we can open the camera.

Code Block
titleSimple button
linenumberstrue
languagexml
<Alloy>
    <Window>if (e.code === Titanium.Media.NO_CAMERA) {
          <Button id="btn_record" title="Take a picture" />     </Window>
</Alloy>
Code Block
titleClick event
languagejs
function onClickRecord(e) {}

$.btn_record.addEventListener("click",onClickRecord);
$.index.open();

Next, we should call our getPermissions() helper script. Once we have the correct permission, we can open the camera. To use the lib/helper.js, we need to  require() it:

Code Block
languagejs
var helper = require("/helper");

Then use all export functions:

Code Block
languagejs
helper.getPermissions(function( ){});

The last part is opening the camera:

Code Block
languagejs
Ti.Media.showCamera({});

Complete code should look something like this:

Code Block
titleComplete click event
linenumberstrue
languagejs
var helper = require("/helper");

function onClickRecord(e) {
    helper.getPermissions(function( ){
        // permission grantedalert('Device does not have a camera.');
                }
            }
   // open the camera         Ti.Media.showCamera({});
    });
}

$.btn_record.addEventListener("click",onClickRecord);
$.index.open();

If you click the button now, it will ask you for camera and storage permission the first time and then open the camera.

The showCamera() method has some properties you can set to change some options and to get the image. For a full list, please review CameraOptionsType API documentation.

The most common option is the success callback. This will be called after the images was taken and you can get the actual image to show it in your app or store it.

Code Block
linenumberstrue
languagejs
Ti.Media.showCamera({
    success: function(e) {
        // display image information:
        console.log(e.media);
        // $.imageView.image = e.media; // to put it into an imageview
    }
})

You can also add a custom overlay to the camera with overlay. When you set an overlay, it won’t run the normal camera as an intent, but it will create a custom camera view for you. You have to take care of the actions/buttons (with the overlay property which is assigned a view. When doing this, you have to display your own buttons to take a picture or cancel out and use the Ti.Media.takePicture(), and Ti.Media.hideCamera(),…) yourself! overlay accepts a view as a parameter functions. On Android, using an overlay will display an in-app camera activity instead of displaying the default camera app installed on the device for taking photos.

 

This tutorial was adapted from https://devblog.axway.com/mobile-apps/from-zero-to-app-with-a-camera/ which was originally written by Michael Gangolf