How can I turn this line of objective-C code into Swift? - ios

#protocol YozioMetaDataCallbackable <NSObject>
/**
* implement this method to handle the callback from new install or deeplink.
*
* #param targetViewControllerName - the target view controller that you configured in Yozio Web Console.
* #param metaData - the meta data passed to your app.
*/
- (void) onCallbackWithTargetViewControllerName:(NSString *)targetViewControllerName
andMetaData:(NSDictionary *)metaData;
#end
I tried subclassing it to Swift:
class YozioCaller: NSObject , YozioMetaDataCallbackable {
func onCallbackWithTargetViewControllerName(targetViewControllerName: NSString!, andMetaData metaData: NSDictionary!){
}
}
But it states that it doesn't conform.

In swift, use String for NSString and [ NSObject: AnyObject ] for NSDictionary.
func
onCallbackWithTargetViewControllerName(
targetViewControllerName: String?
, andMetaData: [ NSObject: AnyObject ]?
){
}

Related

How to auto-generate parameter names when Swift closures are exposed to Objective-C?

I'm writing some Swift code as follows:
#objc public class SwiftClass: NSObject {
#objc func method(completion: (Int) -> Void) {
completion(100)
}
}
Then I need to call this method from another class written in Objective-C. However, when I type this method name, Xcode auto-complete it as follows:
#implementation ObjectiveCClass
- (void)testMethod {
SwiftClass *obj = [SwiftClass new];
[obj methodWithCompletion:^(NSInteger) { // Xcode complains here: Parameter name omitted
}];
}
#end
The closure parameter name is missing when it is exported to Objective-C, so I have to manually specify a name to it, like ^(NSInteger aNum).
So is there any way to auto-generate this missing closure parameter?

Error while assigning Swift delegate to Objective-C object

This is my Swift class :
class MyClass : NSObject {
public var inAppMessagesController: MPInAppMessagesController!
fun myFunction() {
self.inAppMessagesController.inAppInteractionDelegate = self // Error in this line - Cannot assign value of type 'MyClass' to type 'MPInAppMessageControllerDelegate?'
}
}
extension MyClass : MPInAppMessageControllerDelegate {
// Functions
}
As stated in comments, this is the error -
Cannot assign value of type 'MyClass' to type
'MPInAppMessageControllerDelegate?'
inAppInteractionDelegate in Objective-C class MPInAppMessagesController :
#interface MPInAppMessagesController : NSObject
#property (nonatomic, weak, nullable) id <MPInAppMessageControllerDelegate> inAppInteractionDelegate;
#end
MPInAppMessageControllerDelegate declared in MPInAppMessagesController.h :
#protocol MPInAppMessageControllerDelegate<NSObject>
// Functions
#end
The only missing part is you need to include this class inside the bridging file
#import "MPInAppMessagesController.h"
Look here to a SwiftObjc

Tracing an "unrecognized selector sent to instance" exception in Xamarin

I'm trying to get this to work, but I must have made a mistake somewhere. This is the Delegate class (snipped down) as per the C headers:
#protocol PaymentEngineMiddlewareDelegate <NSObject>
#required
/*!
#brief Delegate method for startTransaction.
#param transResponse - Contains all the transaction response info from the gateway
*/
-(void)transactionComplete :(PaymentEngineTransactionResponse *)transResponse;
#optional
/*!
#brief Delegate method for device connected. The method gets called when the device is connected
*/
-(void)deviceConnected;
/*!
#brief Delegate method for device disconnected. The method gets called when the device is disconnected
*/
-(void)deviceDisconnected;
#end
For this, I have:
// #interface PaymentEngineMiddlewareDelegate : NSObject
[BaseType(typeof(NSObject))]
[Model]
[Protocol]
interface PaymentEngineMiddlewareDelegate
{
[Abstract]
[Export("transactionComplete:")]
void TransactionComplete(PaymentEngineTransactionResponse transResponse);
[Export("deviceConnected")]
void DeviceConnected();
[Export("deviceDisconnected")]
void DeviceDisconnected();
}
Then for the PaymentEngineMiddleware class, the header has this:
#interface PaymentEngineMiddleware : NSObject
+ (PaymentEngineMiddleware *) getInstance;
#property(nonatomic, strong) id<PaymentEngineMiddlewareDelegate> delegate;
//------------------------------Device Methods------------------------------
/*!
#brief This method must be called before starting any transaction. Use it to connect to a device.
#param deviceName The name of the device such as icmp or castle
#param setDelegate Sets to self
*/
-(void)setDevice :(NSString *)deviceName :(id)setDelegate;
#end
And for that, I have:
// #interface PaymentEngineMiddleware : NSObject
[BaseType(typeof(NSObject))]
[Protocol]
interface PaymentEngineMiddleware
{
// +(id)getInstance;
[Static]
[Export("getInstance")]
PaymentEngineMiddleware GetInstance { get; }
[Export("delegate", ArgumentSemantic.Retain)]
PaymentEngineMiddlewareDelegate Delegate { get; set; }
[Export("setDevice:setDelegate:")]
void SetDevice(string deviceName, PaymentEngineMiddlewareDelegate setDelegate);
}
In code, when I try to call the "middleware.SetDevice('name', this);" where this is a class that inherits from the delegate, I get the exception.
Is there anything obvious that I missed or got wrong?
Your selector for setDevice method is wrong.
The proper selector for -(void)setDevice :(NSString *)deviceName :(id)setDelegate method is setDevice::. This is because the second parameter in this method doesn't have an external name.
The final entry for your binding should look like this
[Export("setDevice::")]
void SetDevice(string deviceName, PaymentEngineMiddlewareDelegate setDelegate);
You can read more about how the methods signatures in Objective-C are constructed in the Apple docs.
Also look in the Storyboard file for the component action in properties which is not implemented in the code.
in my case I have given touch insideup action for button in storyboard file but not implemented that in a code. after implementing this issue is no more.

How use Objective-c method in my Swift Class

Hello I want to use this method inside my swift class, already create the header, but I only manage to access the method (setApiKey). this is the code in objective c
#import <Foundation/Foundation.h>
#class CLQResponseHeaders, CLQError;
#class CLQToken;
NS_ASSUME_NONNULL_BEGIN
#interface Culqi : NSObject
/**
* gets singleton object.
* #return singleton
*/
+ (Culqi *_Nonnull)sharedInstance;
+ (void)setApiKey:(NSString *_Nonnull)apiKey;
#pragma mark - Tokens
- (void)createTokenWithCardNumber:(NSString *_Nonnull)cardNumber
cvv:(NSString *_Nonnull)cvv
expirationMonth:(NSString *_Nonnull)expirationMonth
expirationYear:(NSString *_Nonnull)expirationYear
email:(NSString *_Nonnull)email
metadata:(NSDictionary * _Nullable)metadata
success:(void (^_Nullable)(CLQResponseHeaders *_Nonnull responseHeaders, CLQToken * _Nonnull token))success
failure:(void (^_Nullable)(CLQResponseHeaders *_Nonnull responseHeaders, CLQError * _Nonnull businessError, NSError * _Nonnull error))failure;
#end
NS_ASSUME_NONNULL_END
My swift code is
import Foundation
import UIKit
class RegisterController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//THIS METHOD CALL SUCCESS
Culqi.setApiKey("")
}
}
Update: the method setApiKey is accessible, what happens is that I can not call the method "createTokenWithCardNumber"
Declare your function/method setApiKey in header file of your Objective-C class.
// Move following line/code to header file (.h) of your objective-c class
+ (void)setApiKey:(NSString *_Nonnull)apiKey;
Your method createTokenWithCardNumber is an instance method (not a class method), you need to create an instance of your class to access it. Try this,
let c = Culqi()
c.createTokenWithCardNumber(#<your parameter arguments>#)
// or use shared instance
Culqi.sharedInstance().createTokenWithCardNumber(#<your parameter arguments>#)

iOS - Not able to access Static method of swift class

I want to access Swift code in Objective-c.
I have written one class in swift which contains static method. I want to access that Static Method in objective C Class.
Here is Class declaration:
#objc class LocalizedResource: NSObject {
/*!
* #discussion This function will get localize string for key
* #param key Localize key
* #return String for locaized key
* #code LocalizedResource.getStringForKey(key);
*/
static func getStringForKey(key:String) -> String {
let frameworkBundle = NSBundle.mainBundle()
let value = frameworkBundle.localizedStringForKey(key, value: nil, table: nil)
return value;
}
}
I have made following settings for it:
Product Module Name : MyProject
Defines Module : YES
Embedded Content Contains Swift : YES
Install Objective-C Compatibility Header : YES
Objective-C Bridging Header : $(SRCROOT)/MySources/SwiftBridgingHeader.h
Also I have added #Obj before my class declaration in Swift class.
I have import MyProject-Swift.h in the .m file where I want to access that method.
But when I am trying to access it, it is not allowing me to access that static method.
Is any one having solution for it? Is there something missing?
Thnaks.
Note in Swift 4 and the build setting swift 3 #objc inference is default, we must explicitly mark function as #objc, or it will not generate class function in Swift bridge header.
From your comment:
I am calling this method as follows:
errorMessage.text = LocalizedResource.getStringForKey(#"TIMED_OUT_ERROR");
In Objective-C, the "dot syntax" is used for properties,
not for methods. The correct call should be
errorMessage.text = [LocalizedResource getStringForKey:#"TIMED_OUT_ERROR"];

Resources