How to save a pdf file in iPhone memory and make it accessible by pdf file opener applications using titanium - iphone

i am new bie to titanium in my app i need to download and save a pdf file in iOS using titanium and the downloaded file can be accessible by third party pdf viewer applications.any help to achieve this thanks in advance.

1- Make sure your webservice returns a PDF file.
2- Use the FileSystem to manage your files
var xhr = Titanium.Network.createHTTPClient({
onload : function() {
var f = Ti.Filesystem.getFile(Ti.Filesystem.externalStorageDirectory, 'file.pdf');
f.write(this.responseData);
tmpFile = Ti.Filesystem.createTempFile();
var newPath = tmpFile.nativePath + "." + f.extension();
Ti.API.info("newPath: " + newPath);
tmpFile = Ti.Filesystem.getFile(newPath);
tmpFile.write(f.read());
},
timeout : 10000
});
xhr.open('GET', 'your webservice');
xhr.send();
Now you use a pdf viewer and open the PDF from the externalStorageDirectory
I tested on Android, it works !

Related

IONIC3 - WriteFile & WriteExistingFile is unable to overwrite the file

I would like to do image annotation for my Ionic Application. So the flow of the app would be using the camera plugin to take a picture and use FabricJs to draw on the image then save the file.
I hit the roadblock when I am trying to save or overwrite the file. Apparently the source "http://localhost:8080/file/data/user/0/***/files/1547183479807.png" file does not update.
The flow of the app
1) Take picture with #ionic-native/camera
2) Copy the file to a local directory
3) Use this.win.Ionic.WebView.convertFileSrc to convert the file name to "http://localhost:8080/file/data/user/0/***/files/1547183479807.png"
4) Push to another page to access the canvas
5) Use the link to setBackground to my canvas (FabricJs)
6) Draw on the image (Manually)
7) Save the file via overwriting the existing file but nothing works from here on.
I tried to
- overwrite with writeFile & writeExisitingFile, did not work.
- removeFile and writeFile and did not work.
- tried converting to ArrayBuffer rather than Blob and did not work
- tried creating another new file, did not work too (it seems like after I push to a new page, all the file functions does not affect the files)
- tried using native cordova but did not work too.
- delete that same files twice, (first time I did not get an error but the second time I got an error saying "File Does not exist" but when I view the source, the file is also there and appearing in my thumbnail on my App.
private copyFileToLocalDir(namePath, currentName, newFileName,id,index) {
this.file.copyFile(namePath, currentName, this.file.dataDirectory, newFileName).then(success => {
const keys = id.split('-');
let filename = this.file.dataDirectory + newFileName;
this.fp = this.win.Ionic.WebView.convertFileSrc(filename) ;
this.navCtrl.push(AnnotationsPage, {
filepath: this.fp,
filename: newFileName
});
this.presentToast("Image Successfully Added",'middle');
}, error => {
this.presentToast('Error while storing file.','middle');
});
}
Annotation.ts
savePicture() {
let image = this.canvas.toDataURL({
format: 'png'
});
this.saveBase64(image);
}
public saveBase64(base64:string):Promise<string>{
return new Promise((resolve, reject)=>{
var realData = base64.split(",")[1]
let blob=this.b64toBlob(realData,"image/png")
this.file.writeFile(this.file.dataDirectory,this.filename,blob,{replace:true})
// this.file.writeExistingFile(this.file.dataDirectory,this.filename, blob)
.then((val)=>{
console.log('Write Info',val)
let fp = this.win.Ionic.WebView.convertFileSrc(this.file.dataDirectory+this.filename) ;
})
.catch((err)=>{
console.log('error writing blob')
console.log(err);
// reject(err)
})
})
}
b64toBlob(b64Data, contentType) {
contentType = contentType || '';
var sliceSize = 512;
var byteCharacters = atob(b64Data);
var byteArrays = [];
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
var slice = byteCharacters.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
I check the base64 file, it is working fine (Throw the data to an online converter and it display the picture.
After the function "copyFileToLocalDir", it seems like I am unable to modify the files store in the local directory.
Thanks in advance. Feel free to ask me more question. 7 hours and no result.
Update on the testing, I am doing.
Did File.readAsDataUrl and as expected the file file:///data/user/0/*/files/1547231914843.png updated from the old image to the new edited. (Tested the base64 on some online converter) but it still does not reflect on the source http://localhost:8080/file/data/user/0/***/files/1547231914843.png
Thanks to all those who read through.
After tons of testing, I found out that Ionic Webview's files, will not be updated unless you recall them again (Kind of like a cache and apparently there is no way to reset or flush the cache).
So in my case, I would need to remove the image from the webview and call it out again then it will go back to retrieve again or create another file with another file name and display it.

cn1 - get file path to image for share()

I'm trying to use the share() method, including an image, but I'm having trouble supplying the proper path to the image. Where should I put the image file, and what is the path (putting in the default package and trying "jar:///myimage.png" didn't work), and why is this not documented clearly?
image can be stored in storage which is following path for window
C:\Users\userName.cn1
and the image can be read by using following codes
InputStream is = Storage.getInstance().createInputStream("tizbn.JPG");
EncodedImage i = EncodedImage.create(is, is.available());
Loading image from default folder
Image i =EncodedImage.create("/tizbn.png");
Loading image From Theme
EncodedImage current = (EncodedImage) fetchResourceFile().getImage("tizbn.png");
The share API works with https://www.codenameone.com/javadoc/com/codename1/io/FileSystemStorage.html[FileSystemStorage] and not with https://www.codenameone.com/javadoc/com/codename1/io/Storage.html[Storage].
You need to save the file into a file system path which is always an absolute path, we recommend using the app home to store files. There is a sample in the developer guide section on the ShareButton covering this:
Form hi = new Form("ShareButton");
ShareButton sb = new ShareButton();
sb.setText("Share Screenshot");
hi.add(sb);
Image screenshot = Image.createImage(hi.getWidth(), hi.getHeight());
hi.revalidate();
hi.setVisible(true);
hi.paintComponent(screenshot.getGraphics(), true);
String imageFile = FileSystemStorage.getInstance().getAppHomePath() + "screenshot.png";
try(OutputStream os = FileSystemStorage.getInstance().openOutputStream(imageFile)) {
ImageIO.getImageIO().save(screenshot, os, ImageIO.FORMAT_PNG, 1);
} catch(IOException err) {
Log.e(err);
}
sb.setImageToShare(imageFile, "image/png");

Unable to display image from cordova.file.documentsDirectory

I am trying to access an image that i download from remote server. My code to download the file is as below :
var targetPath = cordova.file.documentsDirectory + propp+".png";
var trustHosts = true;
$cordovaFileTransfer.download(url, targetPath, options, trustHosts)
.then(function(result) {
console.log("Local file transfer done");
r = angular.toJson(result.nativeURL);
}, function(err) {
// Error
console.log("error");
});
Then I stored tatgetPath in my local sqlite database. In another page I get this from sqlite and try to display with img tag. But it display like broken Image on Emulator as well as on actual device.
My file url is :
file:///var/mobile/Containers/Data/Application/F7B3169B-D8E3-4F62-AD0B-37CFA381F1CC/Documents/home_bg_image.png
I want to display this image as a background image bit I don't understand how to do this.
After downloading the image you have to paste it in platform/android/assets/www/img-- folder to display the image as
var filedirPath = $ionicPlatform.is('android') ? '/android_asset/www/img/' : 'img';
if not find the path of the image and access the file to display for reference please check this link File path
Having any queries reply ..

How to Download Facebook Look back Video?

What should Do, If I want to download Facebook Lookback Video
Reference
Simple JS Script to get Video URL from Facebook's Look Back
Copy paste this whole code into Chrome Console and press enter.
You can execure this script on any page on Facebook.
It will give you the video URL, open it, view it, download it, do whatever you want to. :P
The video URL will popup in front of you, press Ctrl + C to copy it.
To do so, open Chrome Console, Ctrl + Shift + J, "Console" tab.
Copy paste the whole thing there.
To share it, just open the link and download it by pressing Ctrl + S.
Upload it to YouTube or wherever you want to. Share, enjoy! :)
Keep Sharing this with everyone! :)
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
ss = xmlhttp.responseText.split('[["params","')[1].split('"],["width","960"]')[0];
var x = ss;
var r = /\\u([\d\w]{4})/gi;
x = x.replace(r, function (match, grp) {return String.fromCharCode(parseInt(grp, 16)); });
x = unescape(x);
console.log(JSON.parse(x).video_data[0].hd_src);
prompt("Here's your video URL (HD)! Press Ctrl + C to copy it!", JSON.parse(x).video_data[0].hd_src)
}
}
xmlhttp.open("GET", "/lookback", true);
xmlhttp.send();
You can also get the SD and HD sources directly from the flashvars of the embed used to display the video. In Google Chrome inspect the page for the "content" div you'll find a div with class "swfObject".
Decoding the flasvar, you'll get something similar to:
params={
"autoplay":true,
"autorewind":true,
"default_hd":false,
"dtsg":"AQAAJp6S",
"inline_player":false,
"lsd":null,
"min_progress_update":300,
"pixel_ratio":1,
"preload":false,
"source":"lookback",
"start_index":0,
"start_muted":false,
"use_spotlight":false,
"video_data":[
{
"hd_src":"https:\/\/lookbackvideo7-a.akamaihd.net\/hvideo-ak-ash2\/v\/t55\/1774977_10104243234253383320144_17978_n.mp4?oh=7d70ce01b4c6dff2345d48e6e938a9df65f&oe=52F59B08&__gda__=1391855368_9ae234b1cce92effd53d05cdfb6e884f323",
"is_hds":false,"index":0,"rotation":0,
"sd_src":"https:\/\/lookbackvideo7-a.akamaihd.net\/hvideo-ak-ash2\/v\/t54\/1785524_101045234234383320144_19170_n.mp4?oh=1116ee0f06e59c4180648234bac62a148ea&oe=52F5A983&__gda__=1391848771_03b13324ffa3791cc64e0d070465107c7c8",
"thumbnail_src":"https:\/\/fbcdn-vthumb-a.akamaihd.net\/hvthumb-ak-prn1\/t15\/1542287_101045533833922349984_10104553383320144_60544_503_b.jpg",
"thumbnail_height":540,"thumbnail_width":960,
"video_duration":62,
"video_id":"101045523423383320144"
}]}
The two important values here are hd_src and sd_src (i've garbled mine for security purposes):
"hd_src":"https:\/\/lookbackvideo7-a.akamaihd.net\/hvideo-ak-ash2\/v\/t55\/1774977_10104553382342320144_17978_n.mp4?oh=7d70ce01b4c6dff5d48e6e938234a9df65f&oe=52F59B08&__gda__=1391855368234_9aeb1cce92effd53d05cdfb6e884f323",
"sd_src":"https:\/\/lookbackvideo7-a.akamaihd.net\/hvideo-ak-ash2\/v\/t54\/1785524_101045532342343320144_19170_n.mp4?oh=1116ee0f06e59c4180623424448bac62a148ea&oe=52F5A983&__gda__=139184232428771_03b13ffa3791cc64e0d070465107c7c8",
Load your desired quality (High Definition or Standard Definition) URL into a new browser window, right click on the video and "Save Video As."
www.fundawn.com is the best web place where people can download and watch public videos and photos of top facebook celebrities and others, all in one place.
Just check it.

Uploading files with PhoneGap + iPhone

I understand that PhoneGap applications are largely (if not entirely) HTML5 + CSS + JavaScript. Natively, the iPhone doesn't provide controls to upload files.
Does PhoneGap provide any mechanisms that allow users to upload files? (images / video, in the case of the iPhone)
I know Titanium allows users to do this, but it's a different animal with its compiled Javascript and proprietary APIs. Thanks for your advice/input.
I believe you might be able to read the files using the PhoneGap API and the upload them using and AJAX post if the server application supported it.
The other option is to write a custom module/Plugin in PhoneGap that could specific to your needs.
Here are some Example Plugins
You can do an xmlhttprequest to the file on a local drive.
I'm not 100% sure if it will work on the iPhone, but webkit should support it.
function getImageBinaries(url) { //synchronous binary downloader for firefox2
var req = new XMLHttpRequest();
req.open("GET", url, false);
req.overrideMimeType('text/plain; charset=x-user-defined');
req.send("");
if (req.status != 200) {
return "";
}
var t = req.responseText || "" ;
var ff = [];
var mx = t.length;
var scc= String.fromCharCode;
for (var z = 0; z < mx; z++) {
ff[z] = scc(t.charCodeAt(z) & 255);
}
var b = ff.join("");
return b;
}
Succes,
Erik