how can I implement PlacePicker in my project as I can this doable in iOS native by implement this code
#IBAction func pickPlace(_ sender: UIButton) {
let config = GMSPlacePickerConfig(viewport: nil)
let placePicker = GMSPlacePicker(config: config)
placePicker.pickPlace(callback: { (place, error) -> Void in
if let error = error {
print("Pick Place error: \(error.localizedDescription)")
return
}
guard let place = place else {
print("No place selected")
return
}
print("Place name \(place.name)")
print("Place address \(place.formattedAddress)")
print("Place attributions \(place.attributions)")
})
}
how can I do the same in Xamarin.iOS
First I need nuget to include in my project
Second how can I implement the same code
First follow instruction to get google api key
Second Call this method in FinishedLaunching
string googleApiKey = YOUR_KEY_HERE;
public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
{
ConfigureGoogleMaps();
}
void ConfigureGoogleMaps()
{
PlacesClient.ProvideApiKey(googleApiKey);
MapServices.ProvideAPIKey(googleApiKey);
}
Third add this keys in your Info.plist
<key>LSApplicationQueriesSchemes</key>
<array>
<string>googlechromes</string>
<string>comgooglemaps</string>
</array>
Fourth ask user for permission to use his location Info.plist
<key>NSLocationWhenInUseUsageDescription</key>
<string>This application requires location services to work</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>This application requires location services to work</string>
Fifth now we call PlacePicker
var config = new PlacePickerConfig(null);
var placePicker = new PlacePicker(config);
placePicker.PickPlaceWithCallback((result, error) => {
if(error != null){
return;
}
if(result != null){
SelectedPlace = result;
street.Text = result.FormattedAddress;
}
});
If you want know what equivalent to any method name in native looking here
Related
I have tried many different versions of sample / example code, but I cannot get Cloud Messaging to work on iOS (14.5).
The line
Messaging.SharedInstance.Delegate = this;
Always fails with SharedInstance being null.
To test, I created a new Xamarin Forms project, I added the Nuget package Xamarin.Firebase.iOS.CloudMessaging version 4.7.1, and I added the GoogleServices-Info.plist file and set the Build Action to BundleResource.
I added the following code to AppDelegate:
[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate, IUNUserNotificationCenterDelegate, IMessagingDelegate
{
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
try
{
global::Xamarin.Forms.Forms.Init();
Firebase.Core.App.Configure();
LoadApplication(new App());
// Register your app for remote notifications.
if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
{
// iOS 10 or later
var authOptions = UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound;
UNUserNotificationCenter.Current.RequestAuthorization(authOptions, (granted, error) => {
Console.WriteLine(granted);
});
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.Current.Delegate = this;
// For iOS 10 data message (sent via FCM)
Messaging.SharedInstance.Delegate = this;
}
else
{
// iOS 9 or before
var allNotificationTypes = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound;
var settings = UIUserNotificationSettings.GetSettingsForTypes(allNotificationTypes, null);
UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
}
UIApplication.SharedApplication.RegisterForRemoteNotifications();
return true;
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
}
The above code fails on the line "Messaging.SharedInstance.Delegate = this;".
This issue is also on the GitHub issues section:
https://github.com/xamarin/GoogleApisForiOSComponents/issues/486
The program returns: CANCELED: Reason=Error ErrorDetails=WebSocket Upgrade failed with an authentication error (401). Please check for correct subscription key (or authorization token) and region name. SessionId: cbfcdf7f26304343a08de6c398652053
I'm using my free trial subscription key and westus region. This is the sample code found here: https://learn.microsoft.com/en-us/azure/cognitive-services/speech-service/quickstarts/speech-to-text-from-microphone?tabs=unity%2Cx-android%2Clinux%2Cjava-runtime&pivots=programming-language-csharp
using UnityEngine;
using UnityEngine.UI;
using Microsoft.CognitiveServices.Speech;
#if PLATFORM_ANDROID
using UnityEngine.Android;
#endif
#if PLATFORM_IOS
using UnityEngine.iOS;
using System.Collections;
#endif
public class Helloworld : MonoBehaviour
{
// Hook up the two properties below with a Text and Button object in your UI.
public Text outputText;
public Button startRecoButton;
private object threadLocker = new object();
private bool waitingForReco;
private string message;
private bool micPermissionGranted = false;
#if PLATFORM_ANDROID || PLATFORM_IOS
// Required to manifest microphone permission, cf.
// https://docs.unity3d.com/Manual/android-manifest.html
private Microphone mic;
#endif
public async void ButtonClick()
{
// Creates an instance of a speech config with specified subscription key and service region.
// Replace with your own subscription key and service region (e.g., "westus").
var config = SpeechConfig.FromSubscription("yourSubscriptionKey", "yourRegion");
// Make sure to dispose the recognizer after use!
using (var recognizer = new SpeechRecognizer(config))
{
lock (threadLocker)
{
waitingForReco = true;
}
// Starts speech recognition, and returns after a single utterance is recognized. The end of a
// single utterance is determined by listening for silence at the end or until a maximum of 15
// seconds of audio is processed. The task returns the recognition text as result.
// Note: Since RecognizeOnceAsync() returns only a single utterance, it is suitable only for single
// shot recognition like command or query.
// For long-running multi-utterance recognition, use StartContinuousRecognitionAsync() instead.
var result = await recognizer.RecognizeOnceAsync().ConfigureAwait(false);
// Checks result.
string newMessage = string.Empty;
if (result.Reason == ResultReason.RecognizedSpeech)
{
newMessage = result.Text;
}
else if (result.Reason == ResultReason.NoMatch)
{
newMessage = "NOMATCH: Speech could not be recognized.";
}
else if (result.Reason == ResultReason.Canceled)
{
var cancellation = CancellationDetails.FromResult(result);
newMessage = $"CANCELED: Reason={cancellation.Reason} ErrorDetails={cancellation.ErrorDetails}";
}
lock (threadLocker)
{
message = newMessage;
waitingForReco = false;
}
}
}
void Start()
{
if (outputText == null)
{
UnityEngine.Debug.LogError("outputText property is null! Assign a UI Text element to it.");
}
else if (startRecoButton == null)
{
message = "startRecoButton property is null! Assign a UI Button to it.";
UnityEngine.Debug.LogError(message);
}
else
{
// Continue with normal initialization, Text and Button objects are present.
#if PLATFORM_ANDROID
// Request to use the microphone, cf.
// https://docs.unity3d.com/Manual/android-RequestingPermissions.html
message = "Waiting for mic permission";
if (!Permission.HasUserAuthorizedPermission(Permission.Microphone))
{
Permission.RequestUserPermission(Permission.Microphone);
}
#elif PLATFORM_IOS
if (!Application.HasUserAuthorization(UserAuthorization.Microphone))
{
Application.RequestUserAuthorization(UserAuthorization.Microphone);
}
#else
micPermissionGranted = true;
message = "Click button to recognize speech";
#endif
startRecoButton.onClick.AddListener(ButtonClick);
}
}
void Update()
{
#if PLATFORM_ANDROID
if (!micPermissionGranted && Permission.HasUserAuthorizedPermission(Permission.Microphone))
{
micPermissionGranted = true;
message = "Click button to recognize speech";
}
#elif PLATFORM_IOS
if (!micPermissionGranted && Application.HasUserAuthorization(UserAuthorization.Microphone))
{
micPermissionGranted = true;
message = "Click button to recognize speech";
}
#endif
lock (threadLocker)
{
if (startRecoButton != null)
{
startRecoButton.interactable = !waitingForReco && micPermissionGranted;
}
if (outputText != null)
{
outputText.text = message;
}
}
}
}
The sample code you pasted above still has the placeholder values for region and subscription key. Just double checking that you did in fact replace those strings with your own subscription key and region? If that's true, can you please turn on logging, run the code again, and then provide the log? We can help diagnose from there...
To turn on logging, see https://aka.ms/speech/logging.
I am building an app with Core Data. it has always worked for me so far. Recently,
I get not result. no error. it seems that no data is persisted. has anyone ever encountered this weird malfunction?
My viewcontroller: to display contacts list
import UIKit
import CoreData
class ContactsTableViewController: UITableViewController {
#IBAction func addContactAction(_ sender: AnyObject) {
alertDialog()
}
let identifier = "contactCell"
var contacts:[String] = [String]()
var managedContext:NSManagedObjectContext?
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
managedContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
addContacts(numContacts: 30);
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
fetchContacts("") { (list) in
for i in 0..<list.count {
contacts.append(list[i].value(forKey:"name")! as! String)
}
tableView.reloadData()
}
}
func alertDialog() {
//It takes the title and the alert message and prefferred style
let alertController = UIAlertController(title: "Add Contact", message: "", preferredStyle: .alert)
alertController.addTextField { (textField) in
textField.placeholder = "contact"
}
let defaultAction = UIAlertAction(title: "Add", style: .default) { (UIAlertAction) in
let textField = alertController.textFields![0]
self.addContact(name: textField.text!)
self.tableView.reloadData()
}
let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
//now we are adding the default action to our alertcontroller
alertController.addAction(defaultAction)
alertController.addAction(cancelAction)
//and finally presenting our alert using this method
present(alertController, animated: true, completion: nil)
}
}
extension ContactsTableViewController {
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return contacts.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath)
// Configure the cell...
cell.textLabel?.text = contacts[indexPath.row]
return cell
}
// MARK: - Table view delegate
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let contactToDelete = contacts[indexPath.row]
deleteContact(contactToDelete)
contacts.remove(at: (indexPath as NSIndexPath).row)
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
}
extension ContactsTableViewController {
func addContacts(numContacts:Int) {
for i in 1..<numContacts {
let contact = NSEntityDescription.insertNewObject(forEntityName: "Contact", into: managedContext!) as! Contact
contact.setValue("name \(i)", forKeyPath: "name")
(UIApplication.shared.delegate as! AppDelegate).saveContext()
do {
try managedContext?.save()
print("\(contact.value(forKeyPath: "name") as! String)) successfully saved")
} catch {
fatalError("Failure to save context: \(error)")
}
}
self.tableView.reloadData()
}
func addContact(name:String) {
let contact = NSEntityDescription.insertNewObject(forEntityName: "Contact", into: managedContext!) as! Contact
contact.setValue(name, forKeyPath: "name")
(UIApplication.shared.delegate as! AppDelegate).saveContext()
do {
try managedContext?.save()
print("\(contact.value(forKeyPath: "name") as! String)!) successfully saved")
} catch {
fatalError("Failure to save context: \(error)")
}
self.tableView.reloadData()
}
func fetchContacts(_ predicate:String, completion:(_ array:[Contact]) -> ()) {
var arr:[Contact] = [Contact]()
let request:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "Contact")
request.predicate = NSPredicate(format: "name = %#", predicate)
do {
let results = try managedContext?.fetch(request) as! [Contact]
for result in results {
let name = (result as AnyObject).value(forKey: "name") as? String
arr.append(result)
} //for
print(results)
completion(arr as [Contact])
} catch {
print("error fetching results")
} //do
}
func deleteContact(_ name:String) {
fetchContacts(name) { (array) -> () in
for result in array {
let aContact = (result as AnyObject).value(forKey: "name") as? String
if aContact == name {
//delete
self.managedContext?.delete(result)
//save
do {
try self.managedContext!.save()
print("\(aContact) deleted")
} catch {
print("error deleting contact")
} //do
} // if
} //for
}
}
}
My AppDelegate.swift
import UIKit
import CoreData
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "ContactLists_coreData")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
Generated entity class
import Foundation
import CoreData
extension Contact {
#nonobjc public class func fetchRequest() -> NSFetchRequest<Contact> {
return NSFetchRequest<Contact>(entityName: "Contact");
}
#NSManaged public var name: String?
}
the data model. very simple
<img src="https://drive.google.com/file/d/0B1Usy68B1DzYLUduNTlCY092VEk/view" width="1970" height="1084">
datasource and cell identifier are connected properly
fetchContacts("") always returns an empty list because you have no contacts with a name of "". Also whenever you add or insert to core-data you do not see those changes because you are not doing another fetch and updating the contacts array.
Other more general problems with your code:
You should treat the persistentContainer's viewContext as readonly. To write to core-data use performBackgroundTask(_:)
after you create the persistentContainer set container.viewContext.automaticallyMergesChangesFromParent = true
use a fetchedResultsController to sync core-data with your view.
If you are doing lots of changes or inserts to core data like you are doing in addContacts do a single save at the end, not after every insert in the loop.
I'm trying to get dart to play an audio, but everytime I try to play the Audio I get the following error:
Internal error: 'dart:_blink': error: line 248: native function 'AudioBufferSourceNode_noteOn_Callback_RESOLVER_STRING_1_double' (2 arguments) cannot be found
Native_AudioBufferSourceNode_noteOn_Callback(mthis, when) native "AudioBufferSourceNode_noteOn_Callback_RESOLVER_STRING_1_double";
This is the my Audio class:
class Audio {
static List<Audio> _loadQueue = new List<Audio>();
String _url;
bool loaded = false;
AudioBufferSourceNode _source;
Audio(this._url) {
if (audioContext == null) {
_loadQueue.add(this);
}
else {
load();
}
}
void load() {
print("Loading sound: " + _url);
HttpRequest req = new HttpRequest();
req.open("GET", _url);
req.responseType = "arraybuffer";
req.onLoad.listen((e) {
_source = audioContext.createBufferSource();
print("Found sound: " + _url + ". Decoding...");
audioContext.decodeAudioData(req.response).then((buffer) {
_source.buffer = buffer;
_source.connectNode(gainNode);
_source.connectNode(audioContext.destination);
loaded = true;
});
});
req.send();
}
void play() {
if (!loaded) { return; }
_source.noteOn(0);
}
void stop() {
if (!loaded) return;
_source.noteOff(0);
}
static void loadAll() {
_loadQueue.forEach((e) {e.load();});
}
}
The audio context and gain node is created in another class like this:
audioContext = new AudioContext();
gainNode = audioContext.createGain();
gainNode.connectNode(audioContext.destination);
Audio.loadAll();
I don't know what the problem is, especially since it says it's internal, and that it's missing arguments, but the noteOn function only takes one argument.
I was facing the same issue using dart 1.6. It seems noteOn has been replaced by start in the latest spec/implementation.
The AudioBufferSourceNode Interface (http://webaudio.github.io/web-audio-api/#the-audiobuffersourcenode-interface)
Porting notes (https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Porting_webkitAudioContext_code_to_standards_based_AudioContext#Changes_to_methods_used_to_start.2Fstop_AudioBufferSourceNode_and_OscillatorNode)
I am working on a Windows Universal App. I Want to get the Data from a Bluetooth Device to the Windows Phone. I am Using the Concept of RFCommCommunicationTrigger for this Purpose.
Here's the code Snippet I am Using
var rfTrigger = new RfcommConnectionTrigger();
// Specify what the service ID is
rfTrigger.InboundConnection.LocalServiceId = RfcommServiceId.FromUuid(new Guid("<some_base_guid>"));
//Register RFComm trigger
var rfReg = RegisterTaskOnce(
"HWRFCommTrigger",
"BackgroundLibrary.RFBackgroundTask",
rfTrigger, null
);
SetCompletedOnce(rfReg, OnTaskCompleted);
Here the Function of RegisterTaskOnce
static private IBackgroundTaskRegistration RegisterTaskOnce(string taskName, string entryPoint, IBackgroundTrigger trigger, params IBackgroundCondition[] conditions)
{
// Validate
if (string.IsNullOrEmpty(taskName)) throw new ArgumentException("taskName");
if (string.IsNullOrEmpty(entryPoint)) throw new ArgumentException("entryPoint");
if (trigger == null) throw new ArgumentNullException("trigger");
// Look to see if the name is already registered
var existingReg = (from reg in BackgroundTaskRegistration.AllTasks
where reg.Value.Name == taskName
select reg.Value).FirstOrDefault();
Debug.WriteLine("Background task "+ taskName+" is already running in the Background");
// If already registered, just return the existing registration
if (existingReg != null)
{
return existingReg;
}
// Create the builder
var builder = new BackgroundTaskBuilder();
builder.TaskEntryPoint = entryPoint;
builder.Name = taskName;
builder.SetTrigger(trigger);
// Conditions?
if (conditions != null)
{
foreach (var condition in conditions)
{
builder.AddCondition(condition);
}
}
// Register
return builder.Register();
}
Here's the code for SetCompletedOnce this will add a Handler only once
static private void SetCompletedOnce(IBackgroundTaskRegistration reg, BackgroundTaskCompletedEventHandler handler)
{
// Validate
if (reg == null) throw new ArgumentNullException("reg");
if (handler == null) throw new ArgumentNullException("handler");
// Unsubscribe in case already subscribed
reg.Completed -= handler;
// Subscribe
reg.Completed += handler;
}
I have also Written the BackgroundLibrary.RFBackgroundTask.cs
public sealed class RFBackgroundTask : IBackgroundTask
{
public async void Run(IBackgroundTaskInstance taskInstance)
{
BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
try
{
Debug.WriteLine(taskInstance.TriggerDetails.GetType());
taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
Debug.WriteLine("RFComm Task Running");
Debug.WriteLine(taskInstance.TriggerDetails.GetType().ToString());
}
catch (System.Exception e)
{
Debug.WriteLine("RFComm Task Error: {0}", e.Message);
}
deferral.Complete();
}
}
The Run Method is Invoked Every Time The Device tries to Open the Connection.
The type of the Trigger that is obtained (the type I am debugging in the run method of the RFBackgroundTask.cs) is printed as
Windows.Devices.Bluetooth.Background.RfcommConnectionTriggerDetails
But I am Unable use that because I dont have this Class in the BackgroundLibrary project.
The Documentation says that this Provides information about the Bluetooth device that caused this trigger to fire.
It has Variables like Socket,RemoteDevice etc.
I think I am Missing something very simple
Can you please help me out .
Once your background task is launched, simply cast the TriggerDetails object to an RfcommConnectionTriggerDetails object:
public sealed class RFBackgroundTask : IBackgroundTask
{
public async void Run(IBackgroundTaskInstance taskInstance)
{
BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
try
{
taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
RfcommConnectionTriggerDetails details = (RfcommConnectionTriggerDetails)taskInstance.TriggerDetails;
StreamSocket = details.Socket; // Rfcomm Socket
// Access other properties...
}
catch (System.Exception e)
{
Debug.WriteLine("RFComm Task Error: {0}", e.Message);
}
deferral.Complete();
}
}