React native track player fails to add songs to playlist - ios

I am working on a music player in react native and have been using the package react-native-track-player. I have so far not had a problem with the package in android. but when I try to run it on ios I get the error
You attempted to set the key0with the value
{"id":"0",
"url":{"uri":"https://urltosong.mp3"},
"artwork":"https://url_to_artwork.jpg",
"artist":"author",
"title":"song titile"
}
on an object that is meant to be immutable and has been frozen.
The code that generate the error is
async function togglePlayback() {
const currentTrack = await TrackPlayer.getCurrentTrack();
if (currentTrack == null) {
await TrackPlayer.reset();
await TrackPlayer.add(playlist); //this was never adding and die silently
await TrackPlayer.play();
} else {
await TrackPlayer.add(playlist); //adding this line the error above appeared
await TrackPlayer.play();
//console.warn(TrackPlayer.getCurrentTrack())
}
}
I am using this version of the package "react-native-track-player": "^2.0.0-rc13",
I don't know if there is something I am missing. I will appreciate your help in fixing this.

Change your track to this:
{"id":"0",
"url":"https://urltosong.mp3",
"artwork":"https://url_to_artwork.jpg",
"artist":"author",
"title":"song titile"
}
Urls should be either a string or a Resource Object

Related

undefined is not an object (evaluating '_ExponentImagePicker.default.requestMediaLibraryPermissionsAsync') in expo-image-picker

Error from catch error block Image
Hi, I am using expo-image-picker and I stumbled with this error for a while now.
and this is all the necessary code that I use. I'll give a green checkmark for appreciation.
For more information, I have already handled the permission in info.plist.
// Camera & Image Picker
import * as ImagePicker from 'expo-image-picker';
const openImagePicker = async () => {
try {
// Ask the user for the permission to access the media library
const permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync()
if (permissionResult.granted === false) {
alert("You've refused to allow this appp to access your photos!");
return;
}
const result = await ImagePicker.launchImageLibraryAsync();
// Explore the result
console.log(result);
if (result.cancelled === false) {
setPickedImagePath(result.uri);
console.log(result.uri);
}
} catch (error) {
alert('Error Occur: ' + error.message)
closeSheet()
}
}
If you are using SDK 44, a permission request is no longer necessary for launching the image picker so you can remove the related code.
Simply call
const result = await ImagePicker.launchImageLibraryAsync({});
If you really want to ask for permission (which as I said is no longer necessary) the correct method is
ImagePicker.getMediaLibraryPermissionsAsync()
and not
ImagePicker.requestMediaLibraryPermissionsAsync()

Google Sign-In With Flutter: Error Code -4

I currently try to implement google_sign_in package in Flutter (https://pub.dartlang.org/packages/google_sign_in).
For this, I followed the example of their repository (https://github.com/flutter/plugins/blob/master/packages/google_sign_in/lib/google_sign_in.dart).
In that example in "initState" is a call signInSilently.
#override
void initState() {
super.initState();
_googleSignIn.onCurrentUserChanged.listen((GoogleSignInAccount account) {
setState(() {
_currentUser = account;
loggedIn = true;
});
});
loggedIn = false;
_googleSignIn.signInSilently();
}
I tried this code in iOS. On my first App Start, it worked well. But since I logged out I get an error here all the time I restart my app.It is the following PlatformException:
PlatformException(sign_in_required, com.google.GIDSignIn, The operation couldn’t be completed. (com.google.GIDSignIn error -4.))
I found in question Google Sign-In Error -4 that the error code is because of a missing Auth in Keychain.
The solution while swift programming is to call the method * hasAuthInKeychain* before the try to signInSilently. My problem is that the GoogleSignIn class in the flutter package has no function named like this.
Is there another call I need to run with this package to be sure I can try a silent log in? Or am I doing something wrong to get this message or is there even the possibility of catching this error?
Edit
I tried Marcel's solution, too. Somehow it is not catching the PlatfromException.
I do not know if this will help: signInSilently() is calling a method in which there is a the following call (google_sign_in.dart, line 217):
await channel.invokeMethod(method)
In platform_channel.dart there is a call
codec.decodeEnvelope(result);
The platform exception gets thrown in here.
if (errorCode is String && (errorMessage == null || errorMessage is String) && !buffer.hasRemaining)
throw PlatformException(code: errorCode, message: errorMessage, details: errorDetails);
else
throw const FormatException('Invalid envelope');
Edit 2
Since I just run my app and not started it in debug mode it somehow works again without throwing an exception. I do not know how this affects the code and why I got this exception. I can also run the code in debug mode again.
Since then I had the exception once again. Again I restarted android studio and runned the application once without debug mode.
You could just check if the sign in failed by handling the PlatformException like this:
void _setUpGoogleSignIn() async {
try {
final account = await _googleSignIn.signInSilently();
print("Successfully signed in as ${account.displayName}.");
} on PlatformException catch (e) {
// User not signed in yet. Do something appropriate.
print("The user is not signed in yet. Asking to sign in.");
_googleSignIn.signIn();
}
}
This is one way to catch the error and run _googleSignIn.signIn();
GoogleSignInAccount googleSignInAccount = await googleSignIn
.signInSilently(suppressErrors: false)
.catchError((dynamic error) async {
GoogleSignInAccount googleSignInAccount =
await _googleSignIn.signIn();
});
In my case, I did not want the user to see the login window automatically. In this case I changed from signIn to signOut. This way, I send the user to another view with an explanatory message and a login button.
GoogleSignInAccount googleSignInAccount = await googleSignIn
.signInSilently(suppressErrors: false)
.catchError((dynamic error) async {
GoogleSignInAccount googleSignInAccount = await _googleSignIn.signOut();
return googleSignInAccount;
});

The dialer is not showing full ussd code eg: *123*1#

I am using the url_launcher plugin for call, but the dialer is not showing the # character:
String url = 'tel:*123#';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
You need to use URL encoding for special character in a URL.
So # equals %23
This will work launch('tel:\*123\%23');
Other Way is to encode the number typed by user and pass it through Uri.encodeFull(urlString) or Uri.encodeComponent(urlString)
Like this.
launch("tel:" + Uri.encodeComponent('*123#'));
Disclaimer: plugin author here.
Do you want the phone call user interface to open or would you rather make the request silently? If you prefer to do it without popping the phone call UI, Android introduced in API level 26 the method sendUssdRequest.
I made a Flutter plugin called ussd_service to be able to easily access it from dart in a Flutter application. It can be used in the following manner:
import 'package:ussd_service/ussd_service.dart';
makeMyRequest() async {
int subscriptionId = 1; // sim card subscription Id
String code = "*21#"; // ussd code payload
try {
String ussdSuccessMessage = await UssdService.makeRequest(subscriptionId, code);
print("succes! message: $ussdSuccessMessage");
} on PlatformException catch (e) {
print("error! code: ${e.code} - message: ${e.message}");
}
};
makeMyRequest();
Hope this helps! Let me know on the Github repo's issues if you have any issue with it.

Flutter: Location package Not working on First Time App Install

My current app uses the Location package (link) to obtain the user's current latitude and longitude to be used to find nearby facilities.
This is the code I am using (similar to the example in the documentation)
Map<String, double> _currentLocation;
Map<String, double> _startLocation;
StreamSubscription<Map<String, double>> _locationSubscription;
String error;
bool _permission = false;
Location _location = new Location();
// Platform messages are asynchronous, so we initialize in an async method.
initPlatformState() async {
Map<String, double> location;
try {
_permission = await _location.hasPermission();
location = await _location.getLocation();
error = null;
} on PlatformException catch (e) {
if (e.code == 'PERMISSION_DENIED') {
error = 'Permission denied';
} else if (e.code == 'PERMISSION_DENIED_NEVER_ASK') {
error = 'Permission denied - please ask the user to enable it from the app settings';
}
location = null;
}
setState(() {
_startLocation = location;
print("Starting coordinates: ${_startLocation["latitude"]}, ${_startLocation["longitude"]}");
});
}
#override
void initState() {
super.initState();
initPlatformState();
_locationSubscription =
_location.onLocationChanged().listen((Map<String,double> result) {
setState(() {
_currentLocation = result;
print("Current coordinates: ${_currentLocation["latitude"]}, ${_currentLocation["longitude"]}");
});
});
}
The only problem I am facing is that whenever there is a fresh install of a new apk of the app, the app does not find the location after location permission has been granted.
After location has been granted I have set up a print statement to print out the user's location but for some reason it is not printing anything the first time only. After I restart the app then it prints out the location just fine.
First Time Opening After Install
After Restarting the App
Any experts that use the Location package that could help me with this problem?
According to plugin’s source code when you invoke getLocation method it asks ActivityCompat.requestPermissions to get required permission and then process. According to docs from Google:
This method functions asynchronously. It returns right away, and after the user responds to the prompt, the system calls the app's callback method with the results
, but flutter plugin has an issue about location callbacks for Android 6+ and as a workaround it is recommended to aim SDK 21.
So it seems that “native” part of this plugin doesn’t play well with Android 6+. There are two workarounds:
Set SDK to 21 version for your Android project, but I would definitely not recommend doing that.
Create some sort of “hello screen”, which will introduce the app and handle permissions there.
Meanwhile, I am really interested in what is wrong with the plugin cause its implementation seems good, so in case I’ll find how to fix it I’ll get back here.

C# - Xamarin - HttpClient - Operation is not valid due to the current state of the object - iOS

I'm working on a cross platform library that makes HTTP requests. It's working fine on Android, but when I try to use it on iOS I'm getting an exception and I can't figure out how to fix it.
Here is my code:
// method from cross platform library
Task.Factory.StartNew(delegate
{
try
{
var client = new HttpClient();
// some other setup stuff
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.post, "http://myurl.com...");
var task = client.SendAsync(request);
task.Wait(); // Exception thrown on this line
var response = task.Result;
var responseString = response.Content.ReadAsStringAsync().Result;
}
catch (Exception e)
{
}
}
On task.Wait(); I get a System.AggregateException with an inner exception of System.InvalidOperationException that says Operation is invalid due to the current state of the object.
Trying to find some solutions, I found that the issue could be cause by calling this on the UI thread. But that's the whole point of wrapping this all in Task.Factory.StartNew.
I've tried everything I know to do and have yet to solve the issue. Any help would be very appreciated.
Edit:
I decided to try my solution on an iPhone simulator. It's an iPhone 6 simulator running iOS 10. My physical device is the same. It works on the simulator, but not the physical device for some reason... very strange.
Edit 2:
Thanks to #YuriS for finding a solution.
From: https://forums.xamarin.com/discussion/36713/issue-with-microsoft-http-net-library-operation-is-not-valid-due-to-the-current-state-of-the-objec
What you can do is:
1) Go to References of ios Project
2) Edit References
3) Check 'System.Net.Http'
Behaviour for android is the same.
There can be few problems described here:
https://forums.xamarin.com/discussion/36713/issue-with-microsoft-http-net-library-operation-is-not-valid-due-to-the-current-state-of-the-objec
https://bugzilla.xamarin.com/show_bug.cgi?id=17936
"Operation is not valid" error at Xamarin.iOS project with HttpClient
http://motzcod.es/post/78863496592/portable-class-libraries-httpclient-so-happy
Seems all post pointing on System.Net.Http
Regardless of the problem there is a better ways doing this.One of them:
public static async Task PostRequest()
{
try
{
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://myuri");
//request.Headers.Add("", "");
var response = await client.SendAsync(request);
var responseString = await response.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
}
}
If you want to wait till function completes you call
await PostRequest();
If you don't need to wait then just omit "await" in the call or use
PostRequest.ContinueWith((t)=>
{
});
Also you need to handle an exception within the function, so probably returning just Task is not the best. I was just basing my answer on original function signature

Resources