Friday, December 18, 2020

Explain how bitcode works

https://jonasdevlieghere.com/embedded-bitcode/ Bitcode is the intermediate representation used by the LLVM compiler and contains all the information required to recompile an application. Having the bitcode present, in addition to machine code, Apple can further optimize applications by compiling and linking specifically for the user's target device. This is one approach to app thinning, which aims to achieve smaller binaries and therefore more free space on your iDevice. It will most likely replace Apple's current approach, where a developer uploads a fat binary to the App Store, which contains machine code for each target architecture.

Wednesday, December 2, 2020

How to create abstract functions in Swift

 class BaseClass {

    func abstractFunction() {
        preconditionFailure("This method must be overridden") 
    } 
}

class SubClass : BaseClass {
     override func abstractFunction() {
         // Override
     } 
}
https://stackoverflow.com/questions/24110362/abstract-functions-in-swift-language

Wednesday, November 18, 2020

Get Value For Selector

func getValueForSelector(cls: AnyClass, selector: Selector) -> AnyObject {

  let method = class_getInstanceMethod((cls), selector)!

  let methodIMP : IMP! = method_getImplementation(method)

  let newAmountObj = unsafeBitCast(methodIMP,to:(@convention(c)(AnyClass?,Selector,Any?)->Any).self)(cls,selector, nil) as AnyObject

  return newAmountObj

}

Accessor Search Patterns

Search Pattern for the Basic Setter

The default implementation of setValue:forKey:, given key and value parameters as input, attempts to set a property named key to value (or, for non-object properties, the unwrapped version of  value, as described in Representing Non-Object Values) inside the object receiving the call, using the following procedure:

  1. Look for the first accessor named set<Key>: or _set<Key>, in that order. If found, invoke it with the input value (or unwrapped value, as needed) and finish.

  2. If no simple accessor is found, and if the class method accessInstanceVariablesDirectly returns YES, look for an instance variable with a name like _<key>_is<Key><key>, or is<Key>, in that order. If found, set the variable directly with the input value (or unwrapped value) and finish.

  3. Upon finding no accessor or instance variable, invoke setValue:forUndefinedKey:. This raises an exception by default, but a subclass of NSObject may provide key-specific behavior.


Tuesday, November 17, 2020

3 ways to call ObjC methods from swift

 There are three ways to dynamically call the method in this class:

1. Using performSelector()

let selector = NSSelectorFromString("titleForItem:withTag:")
let unmanaged = toolbar.perform(selector, with: "foo", with: "bar")
let result = unmanaged?.takeRetainedValue() as? String

2. Using methodForSelector() with @convention(c)

typealias titleForItemMethod = @convention(c)
    (NSObject, Selector, NSString, NSString) -> NSString
  
let selector = NSSelectorFromString("titleForItem:withTag:")
let methodIMP = toolbar.method(for: selector)
let method = unsafeBitCast(methodIMP, to: titleForItemMethod.self)
let result = method(toolbar, selector, "foo", "bar")

3. Using NSInvocation

It's only available in Objective-C.
SEL selector = @selector(titleForItem:withTag:);
NSMethodSignature *signature = [toolbar methodSignatureForSelector:selector];

NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
invocation.target = toolbar;
invocation.selector = selector;

NSString *argument1 = @"foo";
NSString *argument2 = @"bar";
[invocation setArgument:&argument1 atIndex:2];
[invocation setArgument:&argument2 atIndex:3];

[invocation invoke];

NSString *result;
[invocation getReturnValue:&result];

Or, we can use Dynamic ðŸŽ‰

let result = Dynamic(toolbar)            // Wrap the object with Dynamic
    .titleForItem("foo", withTag: "bar") // Call the method directly!

More details on how the library is designed and how it works here.

Calling selectors using Dynamic library



let result = Dynamic(toolbar)            // Wrap the object with Dynamic
    .titleForItem("foo", withTag: "bar") // Call the method directly!


 https://github.com/mhdhejazi/Dynamic

https://github.com/mhdhejazi/Dynamic/blob/master/Tests/DynamicTests/DynamicTests.swift


Wednesday, November 11, 2020

How to call methods using selectors

func getClass(_ classNameString: String) -> AnyClass {
  let clazz = objc_getMetaClass(classNameString)
  return clazz as! AnyClass
}

func callMethod2(clazz: AnyClass, method: String) -> AnyObject {
  let selector : Selector = NSSelectorFromString(method)
  let method = class_getInstanceMethod((clazz), selector)!
  let methodIMP : IMP! = method_getImplementation(method)
  let newAmountObj = unsafeBitCast(methodIMP,to:(@convention(c)(AnyClass?,Selector,Any?)->Any).self)(clazz,selector, nil) as AnyObject
  return newAmountObj
}

func callMethod(clazz: AnyClass, method: String) -> AnyObject? {
  let selector : Selector = NSSelectorFromString(method)
  guard let method = class_getClassMethod((clazz), selector) else { return nil }
  let methodIMP : IMP! = method_getImplementation(method)
  let newAmountObj = unsafeBitCast(methodIMP,to:(@convention(c)(AnyClass?,Selector,Any?)->Any).self)(clazz,selector, nil) as AnyObject
  return newAmountObj
}

func callMethod(classNameString: String, method: String) -> AnyObject? {
  let clazz: AnyClass = getClass(classNameString)
  let newAmountObj = callMethod(clazz: clazz, method: method)
  return newAmountObj
}

Dealing with managed and unmanaged objects

While most CoreFoundation APIs have been annotated, some significant chunks have yet to receive attention. As of this writing, the Address Book framework seems the highest profile of the unannotated APIs, with several functions taking or returning Unmanaged-wrapped types.

An Unmanaged<T> instance wraps a CoreFoundation type T, preserving a reference to the underlying object as long as the Unmanaged instance itself is in scope. There are two ways to get a Swift-managed value out of an Unmanaged instance:

  • takeRetainedValue(): returns a Swift-managed reference to the wrapped instance, decrementing the reference count while doing so—use with the return value of a Create Rule function.
  • takeUnretainedValue(): returns a Swift-managed reference to the wrapped instance without decrementing the reference count—use with the return value of a Get Rule function.


 https://nshipster.com/unmanaged/

 

converting an unmanaged object to a string

 https://vandadnp.wordpress.com/2014/07/07/swift-convert-unmanaged-to-string/

Monday, November 2, 2020

how to get a certificate in java

 http://littlesvr.ca/grumble/2014/07/21/android-programming-connect-to-an-https-server-with-self-signed-certificate/

Sunday, November 1, 2020

Merge dictionaries in Swift

Keep the current value (value in dictionary1) if there is a duplicate key 

Keep the new value (value in dictionary2) if there is a duplicate key 

 https://www.tutorialkart.com/swift-tutorial/merge-dictionaries-in-swift/

Convert Any object to a String

String(describing: someValue)

Wednesday, May 27, 2020

c++ switch Vs hash map optimization

  • cost(Hash_table) >> cost(direct_lookup_table)
  • cost(direct_lookup_table) ~= cost(switch) if your compiler translates switches into lookup tables. 
  • cost(switch) >> cost(direct_lookup_table) (O(N) vs O(1)) if your compiler does not translate switches and use conditionals, but I can't think of any compiler doing this.
  • But inlined direct threading makes the code less readable.

Wednesday, September 25, 2019

iOS returns a temporary IP address if wifi is turned off and airplane mode is on 196.254.x.x

this article talks about the different ip ranges
https://kb.iu.edu/d/aoyj

How to create a custom header in tableview section that stretch when orientation changes

    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == TableSections.OtherDevices.rawValue {
            let v = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.width, height: SetupConstants.DEFAULT_HEADER_HEIGHT))

            self.spinner.center = CGPoint(x:(tableView.bounds.size.width - (SetupConstants.DEFAULT_HEADER_HEIGHT / 2)), y:SetupConstants.DEFAULT_HEADER_HEIGHT/2)
            spinner.hidesWhenStopped = true
            spinner.startAnimating()
            spinner.color = UIColor.blue
            
            v.addSubview(spinner)
            spinner.autoresizingMask = .flexibleLeftMargin
            v.autoresizingMask = .flexibleWidth
            return v
        }
        return nil
    }

Monday, September 23, 2019

Print c++ map to logs

// TODO: (ravij): remove this code after testing is complete >>>
  long unsigned mySize = static_cast<long unsigned>(parameterMap.size());
  ZF_LOGD("number of items in teh config map %lu", mySize);
  for ( auto it = parameterMap.begin(); it != parameterMap.end(); ++it )
    std::cout << " " << it->first << ":" << it->second;

  std::cout << std::endl;

Friday, August 2, 2019

Structure of a framework

MyFramework.framework/
   MyFramework  -> Versions/Current/MyFramework
   Resources    -> Versions/Current/Resources
   Versions/
      A/
         MyFramework
         Headers/
            MyHeader.h
         Resources/
            English.lproj/
               InfoPlist.strings
            Info.plist
      Current  -> A

Monday, July 29, 2019

Thursday, July 25, 2019

How to add buttons to the navigation bar

http://swiftdeveloperblog.com/code-examples/create-uibarbuttonitem-programmatically/

NOTE:
remember to pass in a navigation controller

 let navController = UINavigationController(rootViewController: viewController) // Creating a navigation controller with VC1 at the root of the navigation stack.
        
        DispatchQueue.main.async {
        
            self.navigationController?.visibleViewController?.present(navController, animated: true, completion: nil)
           

        }

Thursday, February 14, 2019

How best to create static functions

///////////////////////////////
In Struct:

struct MyStruct {
    static func something() {
        println("Something")
    }
}
Called via:
MyStruct.something()

///////////////////////////////
In Class

class MyClass {
    class func someMethod() {
        println("Some Method")
    }
}
called via:

MyClass.someMethod()

Tuesday, February 12, 2019

How to check what is inside a Assets.car file

xcrun --sdk iphoneos assetutil --info

EXAMPLE OUTPUT:

 {
    "AssetType" : "Image",
    "BitsPerComponent" : 8,
    "ColorModel" : "Monochrome",
    "Colorspace" : "gray gamma 22",
    "DeploymentTarget" : "2018",
    "Idiom" : "universal",
    "Image Type" : "kCoreThemeOnePartScale",
    "Name" : "bluetooth_on",
    "Opaque" : false,
    "PixelHeight" : 54,
    "PixelWidth" : 54,
    "RenditionName" : "baseline_bluetooth_black_18pt_3x.png",
    "Scale" : 3,
    "SizeOnDisk" : 338,
    "Template Mode" : "template"
  },
  {
    "AssetType" : "Image",
    "BitsPerComponent" : 8,
    "ColorModel" : "Monochrome",
    "Colorspace" : "gray gamma 22",
    "DeploymentTarget" : "2018",
    "Idiom" : "universal",
    "Image Type" : "kCoreThemeOnePartScale",
    "Name" : "keypad_black_off",
    "Opaque" : false,
    "PixelHeight" : 168,
    "PixelWidth" : 168,
    "RenditionName" : "keypad_black_off@3x.png",
    "Scale" : 3,
    "SizeOnDisk" : 338,
    "Template Mode" : "automatic"
  },

Monday, February 11, 2019

How to cleanly launch VC using storyboard


enum AppStoryboard : String {
    case Main = "Main"
    case PreLogin = "PreLogin"
    case Timeline = "Timeline"
    var instance : UIStoryboard {
      return UIStoryboard(name: self.rawValue, bundle: Bundle.main)
    }
}
// USAGE :

let storyboard = AppStoryboard.Main.instance

// Old Way

let storyboard = UIStoryboard(name: “Main”, bundle: Bundle.main)

https://medium.com/@gurdeep060289/clean-code-for-multiple-storyboards-c64eb679dbf6

Friday, February 8, 2019

How to create an app with access control management

https://medium.com/ios-os-x-development/access-control-management-with-swift-cc3c3d68cbc3

What are the View Controller's lifecycle events

# Controller Lifecycle events order ?
There are a few different lifecycle event

- loadView
Creates the view that the controller manages. It’s only called when the view controller is created and only when done programatically. It is responsible for making the view property exist in the first place.

- viewDidLoad
Called after the controller’s view is loaded into memory. It’s only called when the view is created.

- viewWillAppear
It’s called whenever the view is presented on the screen. In this step the view has bounds defined but the orientation is not applied.

- viewWillLayoutSubviews
Called to notify the view controller that its view is about to layout its subviews. This method is called every time the frame changes

- viewDidLayoutSubviews
Called to notify the view controller that its view has just laid out its subviews. Make additional changes here after the view lays out its subviews.

- viewDidAppear
Notifies the view controller that its view was added to a view hierarchy.

- viewWillDisappear
Before the transition to the next view controller happens and the origin view controller gets removed from screen, this method gets called.

- viewDidDisappear
After a view controller gets removed from the screen, this method gets called. You usually override this method to stop tasks that are should not run while a view controller is not on screen.

- viewWillTransition(to:with:)
When the interface orientation changes, UIKit calls this method on the window’s root view controller before the size changes are about to be made. The root view controller then notifies its child view controllers, propagating the message throughout the view controller hierarchy.`

How to add a path when saving data to the documents folder

let filemgr = FileManager.default
let dirPaths = filemgr.urls(for: .documentDirectory, in: .userDomainMask)
let docsURL = dirPaths[0]

let newDir = docsURL.appendingPathComponent("data").path
do {
    try filemgr.createDirectory(atPath: newDir,
                withIntermediateDirectories: true, attributes: nil)
    } catch let error as NSError {
            print("Error: \(error.localizedDescription)")
}

How to create a Singleton

class Environment: NSObject {
    private var values = [String:String]()
    let skipLogin:Bool
    let baseURL:String
    let baseAuthURL:String

    class var shared: Environment {
        struct Singleton {
            static let instance = Environment()
        }
        return Singleton.instance
    }
}  

How to create a simple animation

https://blog.usejournal.com/ios-animations-uiview-part-1-d94305bee2f5

Thursday, February 7, 2019

How to create a custom cell with callback when row selected

custom cell:

import UIKit

typealias ActionCallback = () -> Void

class ActionLinkCell: UITableViewCell {
    var cb: ActionCallback? = nil

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: UITableViewCell.CellStyle.default, reuseIdentifier: reuseIdentifier)
        self.accessoryType = .disclosureIndicator
        self.textLabel?.textColor = self.tintColor
    }
    
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        
        // Configure the view for the selected state
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ActionLinkCell.handleIsTap(_:)))
        self.addGestureRecognizer(tapGesture)
        
    }

    @objc func handleIsTap(_ sender: UIGestureRecognizer) {
        debugPrint("\(#function)")
        if let callback = self.cb {
            callback()
        }
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    func config(title: String, callback: ActionCallback? = nil) {
        self.textLabel?.text = title
        self.setNeedsDisplay()
        self.cb = callback
    }

}

calling code:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier:    bluetoothActionLinkCellId, for: indexPath) as! ActionLinkCell
    let message = NSLocalizedString("Pair device using Bluetooth", comment: "")
    cell.config(title: message) {
    //MY CODE GOES HERE
    }
    return cell
}


Wednesday, January 30, 2019

How to check if bluetooth is enabled

viewDidLoad:

self.cbCentralManager = CBCentralManager(delegate: self, queue: nil, options: [CBCentralManagerOptionShowPowerAlertKey : false])
self.cbCentralManager.delegate = self


handle:

    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        switch central.state {
        case .poweredOn:
            btEnabled = true
            break
        case .poweredOff:
            btEnabled = false
            break
        case .resetting:
            break
        case .unauthorized:
            break
        case .unsupported:
            break
        case .unknown:
            break
        default:
            break
        }
    }




Protocol:

extension MyVC: CBCentralManagerDelegate {
}