BlackM BlackM - 1 month ago 20
iOS Question

initWithDelegate for Objective-C class

I have import this Objective-C class in a swift project.
MMLANSCanner.h

#import <Foundation/Foundation.h>

@class Device;
@protocol MMLANScannerDelegate;
@protocol MMLANScannerDelegate <NSObject>
@required
- (void)lanScanDidFinishScanningWithStatus:(MMLanScannerStatus)status;
- (void)lanScanDidFailedToScan;
@optional
- (void)lanScanProgressPinged:(float)pingedHosts from:(NSInteger)overallHosts;
@end

#pragma mark - Public methods
@interface MMLANScanner : NSObject
-(instancetype)initWithDelegate:(id <MMLANScannerDelegate>)delegate;
@property(nonatomic,weak) id<MMLANScannerDelegate> delegate;
@property(nonatomic,assign,readonly)BOOL isScanning;
- (void)start;
- (void)stop;
@end


I successfully created the bridging header and make the MainVC.Swift to conform to MMLANScannerDelegate.
Then I tried to initialise the MMLanScanner with delegate
self
.

import UIKit
import Foundation

class MainVC: UIViewController, MMLANScannerDelegate {

var presenter = MMLANScanner(delegate:self)

override func viewDidLoad() {
super.viewDidLoad()

// Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

func lanScanDidFindNewDevice(_ device: Device!) {

}

func lanScanDidFailedToScan() {

}

func lanScanDidFinishScanning(with status: MMLanScannerStatus) {

}

func lanScanProgressPinged(_ pingedHosts: Float, from overallHosts: Int) {

}
}


But I get error:


Argument passed to call that takes no arguments


Any ideas how to implement initWithDelegate function that I had in Objective-C?

par par
Answer

MLANScanner doesn't take a delegate argument to its init method (delegate is a property of MLANScanner).

You also have a problem with the definition of your presenter property since self isn't valid at the time MainVC is created.

Do this instead:

let presenter = MLANScanner()

override func viewDidLoad() {
    super.viewDidLoad()

    presenter.delegate = self
}

based on edit to question:

var presenter: MLANScanner!

override func viewDidLoad() {
    super.viewDidLoad()

    presenter = MLANScanner(delegate: self)
}

Note: My edited answer assumes there is a Swift bridge somewhere that exposes an init(delegate:) method. There may not be and making one is beyond the scope of this question. Since the delegate is not private or read-only you can almost certainly use the first version I posted.