Objective-C to Swift Conversion Issue - objective-c

I am trying to convert Apple's own sample code which is only written in Objective-C in to Swift.
This is what's in Objective C
.h
#import UIKit;
#class AVCaptureSession;
#interface AAPLPreviewView : UIView
#property (nonatomic) AVCaptureSession *session;
#end
.m
#import AVFoundation;
#import "AAPLPreviewView.h"
#implementation AAPLPreviewView
+ (Class)layerClass
{
return [AVCaptureVideoPreviewLayer class];
}
- (AVCaptureSession *)session
{
AVCaptureVideoPreviewLayer *previewLayer = (AVCaptureVideoPreviewLayer *)self.layer;
return previewLayer.session;
}
- (void)setSession:(AVCaptureSession *)session
{
AVCaptureVideoPreviewLayer *previewLayer = (AVCaptureVideoPreviewLayer *)self.layer;
previewLayer.session = session;
}
#end
So far, this what I came up for Swift:
import AVFoundation
import UIKit
class CamPreviewLayer: UIView
{
var session: AVCaptureSession!
override class func layerClass() -> AnyClass
{
return AVCaptureVideoPreviewLayer
}
func session() -> AVCaptureSession {
var previewLayer: AVCaptureVideoPreviewLayer = self.layer as! AVCaptureVideoPreviewLayer
return previewLayer.session
}
func setSession(session: AVCaptureSession) {
let previewLayer: AVCaptureVideoPreviewLayer = self.layer as! AVCaptureVideoPreviewLayer
previewLayer.session = session
}
}
My Swift code has 3 errors.

You have to remove var session: AVCaptureSession like this.
import AVFoundation
import UIKit
class AVPreviewView : UIView {
override class func layerClass() -> AnyClass {
return AVCaptureVideoPreviewLayer.self
}
func session () -> AVCaptureSession {
return (self.layer as! AVCaptureVideoPreviewLayer).session
}
func setSession(session : AVCaptureSession) -> Void {
(self.layer as! AVCaptureVideoPreviewLayer).session = session;
(self.layer as! AVCaptureVideoPreviewLayer).videoGravity = AVLayerVideoGravityResizeAspect;
}
}
Hope it help!

Related

UISceneDelegate of Method Swizzling in iOS13?

iOS 13 has a new way of sending app lifecycle events:
#implementation SceneDelegate
- (void)sceneDidDisconnect:(UIScene *)scene {
}
- (void)sceneDidBecomeActive:(UIScene *)scene {
}
- (void)sceneWillResignActive:(UIScene *)scene {
}
- (void)sceneWillEnterForeground:(UIScene *)scene {
}
- (void)sceneDidEnterBackground:(UIScene *)scene {
}
#end
SWIZZLE code:
#implementation UIScene (SWIZZLE)
- (void)my_setDelegate:(id <UISceneDelegate>)delegate {
// do custom work
[self my_setDelegate:delegate];
}
+ (void)load {
[self swizzle:#selector(setDelegate:) with:#selector(my_setDelegate:)];
}
#end
typedef IMP *IMPPointer;
BOOL class_swizzleMethodAndStore(Class class, SEL original, IMP replacement, IMPPointer store) {
IMP imp = NULL;
Method method = class_getInstanceMethod(class, original);
if (method) {
const char *type = method_getTypeEncoding(method);
imp = class_replaceMethod(class, original, replacement, type);
if (!imp) {
imp = method_getImplementation(method);
}
}
if (imp && store) { *store = imp; }
return (imp != NULL);
}
#implementation NSObject (RuntimeAdditions)
+ (BOOL)swizzle:(SEL)original with:(IMP)replacement store:(IMPPointer)store {
return class_swizzleMethodAndStore(self, original, replacement, store);
}
#end
Document:
#pragma mark - Delegate
// UIScene is strongly retained by UIKit like UIApplication, however, unlike UIApplication, the delegate may not need to live for the whole lifetime of the process.
// A strong ref here relieves clients of the responsibility of managing the delegate lifetime directly.
#property (nullable, nonatomic, strong) id<UISceneDelegate> delegate;
that is no't work ,how to do swizzle UIWindowScene delegate ?

Swift Completion Handler from Class Objective C

I have this classe in swift
#objc class NetworkManager: NSObject{
var dataRepositories: [repositories]!
static let shared = NetworkManager()
func request_repositories(_ completionHanlder: #escaping ()-> Void){
Alamofire.request("https://api.github.com").responseJSON { (response) in
let data = response.data
// print(response)
do{
let r = try JSONDecoder().decode(repositories.self, from: data!)
self.dataRepositories = [r]
completionHanlder()
}catch let error{
print(error)
return
}
}
}
and I can't call request_repositories in objective c Class
#interface ViewController ()
#property (strong, nonatomic) NetworkManager *man;
#end
#interface NetworkManager ()
-(void)request_repositories;
//-(repositories*)retornar;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.man = [NetworkManager alloc];
[self.man request_repositories];
[[NetworkManager new] request_repositories];
}
#end
I have doubt I can call a completion handler within the objective c class c, if yes how can I do this, I'm new to programming ios and I have doubts, I'm doing it this way because I do not know how to work with json in objective c, if someone has a suggestion better thank you

How set title of a WKInterfaceButton?

I'm trying to change the text of a button once it is pressed however it doesn't work. Am i missing something?
i've been trying to figure my problem for hours.
any help would be appreciated.
h. file
#import <WatchKit/WatchKit.h>
#import <Foundation/Foundation.h>
#interface InterfaceController : WKInterfaceController
{
IBOutlet WKInterfaceButton*playpausebtn;
}
-(IBAction)play;
#end
m. file
#import "InterfaceController.h"
#import <WatchConnectivity/WatchConnectivity.h>
#interface InterfaceController() <WCSessionDelegate>
#end
#implementation InterfaceController
- (void)awakeWithContext:(id)context {
[super awakeWithContext:context];
// Configure interface objects here.
}
- (void)willActivate {
[super willActivate];
if ([WCSession isSupported]) {
WCSession *session = [WCSession defaultSession];
session.delegate = self;
[session activateSession];
}
}
- (void)didDeactivate {
// This method is called when watch view controller is no longer visible
[super didDeactivate];
}
-(IBAction)play{
[playpausebtn setTitle:#"sleep"];
}
It is working fine in Swift-3 Xcode-8.1 .
// InterfaceController.swift
// WatchKit Extension
import WatchKit
import Foundation
import WatchConnectivity
class InterfaceController: WKInterfaceController,WCSessionDelegate {
#IBOutlet var textLabel: WKInterfaceLabel!
var session:WCSession?
override func awake(withContext context: Any?) {
super.awake(withContext: context)
// Configure interface objects here.
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
checkSupportOfSession()
changeAttributeOfText()
}
#IBOutlet var buttonOutlet: WKInterfaceButton!
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
func checkSupportOfSession() {
if( WCSession.isSupported() ) {
self.session = WCSession.default()
self.session?.delegate = self
self.session?.activate()
}
}
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
print("session")
}
func session(_ session: WCSession, didReceiveMessage message: [String : Any]) {
let message:String = message["textIndex"] as! String
textLabel.setText(message)
print(message)
}
func changeAttributeOfText() {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .left
let font = UIFont.boldSystemFont(ofSize: 12)
let attributes:Dictionary = [NSParagraphStyleAttributeName:paragraphStyle , NSFontAttributeName:font ]
let attributeString:NSAttributedString = NSAttributedString(string: "HELLO", attributes: attributes)
textLabel.setAttributedText(attributeString)
}
//Change the ButtonTitle after click
#IBAction func buttonClicked() {
buttonOutlet.setTitle("textNew")
}}
Demo App

Convert Objective-C code to Swift: delegate

I'm now learning a function which is written in Objective-C. But I don't know Objective-C language. When I'm converting the code to Swift, I got stuck at the delegate functions.
The code in .h file is:
#import <UIKit/UIKit.h>
#protocol SCPopViewDelegate <NSObject>
#optional
- (void)viewHeight:(CGFloat)height;
- (void)itemPressedWithIndex:(NSInteger)index;
#end
#interface SCPopView : UIView
#property (nonatomic, weak) id <SCPopViewDelegate>delegate;
#property (nonatomic, strong) NSArray *itemNames;
#end
and I'm trying to convert the code as:
protocol popViewDelegate: class {
func itemPressedWithIndex(index: Int)
func viewHeight(height: CGFloat)
}
but for the three last sentences, i don’t know how to deal with them, especially the one with id and delegate.
Can I get any help, please? I will do more effort to learn Swift. Thank you very much!
Swift 4.2
Converted Code for Swift 4.2
protocol SCPopViewDelegate: class {
func viewHeight(_ height: CGFloat)
func itemPressed(with index: Int)
}
extension SCPopViewDelegate {
func viewHeight(_ height: CGFloat) {}
func itemPressed(with index: Int) {}
}
class SCPopView: UIView {
weak var delegate: SCPopViewDelegate?
var itemNames: [Any] = []
}
This code is based on code converted by an online code conversion tool, the link to the original generated code.
The definition of the protocol ends with the first #end statement.
The #interface after that is the definition of an Objective-C class, SCPopView.
You don't need to care about the latter part if you're just trying to define the protocol in Swift.
FYI:
#interface someClass: NSObject
is equivalent to
class someClass: NSObject
In Swift.
import UIKit
#objc protocol SCPopViewDelegate{
optional func viewHeight(height: Float)
optional func itemPressedWithIndex(index : Int)
}
class DGViewController: UIViewController {
var delegate:SCPopViewDelegate! = nil
override func viewDidLoad() {
super.viewDidLoad()
delegate?.viewHeight?(Float(self.view.frame.size.height))
}
And in the class that implements the delegate
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
var vc = DGViewController()
vc.delegate = self
vc.view.frame = self.view.frame;
vc.view.backgroundColor = (UIColor.redColor())
self.presentViewController(vc, animated: true) { () -> Void in}
}
func viewHeight(height: Float) {
println(height)
}

Set Delegate in a mixed language project

I have an XCode6 mixed-language project, combining Swift and Objective C.
I created a Swift-based SingleView application, then added 2 Objective-C files, having contents as below:
Singleton.h
#import <Foundation/Foundation.h>
#protocol SingletonDelegate <NSObject>
#optional
- (void)methodCalled;
#end
#interface Singleton : NSObject
#property (weak, nonatomic) id <SingletonDelegate> singletonDelegate;
+ (id)sharedSingleton;
- (void)method;
#end
Singleton.m
#import "Singleton.h"
static Singleton *shared = nil;
#implementation Singleton
- (id)init {
self = [super init];
if (self) {
}
return self;
}
#pragma mark - Interface
+ (Singleton *)sharedSingleton {
static dispatch_once_t pred;
dispatch_once(&pred, ^{
shared = [[Singleton alloc] init];
});
return shared;
}
- (void)method {
[self.singletonDelegate methodCalled];
}
#end
After setting up bridging header file as XCode suggested, I added #import "Singleton.h" into it.
In ViewController.swift, I tried to set singletonDelegate but always failed:
import UIKit
class ViewController: UIViewController, SingletonDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Singleton.sharedSingleton().singletonDelegate = self // FAILED HERE!!!
Singleton.sharedSingleton().method()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
The error message is:
Cannot assign to the result of this expression
Could any one show me how to fix this? (I am new in integrating Objective-C into Swift project)
Thanks in advance,
Create a class variable. Then set its delegate.
let singleton: Singleton = Singleton.sharedSingleton()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
singleton.singletonDelegate = self
//Singleton.sharedSingleton().singletonDelegate = self // FAILED HERE!!!
//Singleton.sharedSingleton().method()
}
fun methodCalled() {
//This method gets called from the Singleton class through the delegate
}