Can someone share a sample code of iOS Xamarin PushKit in C#? - c#

I am trying to implement PushKit in my ios app. However the Xamarin document for PushKit is very limited. Do you have a sample code how to use it in Xamarin C#? Thanks a lot.

You can get idea from following link
Swift Code
Binding

If you have pure swift code, then you can download sample code from below link.
Download
import UIKit
import PushKit
class AppDelegate: UIResponder, UIApplicationDelegate,PKPushRegistryDelegate{
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let types: UIRemoteNotificationType = [.Alert, .Badge, .Sound]
application.registerForRemoteNotificationTypes(types)
self. PushKitRegistration()
return true
}
//MARK: - PushKitRegistration
func PushKitRegistration()
{
let mainQueue = dispatch_get_main_queue()
// Create a push registry object
if #available(iOS 8.0, *) {
let voipRegistry: PKPushRegistry = PKPushRegistry(queue: mainQueue)
// Set the registry's delegate to self
voipRegistry.delegate = self
// Set the push type to VoIP
voipRegistry.desiredPushTypes = [PKPushTypeVoIP]
} else {
// Fallback on earlier versions
}
}
#available(iOS 8.0, *)
func pushRegistry(registry: PKPushRegistry!, didUpdatePushCredentials credentials: PKPushCredentials!, forType type: String!) {
// Register VoIP push token (a property of PKPushCredentials) with server
let hexString : String = UnsafeBufferPointer<UInt8>(start: UnsafePointer(credentials.token.bytes),
count: credentials.token.length).map { String(format: "%02x", $0) }.joinWithSeparator("")
print(hexString)
}
#available(iOS 8.0, *)
func pushRegistry(registry: PKPushRegistry!, didReceiveIncomingPushWithPayload payload: PKPushPayload!, forType type: String!) {
// Process the received push
}
}

Related

Converting Kotlin app to Xamarin.Android application

I am trying to translate a Kotlin (Android) application to Xamarin.Android application. I came across a function and not able to figure out what would be equivalent C# code would be.
fun loadDrawable(
activity: Activity,
imageUrl: String?,
#DrawableRes defaultImage: Int,
onLoaded: (image: Drawable) -> Unit) {
val imageToLoad = if (imageUrl.isNullOrEmpty()) defaultImage else imageUrl
Glide.with(activity)
.load(imageToLoad)
.error(defaultImage)
.centerCrop()
.into<CustomTarget<Drawable>>(object : CustomTarget<Drawable>() {
override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) {
onLoaded(resource)
}
override fun onLoadCleared(placeholder: Drawable?) {
placeholder?.let { onLoaded(it) }
}
})
}
In the above function, I am not able to convert the last parameter (onLoaded: (image: Drawable) -> Unit) to the function.
This is how I am currently calling the above function in Kotlin
loadDrawable(requireActivity(), null, R.drawable.bg_default) {
_backgroundManager?.drawable = it
}
I would really appreciate if someone can help me figure out how to convert this code (or something equivalent in functionality in C#)
Thanks
I was able to achieve the same functionality using action delegate
Action<Drawable> onLoaded

Swift Xcode AVMetadataMachineReadableCodeObject encoding versus C# Xamarin AVMetadataMachineReadableCodeObject

I am researching for a Barcode scanning application with iOS iPhone Camera.
I can use Swift to get the string data that I actually need from the image I scan. However, when using Xamarin with the Xamarin implementation of the AVFoundation.AVMetadataObject and AVMetadataMachineReadableCodeObject, I don't get all of the characters. The C# code appears to execute in the same way as the Swift code with two different results.
Example Xcode Swift:
if let metadataObject = metadataObjects.first {
guard let readableObject = metadataObject as? AVMetadataMachineReadableCodeObject else { return }
guard let stringValue = readableObject.stringValue else { return }
AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))
found(code: stringValue)
}
will render something like this: WHICH I WANT
[)>\u{1e}06\u{1d}1SMYDATA\u{1d}S1MYDATA\u{1d}1PMYDATA\u{1d}WMYDATA\u{1d}4LUS\u{1e}\u{4}
Example Xamarin Foundation Code:
var barcodeMetadataObject = transformedMetadataObject as AVMetadataMachineReadableCodeObject;
if (barcodeMetadataObject != null)
{
var barcodeOverlayPath = this.BarcodeOverlayPathWithCorners(barcodeMetadataObject.Corners);
metadataObjectOverlayLayer.Path = barcodeOverlayPath;
// If the metadata object has a string value, display it.
string textLayerString = null;
if (!string.IsNullOrEmpty(barcodeMetadataObject.StringValue))
{
textLayerString = barcodeMetadataObject.StringValue;
}
else
{
// TODO: add Descriptor (line 618 in original iOS sample)
}
will render something like this: WHICH I DO NOT WANT...I WANT THE ENTIRE CHARACTER SET
[)>061SMYDATAS1911500531PMYDATAWMYDATA
So I have this: (Xcode)
[)>\u{1e}06\u{1d}1SMYDATA\u{1d}S1MYDATA\u{1d}1PMYDATA\u{1d}WMYDATA\u{1d}4LUS\u{1e}\u{4}
Versus this:(Xamarin)
[)>061SMYDATAS1911500531PMYDATAWMYDATA
I am not understanding why the implementation in Xamarin would not be supplying all of the same characters of the scan when it essentially acts only as a wrapper.
Does anyone have any idea?

How to open settings programmatically in ios

I was searching for the Xamarin implementation of How to open settings programmatically
Vito-ziv answered it for objective C - what is the correct way to do this in C# for iOS in Xamarin Studio?
For current devices this is only possible in ios8 (ios9 not available at time of writing) (It used to be possible before ios5 apparently - see this blog post from Adrian Stevens at Xamarin - shout out to him for the inspiration for this answer)
To do it in ios8, I did it like this:
var settingsString = UIKit.UIApplication.OpenSettingsUrlString;
var url = new NSUrl (settingsString);
UIApplication.SharedApplication.OpenUrl (url);
Where the above code was called from a click event via delegate class in a UIAlertView click.
Since I am supporting ios7 too, to handle ios7 devices I did this, where the HandleLocationAuthorisation method is called when deciding whether to present a view controller - the user on ios8 and above can choose to go to the settings directly, whereas the user on ios7 has to go there manually.
This example below is checking for location services, but with trivial changes could easily be changed to check for other types of settings.
public bool HandleLocationAuthorisation ()
{
if (CLLocationManager.Status == CLAuthorizationStatus.AuthorizedAlways) {
return true;
} else {
UIAlertView uiAlert;
//iOS 8 and above can redirect to settings from within the app
if (UIDevice.CurrentDevice.CheckSystemVersion(8,0)) {
uiAlert = new UIAlertView
("Location Services Required",
"",
null,
"Return To App","Open Settings");
uiAlert.Delegate = new OpenSettingsFromUiAlertViewDelegate();
uiAlert.Message = "Authorisation to use your location is required to use this feature of the app.";
//ios7 and below has to go there manually
} else {
uiAlert = new UIAlertView
("Location Services Required",
"Authorisation to use your location is required to use this feature of the app. To use this feature please go to the settings app and enable location services",
null,
"Ok");
}
uiAlert.Show ();
return false;
}
}
For completeness, here is the code for the event delgate referenced above:
public class OpenSettingsFromUiAlertViewDelegate : UIAlertViewDelegate {
public override void Clicked (UIAlertView alertview, nint buttonIndex)
{
if (buttonIndex == 1) {
var settingsString = UIKit.UIApplication.OpenSettingsUrlString;
var url = new NSUrl (settingsString);
UIApplication.SharedApplication.OpenUrl (url);
}
}
}
Hope this will help you. This is working in iPhone not sure about working on iPad.
var url = new NSUrl("prefs:root=Settings");
UIApplication.SharedApplication.OpenUrl(url);

Calling static function of C# .NET in C (ICLRRuntimeHost_ExecuteInDefaultAppDomain)

I have this class KernelHelper which is written in C# .NET Framework 2.0. What I want to do is call its static functions in a C program.
namespace Kernel.Client {
public class KernelHelper {
public static int testc(string msg) {
// Removing the message box does not change anything
System.Windows.Forms.MessageBox.Show(msg);
return 0;
}
// ...
}
}
which compiles and does not seem to make any problems so far. But calling ICLRRuntimeHost_ExecuteInDefaultAppDomain() returns 0x80131513 which is according to this the fact that I didn't follow the correct signature convention. But this can not be the problem.
#if defined(_WIN32)
# include <Windows.h>
# define COBJMACROS
# define CINTERFACE
# include <mscoree.h>
#endif
// ...
HRESULT status;
ICLRRuntimeHost *Host;
BOOL Started;
DWORD Result;
Host = NULL;
Started = FALSE;
status = CorBindToRuntimeEx(
NULL,
NULL,
0,
&CLSID_CLRRuntimeHost,
&IID_ICLRRuntimeHost,
(PVOID *)&Host
);
if (FAILED(status)) {
printf("failed 1\n");
}
status = ICLRRuntimeHost_Start(Host);
if (FAILED(status)) {
printf("failed 2\n");
}
Started = TRUE;
status = ICLRRuntimeHost_ExecuteInDefaultAppDomain(
Host,
L"C:\\svn\\Server\\Kernel\\interface\\bin\\Kernel.Client.dll",
L"Kernel.Client.KernelHelper",
L"testc",
L"My message",
&Result
);
if (FAILED(status)) {
printf("failed 3\n");
}
Could anybody help me here?
Edit:
I tried it also without the message box and let the function just return 0 but it didn't change a thing.
Wow, I did not expect to find the solution so fast and on my own. If you experiance the same problem try this. It seems not to work for everyone.
All I needed to do is to change the Platform Target from Any CPU to x86 inside my project properties.
Edit: If anyone can show me another solution I'd still be glad since I can not tell if this might not be a problem anyway changing this setting.

Examples of Quickbase API in C#

I am fairly new to the use of APIs and haven't touched Quickbase until today. I was researching the Quickbase API and it seemed as if all the examples I saw were written in XML or some similar variant. Is there a way to write code in C# that will do the same things that I saw could be done on the Quickbase website's API documentation? If you know of any code examples, please let me know.
There is a QuickBase C# SDK that might help get you started.
using System;
using Intuit.QuickBase.Client;
namespace MyProgram.QB.Interaction
{
class MyApplication
{
static void Main(string[] args)
{
var client = QuickBase.Client.QuickBase.Login("your_QB_username", "your_QB_password");
var application = client.Connect("your_app_dbid", "your_app_token");
var table = application.GetTable("your_table_dbid");
table.Query();
foreach(var record in table.Records)
{
Console.WriteLine(record["your_column_heading"]);
}
client.Logout();
}
}
}
There is also a QuickBase API Wrapper example as well.
Back in 2009 I wrote an .NET API for QuickBase which makes working with the platform easy, it also supports uploading and downloading of attached files.
IQuickBaseService svc = new QuickBaseService("user", "pass", "URL", "token");
Schema schema = svc.GetSchema("DBID");
Console.WriteLine("Schema : {0}", schema.Name);
Console.WriteLine("Variables - ");
for (KeyValuePair<string, string> ent in schema.Variables.OrderBy(en => en.Key)) {
Console.WriteLine("Var: {0} = {1}", ent.Key, ent.Value);
}
for (Query q : schema.Queries) {
// Work with queries.
}
// schema.Children
// schema.Fields
// ...
svc.SignOut();
Performing a query is simple.
QueryResult res;
res = svc.Query("tableid", 1); // Execute query number 1
res = svc.Query("tableid", "{{140.EX.'1'}}") // execute QB query text
foreach (QueryRow row in result.Rows) {
// Do something with row, use get<type>, not all shown here.
// row.GetBool(1);
// row.GetInt(1);
// row.GetLong(1);
// row.GetFloat(1);
// row.GetDouble(1);
// row.GetDecimal(1);
// row.GetString(1);
// row.GetDate(1);
// row.GetDateTime(1);
// row.GetObject(1);
}
QuickBase SDK Code is now moved to github https://github.com/QuickbaseAdmirer/QuickBase-C-Sharp-SDK

Categories

Resources