I am have created an app with an apple watch extension.
When you click on the button in the watch app an functions gets triggered in the ios app.
In this function i create an json file an send it to the watch app.
When the iphone is not locked everything is working.
But when the iphone is locked i get the following error:
[ERROR] : Could not write data to file at path "/var/mobile/Containers/Data/Application/4015E77E-A694-4E43-8AF6-4858A5FD5958/Documents/arr.json" - details: Error Domain=NSCocoaErrorDomain Code=513 "Sie haben nicht die Zugriffsrechte, um die Datei „arr.json“ im Ordner „Documents“ zu sichern." UserInfo={NSFilePath=/var/mobile/Containers/Data/Application/4015E77E-A694-4E43-8AF6-4858A5FD5958/Documents/arr.json, NSUserStringVariant=Folder, NSUnderlyingError=0x14dd83fa0 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}
The stranage thing is, when i try to save data in that file from an remote source it is working, but when i am trying to set an local json string i get this error.
This is my normal why to save the data:
var jsontext = JSON.stringify(arrData);
var f = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory,'arr.json');
f.write(jsontext);
This is the way with the remote data
var cache = require("ui/common/fileCache");
cache.loadJSON({
url : REMOTEURL,
path : cache.appDir + "arr.json",
last : false
});
fileCache.js
var c = Titanium.Network.createHTTPClient();
c.cache = false;
c.onerror = function(e) {
Ti.API.info('Daten-Caching :: ERROR :: URL = ' + params.url + ' Error=' + e.error);
};
c.onload = function(e) {
var f = Titanium.Filesystem.getFile(params.path);
f.write(c.responseData);
};
c.open('GET', params.url);
c.send();
I dont understand why the second code works when the iphone is locked and the first one not.
Does anyone knows what went wrong?
Related
Context:
Hello, I am working on a Ionic application (made in Typescript). In this application, I control a wifi camera via HTTP Request to the IP (http://192.72.1.1/myCommand to be precise).
Main actions I do with the camera:
Start recording
Stop recording
Get videos list
Download a video
When I use the Ionic DevApp:
With the Ionic DevApp, everything works perfectly, I can do all mains actions without a problem.
When I compile the application on IOS:
I compile with the command ionic cordova build ios --prod, then I archive with Xcode and send it to the AppStore to test it with Test Flight.
I got no errors while compiling / archive the application. But when I try it on my iPhone, I can start / stop recording, but can't download the video.
Problem:
Some commands are not working, but I don't know if it is getting the list or downloading the video, I have no logs. I don't understand why some commands are working but others no.
IOS is blocking download requests? How to solve my problem?
Notes:
I already tried all basic things like delete the IOS platform, recompile, uninstall, ...
I tried different Ionic HTTP plugins, same problem with all of them.
Some code:
Start / Stop the camera: (it is the same command to start / stop).
startCamera(){
var url = "http://192.72.1.1/changeRecordStatus";
var result = this.http.get(url);
result.subscribe(data => {
console.log("Works");
},
err => {
console.log("Error" + err);
}
);
}
Getting the name of the last video:
getLastVideo(){
var url = "http://192.72.1.1/listVideos";
this.http.get(url, {}, {})
.then(data => {
var xml = data.data
var xmlDOM = new DOMParser().parseFromString(xml, 'text/xml');
var temp = this.xmlToJson(xmlDOM); // function that convert XML to JSON
var resultArray = Object.keys(temp).map(function(i){
let ite = temp[i];
return ite;
});
resultArray = resultArray[0]['file'].reverse();
this.lastVideo = resultArray[0]['name']; // lastVideo is a global variable
},
(error) =>{
console.log("Error while getting the name of the last video" + error);
});
}
Downloading the file from the camera:
downloadFileFromCamera() {
this.getLastVideo();
var basename_file = this.lastVideo;
var url = "http://192.72.1.1" + basename_file;
this.fileTransfer.download(encodeURI(url), this.file.dataDirectory + '/videos/' + basename_file, true).then((entry) => {
this.video[this.counterVideos] = entry; // video is a global array
this.counterVideos +=1;
}, (error) => {
console.log("Error while downloading the last video" + error);
});
}
If someone knows how to solve my problem, I would be so grateful! Thanks in advance.
I am using react-native-firebase to work with our Firebase account for authentication, firestore and storage. Attempting to upload a photo to Storage is failing with an unknown error. Here is the code attempted:
_pickImage = async () => {
await this.getCameraRollPermission()
let result = await ImagePicker.launchImageLibraryAsync({
allowsEditing: true,
aspect: [4, 3],
});
console.log(result);
if (!result.cancelled) {
// this.setState({ photoURL: result.uri });
this._handlePhotoChoice(result)
}
};
_handlePhotoChoice = async pickerResult => {
let userId = this.state.userId
firebase
.storage()
.ref('photos/profile_' + userId + '.jpg')
.putFile(pickerResult.uri)
.then(uploadedFile => {
console.log("Firebase profile photo uploaded successfully")
})
.catch(error => {
console.log("Firebase profile upload failed: " + error)
})
}
Testing in iOS Simulator and using the debugger to detect the errors I'm just getting back this error:
"Error: An unknown error has occurred.
at createErrorFromErrorData (blob:http://localhost:19001/e9d43477-4e42-4f7a-b494-16485def4c28:2371:17)
at blob:http://localhost:19001/e9d43477-4e42-4f7a-b494-16485def4c28:2323:27
at MessageQueue.__invokeCallback (blob:http://localhost:19001/e9d43477-4e42-4f7a-b494-16485def4c28:2765:18)
at blob:http://localhost:19001/e9d43477-4e42-4f7a-b494-16485def4c28:2510:18
at MessageQueue.__guardSafe (blob:http://localhost:19001/e9d43477-4e42-4f7a-b494-16485def4c28:2678:11)
at MessageQueue.invokeCallbackAndReturnFlushedQueue (blob:http://localhost:19001/e9d43477-4e42-4f7a-b494-16485def4c28:2509:14)
at http://localhost:19001/debugger-ui/debuggerWorker.js:70:58"
UPDATE:
A file is uploaded to the storage bucket, but the file is not the JPEG photo, but instead is JSON content about the file:
{"contentType":"image\/jpeg","name":"photos\/profile_XPIO2lHjlYbdLPchACZHBsmY9Jr1.jpg"}
So somehow a JSON file is ending up in the bucket instead of the actual photo and then the error is thrown.
It looks like this issue is tracked a couple times, but not resolved:
https://github.com/invertase/react-native-firebase/issues/1177
https://github.com/invertase/react-native-firebase/issues/302
Finally found my issue. The URI of the image from the ImagePicker had a '%' character in it from the local app cache. This percent was being URI encoded to '%25' which resulted in the file not being found by the putFile code. Adding a decodeURI call around the uri fixed the issue.
let fileUri = decodeURI(pickerResult.uri)
In case you are using react-native-document-picker, check out this:
https://github.com/rnmods/react-native-document-picker/issues/235
I'm receiving the error JSON Parse error: Unrecognized token '<'. but only on IOS. in android it is working fine and the JSON seams to be right. (You can put the link in your web browser and se). The error is in this line Data = JSON.parse(this.responseText); but i can't understand why. and why does is work on android and not in IOS?
var client = Ti.Network.createHTTPClient({
onload : function(e) {
Data = JSON.parse(this.responseText);
Size = Object.keys(Data).length;
AddList();
},
onerror : function(e) {
},
timeout : 15000
});
client.open("GET", http://lamadeus.virtualweb.pt/site/app_mobile/teste.php?act=getprodsdestaque);
client.send();
Have you tried printing the responseText on iOS? Usually this error indicates that the request is receiving a HTML instead of JSON.
Check after replacing :
< with <
> with >
& with & in your this.responseText and after that try to parse.
first, sorry if my english is bad.
Then, here is my issue:
I try to make an app for iOS with PhoneGap 2.8.1 . Evrything is going well on Android, now I just want to move my code on Xcode to compile on iPad or iPhone.
The probleme I have is with FileTransfer, when I upload an image. The transfer itself has no problem, as it finishes with a response code 200, so it's a success.
Then, my serve is supposed to return back an XML file, handled by the javascript code. The server works fine, because I have absolutly no problem with Android devices.
So, I made a lot of tests, and it appears that the app has a problem with the success callback or the FileTransfer.upload(). When I just put a simple console.log('success') in this callback function, it's fine. But when I try to use the FileUploadResult object, nothing happens.
And the weirdest thing is, that when I press the main button of the iPad or iPhone, in order to close my app, I see all my logs displayed in the debug window, such as console.log("Code = " + r.responseCode);, like in the PhoneGap example. And here, I can finally see that I actually receive the server response, but it's like something blocks it until I close the app.
Here is that part of the code :
function onPhotoDataSuccess(imageURI) {
console.log("---> Image: "+imageURI);
// File Transfer
var options = new FileUploadOptions();
options.fileKey="file";
options.chunkedMode = false;
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI(window.localStorage.getItem("wsURL")), win, fail, options);
// Transfer succeeded
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
// Handle the XML response
}
else {
alert("No response. Please retry");
}
}
// Transfer failed
function fail(error) {
alert("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
}
Thanks for your help
I am working on trying to get iOS 6 to use XMLHttpRequest POSTs to upload images. This works on desktop and Android web browsers, but with iOS 6 I am getting an error on the page being posted to: "Request Body Stream Exhausted". (Using iOS Simulator with the Safari Web Inspector).
Here is the basic code of the page:
function fileSelected() {
var file = document.getElementById('fileToUpload').files[0];
if (file) {
var fileSize = 0;
if (file.size > 1024 * 1024)
fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
else
fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
document.getElementById('fileName').innerHTML = 'Name: ' + file.name;
document.getElementById('fileSize').innerHTML = 'Size: ' + fileSize;
document.getElementById('fileType').innerHTML = 'Type: ' + file.type;
}
}
function uploadFile() {
var fd = new FormData();
fd.append("fileToUpload", document.getElementById('fileToUpload').files[0]);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", "/UploadHandler.ashx");
xhr.send(fd);
}
function uploadProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded * 100 / evt.total);
document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';
document.getElementById('prog').value = percentComplete;
}
else {
document.getElementById('progressNumber').innerHTML = 'unable to compute';
}
}
function uploadComplete(evt) {
/* This event is raised when the server send back a response */
alert(evt.target.responseText);
}
function uploadFailed(evt) {
alert("There was an error attempting to upload the file.");
}
function uploadCanceled(evt) {
alert("The upload has been canceled by the user or the browser dropped the connection.");
}
When doing this on any other browser, the handler returns correctly and uploads the file. However, with iOS the ashx page has the error "request body stream exhausted".
Here is a screenshot of the inspector:
Any ideas?
UPDATE: This issue only occurs when NTLM/Windows authentication is enabled for the application in IIS. With forms or anonymous authentication, the upload works fine.
Thanks,
John
In iOS 6, Safari sends the file with the initial post, including the file. That means the file stream is at the end, or "exhausted."
However, with NTLM, it will get a 401 challenge in response, and then have to resend the post with the authentication information. Since it does not reset the file stream, it is unable to send the file again with the second post. You can see this in the IIS logs.
As far as I know, there is no particularly good way around it. I am changing my mobile app, so that it uses form authentication. I direct the mobile app to a separate login app on the same server, which is set to use Windows Authentication. The login app can then redirect back to the main app with a form authentication cookie, and all is well again.
You have to set the machine key on both apps in the web.config file, so that both are using the same keys for encryption and validation.
The code on the login app is as simple as
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles Me.Load
With HttpContext.Current.User.Identity
If .IsAuthenticated Then
Dim sUser As String = .Name.ToLower.Trim
FormsAuthentication.RedirectFromLoginPage(s, False)
End If
End With
End Sub
I solved the issue by not setting the self-defined HTTP Authenticate Head on iOS 7 and iOS 8. (At first, our service use the self-defined value for the Authenticate Head). And after the challenge being handled by the delegate, the request will have the "Authenticate: NTLMxxx automatically" header automatically. And the Put and POST works again.
This error Comes on IOS but you can use different approach
like change your code line in formdata where you appending the file
var fd = new FormData();
fd.append("fileToUpload", document.getElementById('fileToUpload').files[0]);
to the below line basically don't append the file control but use the base64 image data
var reader = new FileReader();
reader.readAsDataURL(opmlFile.files[0]);
reader.onload = function () {
var base64DataImg = reader.result;
base64DataImg = base64DataImg.replace('data:'imagetype';base64,', '');
}