How to handle changing paths in Xamarin.iOS - ios

I'm at the state where I need to load Images taken from camera/gallery.
I'm creating a directory this way:
var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var library = Path.Combine(documents, "..", "Library");
var userDirectory = Path.Combine(library, directoryname);
Directory.CreateDirectory(userDirectory);
So when I'm saving Images in userdirectory and the path to that image I cannot load it after restarting the app.
How would you handle this path problem?
EDIT:
when loading from album this way:
var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var library = Path.Combine(documents, "..", "Library");
var userDirectory = Path.Combine(library, CurrentUser.Username);
var ImageDirectory = Path.Combine(userDirectory, "ImageDirectory");
string imageuuid = Guid.NewGuid().ToString();
string ImageFilename = Path.Combine(ImageDirectory, imageuuid + ".jpg");
After that I check if the Image exists and I can see it everytime.
The Path is:
/Users/exampleuser/Library/Developer/CoreSimulator/Devices/E84B5B50-BA6C-44C2-A755-3A0E96DE20F8/data/Containers/Data/Application/1B287E75-317B-4671-8A16-97F5EA5E27F5/Documents/../Library/userDirectory/ImageDirectory/63408be0-cc49-495f-bc20-e9d90e240597.jpg
I'm closing the app completely and restart and the path to the Image changed to:
/Users/exampleuser/Library/Developer/CoreSimulator/Devices/E84B5B50-BA6C-44C2-A755-3A0E96DE20F8/data/Containers/Data/Application/7AACA518-20BE-4276-B29F-9059CAB1B957/Library/userDirectory/ImageDirectory/63408be0-cc49-495f-bc20-e9d90e240597
As you see after Data/Application it changes.
After the selection of an Image I save the path. But when I'm loading it can't find the path to that image.

Related

What is the correct way to obtain the Resource folder path from the running iOS / macOS app instance (Xamarin Forms)

I am having difficulties copying some files from my application Resources folder:
var myDocuments = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Library");
// Confirm these paths are OK for iOS too
var root = Path.Combine(myDocuments, "VisitsRota.MacOS");
var styles = Path.Combine(root, "Styles");
var stylesheet = Path.Combine(styles, "ElderlyInfirm-Schedule-v1.css");
var db = Path.Combine(root, "ElderlyInfirmRotaData.xml");
var defaultroot = Path.Combine( ".", "Resources");
// Main folder
if (!Directory.Exists(root))
{
Directory.CreateDirectory(root);
}
// Database
if (!File.Exists(db))
{
var defaultdb = Path.Combine(defaultroot, "ElderlyInfirmRotaData.xml");
File.Copy(defaultdb, db);
}
// Styles folder
if (!Directory.Exists(styles))
{
Directory.CreateDirectory(styles);
}
// Stylesheet
if (!File.Exists(stylesheet))
{
var defaultstylesheet = Path.Combine(defaultroot, "Styles", "ElderlyInfirm-Schedule-v1.css");
File.Copy(defaultstylesheet, stylesheet);
}
The problem is determining the application folders Resources folder, At the moment I get this exception:
What is the correct way to get to the Resources folder (for either iOS or macOS)?
In the IDE I only see just the one Resource folder:
Both of my resources have a Build Action set to Content.
Thank you for pointing me in the right direction to resolve this.
I tried using the result from:
public static string GetExecutingDirectoryName()
{
var location = new Uri(Assembly.GetEntryAssembly().GetName().CodeBase);
return new FileInfo(location.AbsolutePath).Directory.FullName;
}
It was completely wrong.
I am running the app in the Debugger in VS for Mac (macOS build).
I assume that using the Resource folder for these files was OK. Unless there is a better way to do this?
It was much easier to use BundleResource:
var myDocuments = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Library");
// Create the folders first
// Main folder
var root = Path.Combine(myDocuments, "VisitsRota.MacOS");
if (!Directory.Exists(root))
{
Directory.CreateDirectory(root);
}
// Styles folder
var styles = Path.Combine(root, "Styles");
if (!Directory.Exists(styles))
{
Directory.CreateDirectory(styles);
}
// Now copy the files
// Database
var db = Path.Combine(root, "ElderlyInfirmRotaData.xml");
var defaultdb = NSBundle.MainBundle.PathForResource("ElderlyInfirmRotaData", ofType: "xml");
if (!File.Exists(db))
{
File.Copy(defaultdb, db);
}
// Stylesheet
var stylesheet = Path.Combine(styles, "ElderlyInfirm-Schedule-v1.css");
var defaultstylesheet = NSBundle.MainBundle.PathForResource("ElderlyInfirm-Schedule-v1", ofType: "css");
if (!File.Exists(stylesheet))
{
File.Copy(defaultstylesheet, stylesheet);
}

Jquery upload file: get duration of video

I use jquery upload file and console.log result :
https://drive.google.com/file/d/0BxOsysEbbmMOSkZXb3NfdEFQQ2s/view?pli=1
I got info file upload in original Files :
var file = data.originalFiles[0];
var postSize = file.size;
var filename = file.name;
var lastModified = file.lastModifiedDate;
But cannot get :
var preview = file.preview;
How to get duration length of file from file.preview?

how to get image file type from ios gallery Titanium Appcelerator

I want get the name of the image type like i selected .png ,.gif ...etc,I need to get the name of the selected from iOS gallery.For that i am using the following code snippet.
Titanium.Media.openPhotoGallery({
success:function(event)
{
var cropRect = event.cropRect;
image = event.media;
if(event.mediaType == Ti.Media.MEDIA_TYPE_PHOTO)
{
var newImageName = new Date().getTime() + ".jpg";
//var newImageName = new Date().getTime();
var filename = Titanium.Filesystem.applicationDataDirectory + "/" + newImageName;
Ti.App.Properties.setString("filename", filename);
newImage = Titanium.Filesystem.getFile(filename);
newImage.write(image);
}
through every file is converted to jpg format .I want get the what every file extension in gallery.

how to create .txt in local file system using Firefox extension

I am currently working on ffsniff extension code. In that I have to save data containing password information into a file in my local system. I have written my code but it is not even creating the file in my local system. (working in mozilla firefox)
Here is my code please help me out.
//// here data variable contains all the information
var fso = new ActiveXObject("Scripting.FileSystemObject");
varFileObject = fso.OpenTextFile("C:\\logs.txt", 2, true,0);
varFileObject.write(data);
varFileObject.close();
after this i tried different code:
Components.utils.import("resource://gre/modules/NetUtil.jsm");
Components.utils.import("resource://gre/modules/FileUtils.jsm");
var file = Components.classes["#mozilla.org/file/directory_service;1"].
getService(Components.interfaces.nsIProperties).
get("Desk", Components.interfaces.nsIFile);
file.append("logs.txt");
var ostream = FileUtils.openSafeFileOutputStream(file)
var converter = Components.classes["#mozilla.org/intl/scriptableunicodeconverter"].
createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
converter.charset = "UTF-8";
var istream = converter.convertToInputStream(data);
}
});
but none of them is working..
Here's a working snippet that creates the destination directory if necessary and writes (overwrites) to file (in this case d:\temp-directory\temp-file.txt):
var {Cc,Ci,Cu}=require("chrome"); //for jetpack sdk.
Cu.import("resource://gre/modules/NetUtil.jsm");
Cu.import("resource://gre/modules/FileUtils.jsm");
var localFile = Cc["#mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile);
var data="test file content";
//localFile.initWithPath("D:\\temp-directory\\temp-file.txt"); //full path is okay if directory exists
localFile.initWithPath("D:\\temp-directory\\"); //otherwise specifiy directory, create it if necessary, and append leaf.
if(!localFile.exists()){
localFile.create(localFile.DIRECTORY_TYPE,FileUtils.PERMS_DIRECTORY);
}
localFile.append("temp-file.txt");
//localFile.createUnique(localFile.NORMAL_FILE_TYPE,FileUtils.PERMS_FILE); //optional: create a new unique file.
asyncSave(localFile,data,onDone);
function asyncSave(file,data,callbackDone){
// file is nsIFile, data is a string, optional: callbackDone(path,leafName,statusCode)
// default flags: FileUtils.openSafeFileOutputStream(file, FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE | FileUtils.MODE_TRUNCATE);
var ostream = FileUtils.openSafeFileOutputStream(file);
var converter = Cc["#mozilla.org/intl/scriptableunicodeconverter"].createInstance(Ci.nsIScriptableUnicodeConverter);
converter.charset = "UTF-8";
var istream = converter.convertToInputStream(data);
// optional: callbackSaved(status).
NetUtil.asyncCopy(istream, ostream, callbackSaved);
function callbackSaved (status) {
if(callbackDone){
if(status===0)callbackDone( file.path, file.leafName, status); //sucess.
else callbackDone( null, null, status); //failure.
};
}
}
function onDone(path,leafName,statusCode){
console.log([statusCode===0?"OK":"error",path,leafName].join("\n"));
}
More information:
https://developer.mozilla.org/en-US/docs/Code_snippets/File_I_O
https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/FileUtils.jsm
https://developer.mozilla.org/en-US/docs/PR_Open
https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/NetUtil.jsm
https://developer.mozilla.org/en-US/docs/XPCOM_Interface_Reference/nsIFile
https://developer.mozilla.org/en-US/docs/XPCOM_Interface_Reference/nsILocalFile
A simple example of how to read/write a file from the filesystem in windows, using Firefox Extension:
// Write File to filesystem
Components.utils.import("resource://gre/modules/osfile.jsm"); // load the OS module
var encoder = new TextEncoder(); // This encoder can be reused for several writes
var array = encoder.encode("just some text"); // Convert the text to an array
var promise = OS.File.writeAtomic("C:\\foo.txt", array,{tmpPath: "foo.txt.tmp"}); // Write the array atomically to "file.txt", using as temporary
alert("URL HOST has been saved");
//Read File from filesystem
var decoder = new TextDecoder(); // This decoder can be reused for several reads
var promise = OS.File.read("C:\\foo.txt"); // Read the complete file as an array
promise = promise.then(
function onSuccess(array) {
alert(decoder.decode(array)); // Convert this array to a text
}
);
This solution is for making file in ubuntu, hope this helps others:
var file = Components.classes["#mozilla.org/file/directory_service;1"].
getService(Components.interfaces.nsIProperties).
get("ProfD", Components.interfaces.nsIFile);
file.append("trick_new");
if( !file.exists() || !file.isDirectory() ) { // if it doesn't exist, create
file.create(Components.interfaces.nsIFile.DIRECTORY_TYPE, 0777);
}
this.log_file = file.path + "/newlog.html";
You can also use text-stream to write to a local file.
function writeTextToFile(text, filename) {
var fileIO = require("sdk/io/file");
var TextWriter = fileIO.open(filename, "w");
if (!TextWriter.closed) {
TextWriter.write(text);
TextWriter.close();
}
}

AS3 Save SWF to iOS device and then load it back into a MovieClip

I have an iOS app that's using AS3 and AIR. I have external swfs downloading from a server and playing properly--all of this works perfectly fine.
I don't want the user to have to download these swfs every time they launch the app, though, so after the swf is downloaded the first time I want to save it to disk. That way I can load it from the local copy when I need it in the future, instead of downloading it again. I found this example online for saving files in AS3:
var file:File = File.applicationStorageDirectory.resolvePath("Swfs/" + "mySwfName" + ".swf");
var wr:File = new File(file.nativePath);
var stream:FileStream = new FileStream();
stream.open(wr, FileMode.WRITE);
stream.writeBytes(SWF_FILE_GOES_HERE, 0, SWF_FILE_DATA_LENGTH_GOES_HERE);
stream.close();
The problem is in the writeBytes line. The sample I found was for saving images to disk, and that line read like this:
stream.writeBytes(imageData, 0, imageData.length);
But I need to do this for a swf, not an image, and I'm not sure how to get the requisite data from my swf file. I've searched online for saving swf files, getting data from swf files, etc... But I haven't found anything. I need to get the swf's data and data length (I'm assuming this is a number of bytes?). Has anyone solved this problem before, or have a resource they can point me in the direction of?
UPDATE: Based on #LondonDrugs_MediaServices' comments, I figured out the writeBytes line:
stream.writeBytes(mySwf.loaderInfo.bytes, 0, mySwf.loaderInfo.bytesTotal);
This seems to work, in as much as it compiles and runs without errors. But when I try to grab the file and put it back into a movie clip, I get this error:
Error #2044: Unhandled IOErrorEvent:. text=Error #2035: URL Not Found.
Which implies that the file was not, in fact, saved correctly. When I print the file locations, however, they seem to be right! When I save the file to the applicationStorageDirectory:
/Users/MyName/Library/Preferences/com.appdir/Local Store/Swfs/mySwName.swf
And the filename when I try and load it out of storage and into a movie clip:
/Users/MyName/Library/Preferences/com.appdir/Local Store/Swfs/mySwName.swf
This is the code I'm using to try and load it back into a movie clip:
var videoFileName:String = "Swfs/" + ENVAR.currentVideoSelected + ".swf";
var videoFilePath:File = File.applicationStorageDirectory.resolvePath(videoFileName);
var inFileStream:FileStream = new FileStream();
trace("[Loading] filepath: ", videoFilePath.nativePath);
inFileStream.open(videoFilePath, FileMode.READ);
var fileContents:String = inFileStream.readUTFBytes(inFileStream.bytesAvailable);
inFileStream.close();
var req:URLRequest = new URLRequest(videoFilePath.nativePath);
var mLoader:Loader = new Loader();
mLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onVideoLoadComplete);
mLoader.load(req);
And my onVideoLoadComplete function contains these lines:
var myMC:MovieClip = e.target.content as MovieClip;
addChild(myMC);
But I'm getting that error 2044 and it doesn't think the file exists. Can anyone spot the problem? Thanks!
You can get the raw bytes of a loaded swf file by using it's loaderInfo.bytes parameter. So for you example you could do this:
var file:File = File.applicationStorageDirectory.resolvePath("Swfs/" + key + ".swf");
var wr:File = new File(file.nativePath);
var stream:FileStream = new FileStream();
stream.open(wr, FileMode.WRITE);
stream.writeBytes(mySwf.loaderInfo.bytes, 0, mySwf.loaderInfo.bytesTotal);
stream.close();
Then to pull it back out into a MovieClip:
var videoFileName:String = "Swfs/" + ENVAR.currentVideoSelected + ".swf";
var videoFilePath:File = File.applicationStorageDirectory.resolvePath(videoFileName);
var inFileStream:FileStream = new FileStream();
inFileStream.open(videoFilePath, FileMode.READ);
var swfBytes:ByteArray = new ByteArray();
inFileStream.readBytes(swfBytes);
inFileStream.close();
var mLoader:Loader = new Loader();
var loaderContext:LoaderContext = new LoaderContext(false, ApplicationDomain.currentDomain);
loaderContext.allowCodeImport = true;
mLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onVideoLoadComplete);
mLoader.loadBytes(swfBytes, loaderContext);

Resources