Archivi categoria: Programming

How to create an IVR that reads from Google Sheet with Amazon Connect and AWS Lambda

In this quick tutorial, I will explain how to create a basic IVR that can access a Google Sheet and communicate a 3 digit code via voice.

This tutorial assume that you have a basic knowledge of AWS Console, what is AWS Lambda (the demo function is written in Javascript) and how to create, upload and debug a function via the console.

Need: we have this basic “manual” and “human” flow. We have a safe with a 3 digit code. This safe contains the key of a specific room in the office that must be protected but sometimes opened by guests when no staff is in the office, and we want to give them access only after a phone authorization. When someone has access, the code is changed (usually the day after).

So a guest now do this:
– in front of the safe there is a phone number.
– the guest calls the phone number
– me or my colleague answer and give him the code (The code is stored in a Google Sheet to permit us to find and remember it easily after a change)
– the guest opens the safe and take the key of the room
– the day after, the member of the staff who received the call changes the safe code and update the Google Sheet

What we want now, is to change this flow to avoid that someone of the staff answer to the phone in the night only for giving a stupid 3 digit code 🙂

Start with Amazon Connect.

1) Claim a new Phone Number

1 - claim phone number

2) create a contact flow

2 - create contact flow

3 - create contact flow

3) edit the contact flow like this

4 - contact flow details

4) look at the configuration of “Invoke AWS Lambda Function”

Specifically, in the “Invoke AWS Lambda Function”,  you must insert your function ARN.
By now you haven’t created the Lambda function yet, so leave this field empty, but after creating the function you will insert the ARN which is a code like this:


4) change the “Play prompt” configuration

The upper “play prompt” must be configured like in this image

5 - play prompt details


the lower one is simply an audio that plays “There was an error”

That’s all by now, simply save and publish.

100 - publish

If you call the phone number now, you will hear “There was an error”


Now, let’s create a Lambda function. You have to edit it in your local editor, the lambda function must be uploaded via .zip file (or s3) with the whole node_modules directory and the Google credentials.

Disclaimer: This function is not well formatted and organized, I copied and pasted it adding some spaghetti code, so rewrite it as you prefer 🙂 however it works.

var fs = require('fs');
var readline = require('readline');
var google = require('googleapis');
var googleAuth = require('google-auth-library');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/
var SCOPES = [''];
//var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE) + '/.credentials/';
var TOKEN_DIR = './.credentials/';
var final_callback = null;
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
function authorize(credentials, callback) {
    var clientSecret = credentials.installed.client_secret;
var clientId = credentials.installed.client_id;
var redirectUrl = credentials.installed.redirect_uris[0];
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, function(err, token) {
        if (err) {
            getNewToken(oauth2Client, callback);
} else {
            oauth2Client.credentials = JSON.parse(token);

 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 * @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback to call with the authorized
 *     client.
function getNewToken(oauth2Client, callback) {
    var authUrl = oauth2Client.generateAuthUrl({
        access_type: 'offline',
scope: SCOPES
console.log('Authorize this app by visiting this url: ', authUrl);
var rl = readline.createInterface({
        input: process.stdin,
output: process.stdout
rl.question('Enter the code from that page here: ', function(code) {
oauth2Client.getToken(code, function(err, token) {
            if (err) {
                console.log('Error while trying to retrieve access token', err);
            oauth2Client.credentials = token;

 * Store token to disk be used in later program executions.
 * @param {Object} token The token to store to disk.
function storeToken(token) {
    try {
} catch (err) {
        if (err.code != 'EEXIST') {
            throw err;
    fs.writeFile(TOKEN_PATH, JSON.stringify(token));
console.log('Token stored to ' + TOKEN_PATH);

function readCode(auth) {
    var sheets = google.sheets('v4');
        auth: auth,
spreadsheetId: 'XXXXXX', // id of the spreadsheet
range: 'SHEET_NAME!A1:A1', // cell name for the code
}, function(err, response) {
        if (err) {
            console.log('The API returned an error: ' + err);
        var rows = response.values;
if (rows.length == 0) {
            console.log('No data found.');
} else {
            if (final_callback) {
                final_callback(null, {code: rows[0][0]});

exports.handler = (event, context, callback) => {
    // Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
        if (err) {
            console.log('Error loading client secret file: ' + err);
        // Authorize a client with the loaded credentials, then call the
        // Google Sheets API.
authorize(JSON.parse(content), readCode);
final_callback = callback;
exports.handler('1','2', (a, b) => console.log(b.code));

in the readCode function you have these 2 parameters to fill:

spreadsheetId: 'XXXXXX', // id of the spreadsheet
range: 'SHEET_NAME!A1:A1', // cell name for the code

Some things to remember:

– You will need a Google client_secret.json file
– You have to execute this function at least one time from your PC. The function will ask you to visit a Google link to obtain a token and paste it back. The token is then saved in a .credentials folder inside your project directory (you have to create it!!). Then, the credentials file must be uploaded with the function to Lambda.
– You have to include the whole node_modules directory to the uploaded zip file.
– create the Lambda function in the same region of Connect

After doing this, the last things to do are:

– Connect the Amazon Connect “Invoke AWS Lambda Function” node to the right function ARN, you can find it in the AWS Lambda section in the upper right corner.
– Add the correct permissions to Connect for accessing the Lambda function, this must be done via AWS CLI with this command

aws lambda add-permission –function-name function:lambda-function-name –statement-id 1 –principal  –action lambda:InvokeFunction –source-account 123456789012 –source-arn arn:aws:connect:eu-central-1:123456789012:instance/faf03769-52ce-4577-bedf-dd82c9a933c8 –region eu-central-1

Parameters are:

–function-name is always “function:xxxx” where xxx is the lambda function name
–source-account is your Amazon account ID, you find it in the upper-right “My Account” section of AWS Console
–source-arn is the Amazon Connect ARN
–region  is the Connect and Lambda region

That’s all, if you have done all correctly, you will hear a prompt with the code present in your Google Sheet file.

Next step, this code should be improved to add some controls, for example to save the CLI for the caller and to block anonymous calls, so our staff can know when and who called.

If something is not clear feel free to write me an e-mail.


Fabio Lombardo




Swift and pointers, news in Beta 3 and 4

In this post: you have learned how to play with pointers in Swift.
Things have changed in latest betas, and more researches came in a better, shorter and more concise code. In short:

– CMutablePointer has been removed
– Code like this:

// swift side
 var opaque = COpaquePointer.null() // create a new opaque pointer pointing to null
 var string = Unmanaged.fromOpaque(opaque).takeRetainedValue()
 // this prints pippo pluto

has been revealed to be not safe:
There are circumstances in which Swift does not give you the original address of the variable, but instead gives you an address of a temporary variable that will be assigned back to the original once the call is over. That means you can’t count on the address of opaque being valid after the call to TestClass.writeString(&opaque). So, starting at the line ” var string = Unmanaged.fromOpaque(opaque).takeRetainedValue()”, the code can fail

Now, let’s say that we want to create a C/Objc function that takes all kind of objects and values (simply, it can receive a void** pointer), and pass a value back to Swift.
In this example we will pass in an NSString, changing its value in Objc and then reading it back in Swift. There are better methods to do this kind of things with NSString, passing a void** is used mainly to manage buffers, but in the example we’ll use an NSString for leaving things simple.

The Objc method is this

// with this objc function I completely replace the pointer
 + (void)writeString:(void **)var
     NSString *oldString = CFBridgingRelease(*var); // since we are transferring opaque pointers, ARC can't help us. So, we have to release the old string before replacing it, otherwise it will leak 
     NSString *aString = [[NSString alloc] initWithFormat:@"pippo %@", @"pluto"];
     *var = (void *)CFBridgingRetain(aString); // Since aString will be released by ARC when the method ends, we need to send an additional retain. This retain is balanced by ARC on the Swift side

Now, on the Swift part, the code is more simple than the previous version:

var aString : NSString = NSString(string: "test") // create the string
withUnsafePointer(&aString) { (arg: UnsafePointer) -> () in
     var aPtr = reinterpretCast(arg) as UnsafePointer<UnsafePointer<()>>
println(aString) // this will print "pippo pluto"

Some things to know

1) withUnsafePointer is a function that takes: an inout parameter (&parameterName) and a closure, where an arg (of type UnsafePointer) is passed in.
It can be written even in this way

withUnsafePointer(&aString, { … closure ….})

However, Swift give you a convenient way to put the closure after the parentheses. For this, look at the “Trailing Closures” chapter in the Swift Programming Language Book

2) reinterpretCast() permits to easily change the type of a pointer to another. Since Swift types are all reference types, and we want to obtain the void** pointer:
– when we pass in &aString we obtain a pointer to a Swift Reference type to an NSString, so a pointer to a pointer, and so a void**. We need only to make it “more generic”, and we to this casting to UnsafePointer<UnsafePointer<()>>
() is a TypeAlias to Void, so aPtr will be a pointer to a void pointer

Swift and mach_override, an (unsafe) alternative to objc method swizzling

Objective-c method dispatching is dynamic. This means that, when you call for example an instance method, the objc runtime “searches” the address of the underlying function (*) in a dynamical way. It uses objc_msgSend() for the message dispatching.
I don’t want to go into details here, there is a lot of documentation on the web about it.

(*) every objective c method is a plain c function that takes a _cmd (selector) as the first parameter, and self as the second parameters, then a variable list of parameters.

One advantage of the dynamic dispatching is that you can add classes, variables and methods at runtime.

This is not possible with Swift, since it is based on a vtable approach (*)
(*) This is true for plain swift classes, since classes the inherith from objective-c uses, for compatibility reasons, the dynamic dispatching and the runtime of objective c. In some cases, even the vtable is not used: the function calls are inlined

This means that there is no dynamic search of the functions/methods at runtime, their addresses are statically written at compile time inside the vtable, and it’s not possible to change them at runtime.

If you try to look at the symbols of a Swift compiled app, you will see something like this (OverrideTest is a binary name that I’m analyzing):

LombaXAir:MacOS Lombardo$ nm OverrideTest
 00000001000071e0 t _Mx_mem_size
 00000001000071c0 t _Mx_reg_size
 U _NSApplicationMain
 0000000100010f90 S _OBJC_CLASS_$__TtC12OverrideTest11AppDelegate
 0000000100011070 D _OBJC_METACLASS_$__TtC12OverrideTest11AppDelegate
 0000000100011010 s _OBJC_METACLASS_$___ARCLite__
 U __Block_copy
 0000000100004480 t __OSSwapInt32
 0000000100004490 t __OSSwapInt64
 0000000100001700 T __TF12OverrideTest16doSomethingSwiftFT_T_
 0000000100001aa0 T __TF12OverrideTest26doSomethingSwiftOverriddenFT_T_
 0000000100001820 T __TFC12OverrideTest11AppDelegate13aTestFunctionfS0_FT_T_
 00000001000018b0 T __TFC12OverrideTest11AppDelegate18anOverrideFunctionfS0_FT_T_
 00000001000017a0 T __TFC12OverrideTest11AppDelegate24applicationWillTerminatefS0_FGSqCSo14NSNotification_T_
 0000000100001690 T __TFC12OverrideTest11AppDelegate29applicationDidFinishLaunchingfS0_FGSqCSo14NSNotification_T_
 0000000100001a40 T __TFC12OverrideTest11AppDelegateCfMS0_FT_S0_
 0000000100001940 T __TFC12OverrideTest11AppDelegateD
 00000001000019b0 T __TFC12OverrideTest11AppDelegatecfMS0_FT_S0_
 0000000100001590 T __TFC12OverrideTest11AppDelegateg6windowXwGSQCSo8NSWindow_
 0000000100001640 T __TFC12OverrideTest11AppDelegates6windowXwGSQCSo8NSWindow_
 U __TFSS37_convertFromBuiltinUTF16StringLiteralfMSSFTBp17numberOfCodeUnitsBw_SS
... continue

Symbols like


are plain function/method names, mangled ( see Name Mangling ), that can be called by a C/ObjectiveC function without problems.
You can call them with the static address, or searching by name through dlsym (see this post: Swift Performselector alternative )

So, returning to the original topic, how to do something like method swizzling in Swift?

There is an alternative called mach_override. This is not safe and I discourage you to include it in a shipping application, however it’s possible.

mach_override “simply” add a jmp inside the assembly of the original function, making it jump to another custom function, and then jump back to the original one, if you want.

More info about mach_override Here (Github) and Here an high level explanation on how it works

After including mach_override in your project, you can override a method implementation with a c function like this:

void override()
    void (*landing)(void * par);
    void (*originalFunctionAddress)(void * par);
    const void (*overrideFunctionAddress)(void * par);
   *(void **) (&originalFunctionAddress) = dlsym(RTLD_DEFAULT, "_TF15OverrideTestIOS16doSomethingSwiftFT_T_");
   *(void **) (&overrideFunctionAddress) = dlsym(RTLD_DEFAULT, "_TF15OverrideTestIOS26doSomethingSwiftOverriddenFT_T_");
   mach_override_ptr(originalFunctionAddress, overrideFunctionAddress, (void**)&landing);

Method names are taken with “nm” from command line, but you can try to mangle it at runtime since the mangling syntax has been reverse engineered (an example by Evan Swick Here )

the “par” parameter is because every swift instance method underlying function, takes “self” as the last parameter.

To see this code in action, download a working example (for mac) from my GitHub account

How do I specify that a non-generic Swift type should comply to a protocol?

From this Stackoverflow Question

Given this example method in Objective C:

- (void)addFilter:(GPUImageOutput <GPUImageInput>*)newFilter;

How to rewrite it in Swift, saying that the input parameter is of Class GPUImageOutput (or subclass), and, at the same time, conforms to the protocol GPUImageInput ?

In Swift, the solution comes from Generics:

Given these example declarations of protocol, main class and subclass:

protocol ExampleProtocol {
    func printTest() // classes that implements this protocol must have this method
// an empty test class
class ATestClass
// a child class that implements the protocol
 class ATestClassChild : ATestClass, ExampleProtocol
     func printTest()

Now, you want to define a method that takes an input parameters of type ATestClass (or a child) that conforms to the protocol ExampleProtocol. Write the method declaration like this:

func addFilter<T where T: ATestClass, T: ExampleProtocol>(newFilter: T)

The original method, redefined in Swift, should be

func addFilter<T where T:GPUImageOutput, T:GPUImageInput>(newFilter:T!)
    // ...

A quick tour into Swift Pointers

From: Stackoverflow Question

Swift “hides” pointers, but they still exists under the hood. (because the runtime needs it, and for compatibility reasons with Objc and C)

There are few things to know however, but first how to print the memory address of a Swift String?

var aString : String = "THIS IS A STRING"
 NSLog("%p", aString.core._baseAddress) // _baseAddress is a COpaquePointer
 // example printed address 0x100006db0

This prints the memory address of the string, if you open XCode -> Debug Workflow -> View Memory and go to the printed address, you will see the raw data of the string. Since this is a string literal, this is a memory address inside the storage of the binary (not stack or heap).

However, if you do

var aString : String = "THIS IS A STRING" + "This is another String"
 NSLog("%p", aString.core._baseAddress)
// example printed address 0x103f30020

This will be on the stack, because the string is created at runtime

NOTE: .core._baseAddress is not documented, I found it looking in the variable inspector, and it may be hidden in the future

_baseAddress is not available on all types, here another example with a CInt

var testNumber : CInt = 289

Where takesInt is a C helper function like this

void takesInt(int *intptr)
    printf("%p", intptr);

On the Swift side, this function is takesInt(intptr: CMutablePointer), so it takes a CMutablePointer to a CInt, and you can obtain it with &varname

The function prints 0x7fff5fbfed98, an at this memory address you will find 289 (in hexadecimal notation). You can change its content with *intptr = 123456

Now, some other things to know.

String, in swift, is a primitive type, not an object.
CInt is a Swift type mapped to the C int Type.
If you want the memory address of an object, you have to do something different.
Swift has some Pointer Types that can be used when interacting with C, and you can read about them here: Swift Pointer Types
Moreover, you can understand more about them exploring their declaration (cmd+click on the type), to understand how to convert a type of pointer into another

var aString : NSString = "This is a string" // create an NSString
 var anUnmanaged = Unmanaged.passUnretained(aString) // take an unmanaged pointer
 var opaque : COpaquePointer = anUnmanaged.toOpaque() // convert it to a COpaquePointer
 var mut : CMutablePointer = &opaque // this is a CMutablePointer
printptr(mut) // pass the pointer to an helper function written in C

printptr is a C helper function I created, with this implementation

void printptr(void ** ptr)
    printf("%p", *ptr);

Again, an example of the address printed: 0x6000000530b0 , and if you go through memory inspector you will find your NSString

One thing you can do with pointers in Swift (this can even be done with inout parameters)

func playWithPointer (stringa :AutoreleasingUnsafePointer)
    stringa.memory = "String Updated";
var testString : NSString = "test string"

Or, interacting with Objc / c

// objc side
 + (void)writeString:(void **)var
    NSMutableString *aString = [[NSMutableString alloc] initWithFormat:@"pippo %@", @"pluto"];
    *var = (void *)CFBridgingRetain(aString); // Retain!
// swift side
 var opaque = COpaquePointer.null() // create a new opaque pointer pointing to null
 var string = Unmanaged.fromOpaque(opaque).takeRetainedValue()
 // this prints pippo pluto

Subclass UIApplication in Swift

From Stackoverflow

In Objective C it was simple: it was sufficient to update the main.m file and change the UIApplicationMain() parameters

return UIApplicationMain(argc, argv, NSStringFromClass([CustomUIApplication class]), NSStringFromClass([AppDelegate class]));

But in swift there is no main.m file, since the guide says

“Code written at global scope is used as the entry point for the program, so you don’t need a main function.”

So, how to subclass UIApplication in swift?? Any suggestion?


Ok, I’ve found the solution First, I’ve noticed that, at the top of the AppDelegate.swift file, there is this line


Since this line is outside any scope (it’s at file level), it’s executed immediately, and I assume that the compiler translate it in a standard main function.

So, I did this, starting from a new Swift-Only application:

– commented out @UIApplicationMain
– added a main.swift file like this (FLApplication is my subclass).

IMPORTANT the file MUST BE NAMED main.swift, since top level statements are not supported on other files! You can’t add the UIApplicationMain() call inside any other file, otherwise you’ll receive this error:
“Expressions are not allowed at the top level”

This is the main.swift file .

import Foundation
import UIKit

UIApplicationMain(C_ARGC, C_ARGV, NSStringFromClass(FLApplication), NSStringFromClass(AppDelegate))

create a swift file for the UIApplication subclass, FLApplication.swift, with this code:

import UIKit
import Foundation

class FLApplication: UIApplication
    override func sendEvent(event: UIEvent!)
        println("send event") // this is an example
        // ... dispatch the message...

now, UIApplication is correctly subclassed and you’ll see the “send event” messages in the log

Q&A – Call a method from a String in Swift (performSelector alternative)

From Stackoverflow


Calling a method from its name (in a String format) can be sometimes useful.
In Swift it is recomended to change behavior and to use closures to do something “dynamically”, so for example you can have a dictionary of functions, with the name as the key, and the implementation as the value.
However, sometimes you want to simply know “how to do it”, and this is the reason of this question.
So, how to call dynamically a Swift method starting from it’s name as string?

In Objective C it was simple:

[self performSelector:NSSelectorFromString(@”aSelector”)];

But performSelector is banned in Swift
Is there any alternative?


In Swift, you should use closures and change your approach. However, if you want to use performSelector to dynamically call a method given only it’s String signature, altough it’s not supported natively, I’ve found how to do it.

It is possible to create a C alternative to performSelector that:

works even on native swift classes (non objective-c)
takes a selector from string
However it’s not so straightforward to implement a complete version of it, and it’s necessary to create the method in C.

in C we have dlsym(), a function that returns a pointer to a function given the char symbol. Well, reading this interesting post: I’ve learned a lot of interesting things about swift.

Swift instance methods are plain functions with a specific signature, like this


where the “self” value is passed as the last parameter

in short you can call it directly from the c side without any kind of bridging, it is sufficient to rebuild the correct function signature. In the signature above, there is the name of the project (FirstSwiftTest) and the lenght (14), the name of the class (ASampleClass) and the lenght (12), the name of the function (aTestFunction) and the lenght (13), then other values as the return type ecc ecc. For other details look at the previous link

The function above, is the representation of this:

class ASampleClass
    func aTestFunction() -> NSString
        println("called correctly")
        return NSString(string: "test")

Well, on the c side, I was able to create this function

#include <stdio.h>
#include <dlfcn.h>

typedef struct objc_object *id;

id _performMethod(id stringMethod, id onObject)
    // ...
    // here the code (to be created) to translate stringMethod in _TFC14FirstSwiftTest12ASampleClass13aTestFunctionfS0_FT_CSo8NSString
    // ...

    id (*functionImplementation)(id);
    *(void **) (&functionImplementation) = dlsym(RTLD_DEFAULT, "_TFC14FirstSwiftTest12ASampleClass13aTestFunctionfS0_FT_CSo8NSString");

    char *error;

    if ((error = dlerror()) != NULL)  {
        printf("Method not found \n");
    } else {
        return functionImplementation(onObject); // <--- call the function
    return NULL

And then called it on the swift side

let sampleClassInstance = ASampleClass()
println(_performMethod("aTestFunction", sampleClassInstance))

The function resulted in these statement printed on the log:

called correctly

So it should be not so difficult to create a _performMethod() alternative in C that:

– creates automatically the function signature (since it seems to have a logic 🙂
– manages different return value types and parameters