error when launching image library in react-native - javascript

So I am trying to lauch the image library with a package called react-native-image-picker:
function launchLibrary(fun) {
let options = {
storageOptions: {
skipBackup: true,
path: 'images',
},
};
ImagePicker.launchImageLibrary(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
alert(response.customButton);
} else {
const source = { uri: response.uri };
console.log(source);
console.log('response', JSON.stringify(response));
fun(response);
}
});
};
Then when the function gets executed, I get the following response:
response {"errorMessage":"Activity error","errorCode":"others"}
What went wrong here?

The Google Play store no longer accepts builds targeting SDK < 30 so I managed to get it working with a different work around.
I updated react-native-image-picker to version "^4.7.0" and the error went away, but note that launchImageLibrary response may now contain an array of "assets" with image data, rather than including the image data right within the response object.
After updating, replacing response.uri with response.assets[0].uri did the trick for me.

I changed compileSdkVersion and targetSdkVersion from 30 to the 29 in
build.gradle , depending on that answer:
https://github.com/react-native-image-picker/react-native-image-picker/issues/1600
compileSdkVersion = 29
targetSdkVersion = 29
and it worked normally after that.

Related

Imagepicker React Native crashes on iOS but works fine on Android

I am currently using imagepicker on react native. When I use android to pick image it works fine. However when I use iOS it crashes when I choose a photo.
This is the error it shows in xcode debugger:
2020-04-03 11:54:27.802434+0800 app[7218:1993193] -[NSURLResponse allHeaderFields]: unrecognized selector sent to instance 0x28281aba0
2020-04-03 11:54:27.802766+0800 app[7218:1993193] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSURLResponse allHeaderFields]: unrecognized selector sent to instance 0x28281aba0'
* First throw call stack:
(0x19d01c164 0x19cd30c1c 0x19cf1a7e0 0x19d02085c 0x19d022b60 0x102b27bc8 0x102b27a90 0x102b01ce0 0x1059f5d10 0x1059f718c 0x1059fe968 0x1059ff580 0x105a0b0f0 0x19cd23714 0x19cd299c8)
libc++abi.dylib: terminating with uncaught exception of type NSException
and this is my code:
chooseImage = async (id) => {
//await this.askPermissionsAsync();
let options = {
title: 'Select Image',
storageOptions: {
skipBackup: true,
path: 'images',
},
};
ImagePicker.showImagePicker(options, (response) => {
console.log('Response = ', response.error);
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else {
const source = { uri: response.uri };
// You can also display the image using data:
// const source = { uri: 'data:image/jpeg;base64,' + response.data };
// alert(JSON.stringify(response));
let file_data = [...this.state.fileData];
file_data[id] = response.data;
let file_uri = [...this.state.fileUri];
file_uri[id] = response.uri;
this.setState({filePath:response, fileData: file_data, fileUri: file_uri});
}
});
}
I have also added the permissions in info.plist:
<key>NSCameraUsageDescription</key>
<string></string>
<key>NSPhotoLibraryUsageDescription</key>
<string></string>
<key>NSPhotoLibraryAddUsageDescription</key>
<string></string>
<key>NSDocumentsFolderUsageDescription</key>
<string></string>
but the problem still persist in ios.
The issue was
'data:image/jpeg;base64,' + this.state.fileData[id]
while rendering it on Image tag.
This issue is indicated here:
YellowBox Crash
Image Crash with data:image/png;base64
The solution I did was to add "noData: true" on option and access directly the URI file location in the image tag.
Hope this helps
react-native link did not link the library, so the mage picker lib did not build with the app. Thats why I as getting null pointer exception because there was no lib.
Or else manually add the library.
<key>NSCameraUsageDescription</key>
<string>Access to take a photo by camera</string>
<key>NSAppleMusicUsageDescription</key>
<string>Access to pick a photo</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>Access to pick a photo</string>

Electron dialog.showOpenDialog() Filters not working

I'm working on a fork of an IDE on GitHub and one of the main issues were that it saved the files to cookies, instead of the common computer. So, I needed a way to save and open files. I've gotten the saving file system down by using blobs. However, with the opening file, according to the console, provides an "Unexpected String," even though it's pretty vanilla.
Below is the function:
function openFileCMD() {
console.log('Opening File...');
dialog.showOpenDialog( (fileName), {
filters: [{
name: 'Text Files',
extensions: ['txt']
}, {
name: 'HTML Files',
extensions: ['html', 'htm']
}, {
name: 'Rich Text File',
extensions: ['rtf']
}, {
name: 'XML/YAMLFile',
extensions: ['xml', 'yml', 'yaml']
}, {
name: 'JSON File',
extensions: ['json'] }
]} => {
if(fileName === undefined) {
console.log("Ouch. That wall hurt. Can you pick a file this time? Please?");
// document.getElementsByClassName('alert')[0].style.display = "block";
return;
}
fs.readFile(fileName[0], 'utf-8', (err, data) => {
if(err){
alert("Woah. Something went wrong. Check the console for more info.");
console.log("An error occured reading the file : " + err.message);
return;
} else {
document.getElementById("code-editor").value = "<pre><code>" + data + "</code></pre>";
}
});
closeSidebar();
}
Thanks in advance to anyone who can either help fix this or point me in the right direction to resolving this! :)
Edit: I have tried with dialog.showOpenDialog all on one line: still to no avail.
The "Unexpected String," error message you get is not related to the filters, but to the fact that dialog.showOpenDialog is not called properly...
dialog.showOpenDialog (filename, options => { ... });
should be instead:
dialog.showOpenDialog (options, filename => { ... });

Issues retrieving fbsdk Access Token and User ID

I am trying to retrieve the Access Token and User ID of the logged in user in my React Native App. For some reason when I tried to update the fbsdkcore package, it did not exist anymore. So, I tried to resolve it within the general fbsdk package.
I am calling the js file (of which I think retrieves the accesstoken) in the package as:
const AccessToken = require('react-native-fbsdk/js/FBAccessToken');
And subsequently in my code I try to log it so that I can see if it works, simply by:
console.log(AccessToken.getCurrentAccessToken());
console.log(AccessToken.getUserId);
But the log only returns:
2016-05-05 10:22:28.276 [info][tid:com.facebook.React.JavaScript] { _45: 0, _81: 0, _65: null, _54: null }
2016-05-05 10:22:28.277 [info][tid:com.facebook.React.JavaScript] undefined
Which does not seem to be the droids that im looking for.
I inspected the code for the js file in the fbsdk package and the getCurrentAccessToken code looks like this:
/**
* Getter for the access token that is current for the application.
*/
static getCurrentAccessToken(): Promise<?FBAccessToken> {
return new Promise((resolve, reject) => {
AccessToken.getCurrentAccessToken((tokenMap) => {
if (tokenMap) {
resolve(new FBAccessToken(tokenMap));
} else {
resolve(null);
}
});
});
}
Which of course seems reasonable. But since I get this really weird result when I try to call it, I get worried over that I have done something wrong in the bigger picture. I even modified the resolve(null) part of the code so that I could make sure of what happend. But it still returned the same weird "token".
The log also returns this error when logging in:
2016-05-05 10:22:07.630 AppName[15097:415865] -canOpenURL: failed for URL: "fbauth2:/" - error: "(null)"
But I think that is only because I don't have the facebook app on my xcode simulator.
Can anybody throw me a good guess on what I have done wrong??
GetCurrentAccestoken returns a promise.
Maybe you can try:
AccessToken.getCurrentAccessToken().then(
(data) => {
console.log(data.accessToken.toString())
}
)
Try this. It worked for me
AccessToken.getCurrentAccessToken().then(
(data) => {
console.log(data.accessToken)
console.log(data.userID);
});
LoginManager.logInWithReadPermissions(['public_profile']).then(
function (result) {
if (result.isCancelled) {
alert('Login cancelled');
} else {
// alert('Login success with permissions: ' +
// result.grantedPermissions.toString());
AccessToken.getCurrentAccessToken().then(
(data) => {
doLoginViaFb(data.userID, data.accessToken);
}
);
alert(result);
console.log(result.toString());
console.log(JSON.stringify(result));
}
},
function (error) {
alert('Login fail with error: ' + error);
}
);

Chrome Apps : How to save blob content to fileSystem in the background?

In Chrome Apps, I'm downloading a blob content from a server using JavaScript XHR (Angular $http GET in particular, with response type 'blob')
How should I save this to chrome application's file system?
Currently using an Angular wrapper on HTML5 filesystem API
https://github.com/maciel310/angular-filesystem
I do not want to show user a popup (hence I can't use chrome.fileSystem. chooseEntry )
The chrome.fileSystem.requestFileSystem API is only supported by Kiosk-only apps.
Hence I'm using HTML5 FileSystem API instead of chrome's.
I'm using following code to make XHR to fetch blob.
$http({
url: SERVER_URL+"/someVideo.mp4",
method: "GET",
responseType: "blob"
}).then(function(response) {
console.log(response);
fileSystem.writeBlob(response.name, response).then(function() {
console.log("file saved");
}, function(err) {
console.log(err);
});
}, function (response) {
});
This is my writeBlob method
writeBlob: function(fileName, blob, append) {
append = (typeof append == 'undefined' ? false : append);
var def = $q.defer();
fsDefer.promise.then(function(fs) {
fs.root.getFile(fileName, {create: true}, function(fileEntry) {
fileEntry.createWriter(function(fileWriter) {
if(append) {
fileWriter.seek(fileWriter.length);
}
var truncated = false;
fileWriter.onwriteend = function(e) {
//truncate all data after current position
if (!truncated) {
truncated = true;
this.truncate(this.position);
return;
}
safeResolve(def, "");
};
fileWriter.onerror = function(e) {
safeReject(def, {text: 'Write failed', obj: e});
};
fileWriter.write(blob);
}, function(e) {
safeReject(def, {text: "Error creating file", obj: e});
});
}, function(e) {
safeReject(def, {text: "Error getting file", obj: e});
});
}, function(err) {
def.reject(err);
});
return def.promise;
},
This shows SECURITY_ERR as It was determined that certain files are unsafe for access within a Web application, or that too many calls are being made on file resources.
What's the solution for this?
I've tried using --allow-file-access-from-files flag while launching app. It doesn't help.
Chrome Application's sandbox storage doesn't allow files to be stored in root directory (i.e. / )
Modify the code to save it in a specific sub-directory under it.
For example -
fileSystem.writeBlob("/new"+response.name, response).then(function() {
console.log("file saved");
}, function(err) {
console.log(err);
});
This would successfully save the file under /new/ directory.
To expand on this, here is a full example app on how to download a file and save the blob and display it back to the user.
https://github.com/PierBover/chrome-os-app-download-example

can't get Meteor slingshot to work

I am trying to get slingshot to work but having a hard time, I am attaching here the code I have.
The error I get n the console is:
"Exception in delivering result of invoking 'slingshot/uploadRequest': TypeError: Cannot read property 'response' of undefined"
client
Template.hello.events({
'change .uploadFile': function(event, template) {
event.preventDefault();
var uploader = new Slingshot.Upload("myFileUploads");
uploader.send(document.getElementById('uploadFile').files[0], function (error, downloadUrl) {
if (error) {
// Log service detailed response
console.error('Error uploading', uploader.xhr.response);
alert (error);
}
else{
console.log("Worked!");
}
});
}
});
lib
Slingshot.fileRestrictions("myFileUploads", {
allowedFileTypes: ["image/png", "image/jpeg", "image/gif"],
maxSize: null // 10 MB (use null for unlimited)
});
server
Slingshot.fileRestrictions("myFileUploads", {
allowedFileTypes: ["image/png", "image/jpeg", "image/gif"],
maxSize: null,
});
Slingshot.createDirective("myFileUploads", Slingshot.S3Storage, {
AWSAccessKeyId: "my-AWSAccessKeyId",
AWSSecretAccessKey: "my-AWSSecretAccessKey",
bucket: "slingshot-trial-2",
acl: "public-read",
authorize: function () {
//Deny uploads if user is not logged in.
},
key: function (file) {
//Store file into a directory by the user's username.
return file.name;
}
});
I saw the same issue and it was due to xhr being null - try removing the console error line that references it and I'm assuming you'll start seeing the alert with the actual error message:
console.error('Error uploading', uploader.xhr.response);
I ended up putting in a check for xhr before referencing it and then logging it if it existed.

Categories

Resources