2012-04-16 3 views
2

Я делаю приложение iPhone с помощью JavaScript. Я хочу открыть файл в качестве файла результата, и мне нужно написать некоторые журналы результатов и данные из javascript. С iphone я использую для использования documentsDirectory для открытия файла и выполнения операций чтения/записи. Но теперь я хочу сделать это в javascript. Теперь, как я могу использовать этот documentDirectory для записи файла и доступа к нему позже из Xcode. Любые предложения?Чтение файла записи из Javascript в проекте Xcode

Благодаря Akansha

Я использую следующий код YouTube API. Я создал файл с именем youtubeAPI.html и вызвал этот файл из объектного кода. Он успешно открывает страницу. Теперь я хочу открыть файл и написать что-то каждый раз, когда он изменит его состояние, а затем должен показать этот файл в конечном результате из obejective-c. Скажите, пожалуйста, как я могу это сделать.

<!DOCTYPE HTML> 
<html> 
<body> 
<div id="player"></div> 
<script> 
    //Load player api asynchronously. 
    var tag = document.createElement('script'); 
    tag.src = "http://www.youtube.com/player_api"; 
    var firstScriptTag = document.getElementsByTagName('script')[0]; 
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); 
    var done = false; 
    var player; 
    function onYouTubePlayerAPIReady() { 
     player = new YT.Player('player', { 
      height: '390', 
      width: '640', 
      videoId: 'JW5meKfy3fY', 
      events: { 
      'onReady': onPlayerReady, 
      'onStateChange': onPlayerStateChange 
      } 
     }); 
    } 
    function onPlayerReady(evt) { 
     evt.target.playVideo(); 
    } 
    function onPlayerStateChange(evt) { 
     if (evt.data == YT.PlayerState.PLAYING && !done) { // NEED TO ADD FILE OPERATION HERE 
      setTimeout(stopVideo, 6000); 
      done = true; 
     } 
    } 
    function stopVideo() { 
     player.stopVideo(); 
    } 
</script> 
</body> 
</html> 

ответ

0

Я написал файлы в PhoneGap, но никогда не обращался к нему с объектива c. Но я уверен, что любой файл, написанный в JS или Obj-C, написан в каталоге документов. За помощью вы можете проверить эту ссылку PhoneGap file writing и W3 File api. Примеры в PhoneGap просты в понимании, и я думаю, что он должен работать, поскольку использует W3 JS-файл api.

+0

, пожалуйста, проверьте мой отредактированный вопрос – Akansha

+0

, если я не хочу снова открывать файл в объективе C. Тогда как я могу просто писать и писать в файле из javascript в проекте xcode. – Akansha

0

Вот код, который я написал для чтения и записи в файловую систему, которая работает для меня. Обратите внимание, что fileWriter вернет абсолютный путь к файлу, но читателю файла нужен относительный путь, следовательно, метод getRelativePathToFile внизу.

function onPlayerStateChange(evt) { 
if (evt.data == YT.PlayerState.PLAYING && !done) { // NEED TO ADD FILE OPERATION HERE 

PG.saveToDisk('youTubeStateChange.txt', 'on player state change', 
    function (pathToFile){ 
    alert('file written to ' + pathToFile); 
    } 
); 

setTimeout(stopVideo, 6000); 
    done = true; 
} 
} 

// make error codes meaningful 
PG.FileErrors = { 
1:  'File not found', 
2:  'Security error', 
3:  'Action Aborted', 
4:  'File not readable', 
5:  'Encoding error', 
6:  'No modification allowed', 
7:  'Invalid state error', 
8:  'Syntax error', 
9:  'Invalid modification error', 
10: 'Quota Exceeded', 
11: 'Type mismatch', 
12: 'Path exists' 
}; 

// writes a file to the fileSystem 
// and sets the path to the file 
// which can be used in the callback 
// @param {} fileContent 
// @param {string} fileName 
// @param {function} callback 
PG.saveToDisk = function (fileContent, fileName, callback){ 
var pathToFile, 
    accessFileSystem = window.requestFileSystem; 

// something went wrong.. 
function fail (error){ 
    console.log('-- saveToDisk: error ' + error + ' ' + PG.FileErrors[error.code]); 
} 



// finally write to a file 
function gotFileWriter (writer){ 
    console.log('-- saveToDisk: gotFileWriter'); 

    // ..yaay! it worked 
    writer.onwrite = function (event){ 
    if(typeof callback == 'function'){ 
    console.log('-- saveToDisk: calling back'); 

    callback.call(this, pathToFile); 
    } 
    }; 

    // working it.. 
    writer.write(fileContent); 

    delete gotFileWriter; 
} 

// now that we have a location 
// on disk we can write to it.. 
function gotFileEntry (fileEntry){ 
    console.log('-- saveToDisk: gotFileEntry'); 

    pathToFile = fileEntry.toURI(); 

    // ..not quite 
    fileEntry.createWriter(gotFileWriter, fail); 

    delete gotFileEntry; 
} 

// get file for writing 
function getFileSystem (fileSystem){ 
    console.log('-- saveToDisk: getFileSystem'); 

    fileSystem.root.getFile(fileName, {create: true, exclusive: false}, gotFileEntry, fail); 

    delete getFileSystem; 
} 


if(typeof accessFileSystem != 'undefined'){ 
    console.log('-- saveToDisk: accessed file system'); 

    accessFileSystem(LocalFileSystem.PERSISTENT, 0, getFileSystem, fail); 

    // clean up as we go to save space in 
    // call stack and prevent 'call stack 
    // size exceeded' error 
    delete accessFileSystem; 
} else { 
    console.log('-- saveToDisk: no requestFileSystem so exiting'); 
} 

}; 

// get a file at a source from 
// disk and pass it to callback 
// @param {function} callback 
PG.getFromDisk = function (source, callback){ 
var accessFileSystem = window.requestFileSystem; 

// something went wrong.. 
function fail (error){ 
    console.log('-- getFromDisk: error ' + PG.FileErrors[error.code]); 
} 

//we read it 
// @param {string} method 
// defaults to text unless image is specified 
function readData (file, method){ 
    console.log('readDataUrl'); 

    var reader = new FileReader(), 
    method = method == 'image' ? 'readAsDataURL' : 'readAsText'; 

    reader.onloadend = function (event){ 
    if(typeof callback == 'function'){ 
    console.log('-- getFromDisk: calling back'); 

    callback.call(this, event.target.result); 
    } 
    }; 

    reader[method](file); 
} 

// what do we do with the file? 
function gotFile (file){ 
    console.log('-- gotFile'); 

    readData(file); 
} 

// get the file 
function gotFileEntry (fileEntry){ 
    console.log('-- gotFileEntry'); 

    fileEntry.file(gotFile, fail); 
} 

// get file reader 
function getFileSystem (fileSystem){ 
    console.log('-- getFileSystem: ' + source); 

    fileSystem.root.getFile(source, null, gotFileEntry, fail); 
} 

    // why did the fileSystem cross the road? 
    // so it could callback 4 times! 
if(typeof accessFileSystem != 'undefined'){ 
    accessFileSystem(LocalFileSystem.PERSISTENT, 0, getFileSystem, fail); 
} else { 
    console.log('-- getFromDisk: no requestFileSystem so exiting'); 
} 

}; 

// get relative path to saved file 
// because that is what the file 
// reader needs 
// @param {string} pathToFile 
PG.getRelativePathToFile = function (pathToFile){ 
if(/localhost|mnt/.exec(pathToFile)){ 
    var root = /localhost|mnt/.exec(pathToFile)[0]; 

    pathToFile = pathToFile.substring(pathToFile.indexOf(root)); 
    pathToFile = pathToFile.substring(pathToFile.indexOf('/')); 
} 

console.log('-- getRelativePathToFile: pathToFile = ' + pathToFile); 

return pathToFile; 
}; 
+0

Я отредактировал мой вопрос. PLease help – Akansha

+0

Что вы имеете в виду под изменениями? Всегда, когда вызывается функция onPlayerStateChange? Я обновил код, чтобы показать, как вы можете написать файл в JavaScript. Я не уверен, как вы откроете файл в объективе-C, но похоже, что вы уже это разработали. – Peter

+0

Nops, я не работал. Все еще борется с этим. Необходимо проверить, что можно сделать. Спасибо за вашу помощь. Я попытаюсь посмотреть, может ли ваш код использоваться для моей цели или нет. – Akansha

Смежные вопросы