Phonegap Camera Api не будет работать (не удалось загрузить ресурс)

Я использую телефонную связь версии 3.

Я установил cordova и phonegap, но по какой-то причине моя консоль показывает, что phonegap.js и cordova.js не загружаются. Их нет и в моей папке js, поэтому я подумал, что это довольно странно, но телефонная связь всегда работала для меня, до сегодняшнего дня, когда я попытался использовать их функцию API камеры. Я запустил команды установки плагина для камеры и добавил это в свой файл config.xml:

<feature name="Camera">
    <param name="ios-package" value="CDVCamera" />
</feature>

Но камера не работает ни в эмуляторе iOS, ни в веб-браузере. В веб-консоли я получаю эти ошибки.

Failed to load resource: The requested URL was not found on this server: file:///Users/thomas/dev/myapp/www/cordova.js

и когда я нажимаю на любую из кнопок, я получаю ошибку

TypeError: 'undefined' is not an object (evaluating 'navigator.camera.getPicture')

Вот мой код: (скопировано прямо с сайта phonegap)

<!DOCTYPE html>
<html>
  <head>
    <title>Capture Photo</title>

    <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
    <script type="text/javascript" charset="utf-8">

    var pictureSource;   // picture source
    var destinationType; // sets the format of returned value

    // Wait for device API libraries to load
    //
    document.addEventListener("deviceready",onDeviceReady,false);

    // device APIs are available
    //
    function onDeviceReady() {
        pictureSource=navigator.camera.PictureSourceType;
        destinationType=navigator.camera.DestinationType;
    }

    // Called when a photo is successfully retrieved
    //
    function onPhotoDataSuccess(imageData) {
      // Uncomment to view the base64-encoded image data
      // console.log(imageData);

      // Get image handle
      //
      var smallImage = document.getElementById('smallImage');

      // Unhide image elements
      //
      smallImage.style.display = 'block';

      // Show the captured photo
      // The inline CSS rules are used to resize the image
      //
      smallImage.src = "data:image/jpeg;base64," + imageData;
    }

    // Called when a photo is successfully retrieved
    //
    function onPhotoURISuccess(imageURI) {
      // Uncomment to view the image file URI
      // console.log(imageURI);

      // Get image handle
      //
      var largeImage = document.getElementById('largeImage');

      // Unhide image elements
      //
      largeImage.style.display = 'block';

      // Show the captured photo
      // The inline CSS rules are used to resize the image
      //
      largeImage.src = imageURI;
    }

    // A button will call this function
    //
    function capturePhoto() {
      // Take picture using device camera and retrieve image as base64-encoded string
      navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50,
        destinationType: destinationType.DATA_URL });
    }

    // A button will call this function
    //
    function capturePhotoEdit() {
      // Take picture using device camera, allow edit, and retrieve image as base64-encoded string
      navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 20, allowEdit: true,
        destinationType: destinationType.DATA_URL });
    }

    // A button will call this function
    //
    function getPhoto(source) {
      // Retrieve image file location from specified source
      navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50,
        destinationType: destinationType.FILE_URI,
        sourceType: source });
    }

    // Called if something bad happens.
    //
    function onFail(message) {
      alert('Failed because: ' + message);
    }

    </script>
  </head>
  <body>
    <button onclick="capturePhoto();">Capture Photo</button> <br>
    <button onclick="capturePhotoEdit();">Capture Editable Photo</button> <br>
    <button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">From Photo Library</button><br>
    <button onclick="getPhoto(pictureSource.SAVEDPHOTOALBUM);">From Photo Album</button><br>
    <img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
    <img style="display:none;" id="largeImage" src="" />
  </body>
</html>

person Thomas    schedule 23.08.2013    source источник


Ответы (3)


Я думаю, что отсутствует правильная структура папки www. Сейчас я не на работе, чтобы точно проверить имена, но:

<root_folder_name> / wwww
               index.html
                     /camera
                             index.html 
                  /plugins
                         /<camera plugin name>
                                               /test
                  /platform
                       /ios
                           /<projectname>.xcodeproj

или аналогичная структура, которую вы должны иметь. во всяком случае, из: plugins / <camerapluginmane> /test/ скопируйте папку index.html и camera с другой index.html в корневую папку www.

Также нужны main.css, main.js и cordova-incl.js все файлы находятся в тестовой папке.

Просто дважды проверьте исходный код /test/index.html и сделайте эту структуру и файлы доступными в корневой папке www.

Завтра или в понедельник я могу быть в офисе, чтобы отредактировать этот ответ и исправить имена.

Ваша ошибка: «TypeError:« undefined »не является объектом (оценка« navigator.camera.getPicture »» находится в веб-части (структура www), и вызов кода еще не перешел в файлы ios ( .h .m ) !

Я надеюсь, что это помогает!

person Community    schedule 23.08.2013
comment
в моей папке плагинов все, что у меня есть, это файл ios.json - person Thomas; 23.08.2013
comment
@ Томас, как я вижу, не стоит заморачиваться с твоей проблемой, удачи. - person ; 24.08.2013
comment
В итоге я это исправил. Я сделал новое приложение в phonegap, установил плагин камеры, а затем скопировал свои файлы, и это сработало. Хотя спасибо за помощь - person Thomas; 05.09.2013

Я знаю, что уже слишком поздно отвечать на этот вопрос, но для рабочего примера не поздно. Ниже код работал для меня.

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
    <meta name="format-detection" content="telephone=no" />
    <meta name="msapplication-tap-highlight" content="no" />
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />

  <title>Camera Demo</title>
  <link rel="stylesheet" type="text/css" href="css/style.css" />
  <script src="js/jquery-1.11.3.min.js"></script>

  <script type="text/javascript">

    var pictureSource;   // picture source
    var destinationType; // sets the format of returned value
    // Wait for Cordova to load
    document.addEventListener('deviceready', onDeviceReady, false);

    // Cordova is ready
    function onDeviceReady() {
      pictureSource=navigator.camera.PictureSourceType;
      destinationType=navigator.camera.DestinationType;
    }


    // Called when a photo is successfully retrieved  
    function onPhotoDataSuccess(imageData) {
      // Uncomment to view the base64-encoded image data
       console.log("  "+imageData);

      // Get image handle
      //
      var smallImage = document.getElementById('smallImage');

      // Unhide image elements
      //
      smallImage.style.display = 'block';

      // Show the captured photo
      // The inline CSS rules are used to resize the image
      //
      smallImage.src = "data:image/jpeg;base64," + imageData;
    }

    // Called when a photo is successfully retrieved
    //
    function onPhotoURISuccess(imageURI) {
      // Uncomment to view the image file URI
     //  console.log("IMAGE PATH: "+imageURI);
      alert("Image Url : "+imageURI);
      // Get image handle
      //
      var largeImage = document.getElementById('largeImage');

      // Unhide image elements
      //
      largeImage.style.display = 'block';



      // Show the captured photo
      // The inline CSS rules are used to resize the image
      //
      largeImage.src = imageURI;
    }

    // A button will call this function
    //
    function capturePhoto() {
      // Take picture using device camera and retrieve image as base64-encoded string
      navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50,
        destinationType: destinationType.DATA_URL });
    }

    // A button will call this function
    //
    function capturePhotoEdit() {
      // Take picture using device camera, allow edit, and retrieve image as base64-encoded string
      navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 20, allowEdit: true,
        destinationType: destinationType.DATA_URL });
    }

    // A button will call this function
    //
    function getPhoto(source) {
      // Retrieve image file location from specified source
      navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50,
        destinationType: destinationType.FILE_URI,
        sourceType: source });
    }

    // Called if something bad happens.
    //
    function onFail(message) {
      alert('Failed because: ' + message);
    }
  </script>
</head>
<body>  
<header class="header">
<div class="header-div">
  <div class="header-single">
    <span id="title">Details </span>
  </div>
</div>
</header>
<div class="clear">
</div>
<content class="content-style">
 <h2> Camera Demo</h2>

  <button class="demo-btn-style" onclick="capturePhoto();">Capture Photo</button> <br>
  <button class="demo-btn-style" onclick="capturePhotoEdit();">Capture Editable Photo</button> <br>
  <button class="demo-btn-style" onclick="getPhoto(pictureSource.PHOTOLIBRARY);">From Photo Library</button><br>
  <button class="demo-btn-style" onclick="getPhoto(pictureSource.SAVEDPHOTOALBUM);">From Photo Album</button><br>
  Small image: <br>
  <img style="display:none;width:100px;height:100px;" id="smallImage" src="" /> <br>
  Large image: <br>
  <img style="display:none;" id="largeImage" src="" /> <br>

</content>

<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>

</boyd>
</html>
person IPL10    schedule 03.03.2016
comment
На Android мне пришлось добавить в config.xml: ‹access origin=content:///* /›, хотя ‹access origin=* /› уже был установлен - person Elia Weiss; 12.03.2016

В терминале, в основной папке моего приложения, я запустил cordova plugin add cordova-plugin-camera. Я установил его в свой браузер с помощью PhoneGap, но мне, видимо, нужно было сделать это снова, чтобы установить его для версии iOS, созданной XCode.

Plugin "cordova-plugin-camera" already installed on browser. Installing "cordova-plugin-camera" for ios

Это добавило файлы .h и .m в папку моих платформ-> ios-> APPNAME-> plugins.

Теперь все работает!

person Ian    schedule 29.09.2016