Showing posts with label network. Show all posts
Showing posts with label network. Show all posts

Thursday, April 28, 2016

Facebook SDK and Swift - Create a custom login button programmatically

The FBSDKLoginButton style is like this:


To create a custom Facebook login button, follow these two tutorials first:

Facebook SDK and Swift - Create a Facebook Login Button
Facebook SDK and Swift - Display User Name and Profile Picture

Then remove the FBSDKLoginButton and create a UIButton instead. Add this to viewDidLoad()with Xcode 7.3 (Swift 2.2):


let btnSize : CGFloat = 100
let btnLogin = UIButton(frame: CGRectMake(0,0,btnSize,btnSize))
btnLogin.center = CGPoint(x: view.center.x, y: 400)
btnLogin.setImage(UIImage(named: "facebook_logo.png"), forState: UIControlState.Normal)
btnLogin.addTarget(self, action: #selector(btnLoginPressed), forControlEvents: UIControlEvents.TouchUpInside)
        
//Circular button
btnLogin.layer.cornerRadius = btnSize/2
btnLogin.layer.masksToBounds = true
btnLogin.layer.borderColor = UIColor.blackColor().CGColor
btnLogin.layer.borderWidth = 2

view.addSubview(btnLogin)

and then add this:

func btnLoginPressed() {

let loginManager = FBSDKLoginManager()
loginManager.logInWithReadPermissions(["public_profile"], fromViewController: self, handler: { (response:FBSDKLoginManagerLoginResult!, error: NSError!) in
    if(error == nil){
        print("No Error")
        self.getFacebookUserInfo()
        }
    })
}

Result:


Related Information:

Google Sign-In for iOS - Create a custom sign-in button programmatically

Google Sign-In for iOS - Create a custom sign-in button programmatically

The GIDSignInButton can be assigned as one of the following styles (See GIDSignInButton Class):

GIDSignInButtonStyle.Standard => 230x48


GIDSignInButtonStyle.Wide     => 312x48


GIDSignInButtonStyle.IconOnly =>  48x48

However, we may need custom styles other than the above sign-in buttons. For example the 48x48 IconOnly style is a bit small on the screen and hence we want to enlarge it. So the code below shows how to implement a custom Google sign-in button with these properties:


  • Custom image
  • Custom button size
  • Circular shape

To get started, implement a standard Google Sign-In button with instructions in this tutorial:

Google Sign-In for iOS - Create a GIDSignInButton programmatically in Swift

Then remove the GIDSignInButton and add a UIButton instead:


    var btnSignIn : UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        ...
        
        let btnSize : CGFloat = 100
        btnSignIn = UIButton(frame: CGRectMake(0,0,btnSize,btnSize))
        btnSignIn.center = view.center
        btnSignIn.setImage(UIImage(named: "google_logo.png"), forState: UIControlState.Normal)
        btnSignIn.addTarget(self, action: #selector(btnSignInPressed), forControlEvents: UIControlEvents.TouchUpInside)

        //Circular button
        btnSignIn.layer.cornerRadius = btnSize/2
        btnSignIn.layer.masksToBounds = true
        btnSignIn.layer.borderColor = UIColor.blackColor().CGColor
        btnSignIn.layer.borderWidth = 2
        view.addSubview(btnSignIn)

        ...
    }
    
    func btnSignInPressed() {
        GIDSignIn.sharedInstance().signIn()
    }

Result:


Related Information:

Facebook SDK and Swift - Create a custom login button programmatically

Wednesday, April 27, 2016

Asynchronously Display an Web Image with NSURLSession.sharedSession().dataTaskWithURL

To display an image on the Internet in Swift 2.2 with Xcode 7.3 using asynchronous download method, modify ViewController.swift as:

import UIKit

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let url = NSURL(string: "https://....JPG")!
        
        let imageSize : CGFloat = 200
        let imageView = UIImageView(frame: CGRectMake(0, 0, imageSize, imageSize))
        imageView.center = view.center
        
        NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, response, error) in
            
            if let error = error {
                print("Image read error \(error)")
                return
            }
            
            imageView.image = UIImage(data: data!)
        }).resume()
        
        //Synchronous Method without using NSURLSession
        //imageView.image = UIImage(data: NSData(contentsOfURL: url!)!)
        
        //Scale the image with the original aspect ratio
        imageView.contentMode = UIViewContentMode.ScaleAspectFit
        
        view.addSubview(imageView)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

Monday, April 18, 2016

Carthage Tutorial - Reachability.swift

Carthage is an alternative dependency manager to CocoaPods. Unlike the Objective-C based CocoaPods, Carthage is developed in Swift. The tutorial below shows how to use Carthage to install reachability.swift and receive network reachability notifications.

1. Install Homebrew with this command:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

If Homebrew has already been installed, you'll see this:




2. Type this command in the terminal:

brew update

===== If you have no error, go to step 3. =====

You might see error like this:


warning: unable to unlink CONTRIBUTING.md: Permission denied
warning: unable to unlink SUPPORTERS.md: Permission denied
fatal: cannot create directory at '.github': Permission denied

Error: Failure while executing: git pull --ff --no-rebase --quiet origin refs/heads/master:refs/remotes/origin/master

If you see the above message, type this command:


sudo chown -R username:admin $(brew --prefix)



Then type:

git fetch --all

If this error happens:


fatal: Not a git repository (or any of the parent directories): .git

Type this:

git init

Then try git fetch --all again and type this:

git reset --hard && git clean -df

Then enter these commands:

brew doctor
brew update

Reference: homebrew not working on OSX

===== End of Step 2 Error Section =====

3. Type this command in the terminal:


brew install carthage

4. Check the version of Carthage with:

carthage version

Note: To update the carthage version, use this command:

brew upgrade carthage

5. Create a new Xcode project.

6. Go to the Xcode directory in the terminal and create an empty Cartfile with this command:

touch Cartfile


7. Open the Cartfile with Xcode using this command:


open Cartfile -a Xcode

8. Add this line to the Cartfile:

github "ashleymills/Reachability.swift"

Press [command] + [S] keys to save the Cartfile.

9. Go back to the terminal. Type:

carthage update

You should see message like this:


10. Open the Carthage folder in Finder with this terminal command:

open Carthage

Move to Carthage/Build/iOS/ in Finder.

11.  Select ProjectName -> Targets -> General -> Linked Frameworks and Libraries in Xcode. 




12. Drag Reachability.framework from Finder to Xcode.



13. Select ProjectName -> Targets -> Build Phases -> + sign -> New Run Script Phase.




14. Select Run Script. Add this command:


/usr/local/bin/carthage copy-frameworks

Select Input Files and add this line:

$(SRCROOT)/Carthage/Build/iOS/Reachability.framework


Build the code now and it should work.

15. Modify ViewController.swift in Swift 2.2 with Xcode 7.3 as below:


import UIKit
import Reachability

class ViewController: UIViewController {
    
    var reachability: Reachability?
    
    override func viewWillAppear(animated: Bool) {
        do {
            reachability = try Reachability.reachabilityForInternetConnection()
        } catch {
            print("Unable to create Reachability")
            return
        }
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(reachabilityChanged(_:)), name: ReachabilityChangedNotification, object: reachability)
        
        do {
            try reachability?.startNotifier()
        } catch {
            print("could not start reachability notifier")
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    func reachabilityChanged(notification: NSNotification) {
        
        let reachable = notification.object as! Reachability
        
        if reachable.isReachable() {
            if reachable.isReachableViaWiFi() {
                print("WiFi")
            } else {
                print("Cellular")
            }
        } else {
            print("No Network")
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

Result:

WiFi
Cellular
No Network
Cellular
WiFi

Related Information:

Friday, March 4, 2016

Communication between iOS device (Client) and Raspberry Pi (Server)

To learn the client-server communication, a practical approach is to setup the connection between an iOS device (Client) and a Raspberry Pi (Server):

Client: iOS device with app developed in Swift
Server: Raspberry Pi with socket server programmed in Python

Requirements

1. Setup a Raspberry Pi

2. Mac + Xcode + iPhone/iPad

===============

The three sections below will explain how to:
1. Setup the basic client-server socket communication architecture.
2. Encrypt/decrypt a message with RSA public/private keys.
3. Combine sections 1 and 2 to setup the secure socket communication.

1. Basic Socket Communication

The basic form of client-server communication between an iPhone/iPad and a Python socket server built on a Raspberry Pi is shown in this tutorial:

Connect an iPhone to a Simple Python Socket Server (Raspberry Pi Part) (iOS Part)

The above tutorial must be fully understood, because it is the basis for the tutorials in the 3. Secure Socket Communication section.

2. RSA

The data transmitted between the client and the server in the above example are not encrypted and hence are insecure. Therefore, using RSA (Rivest-Shamir-Adleman) cryptosystem for secure communications is a good topic to be studied for understanding asymmetric public-private key cryptosystem.

All examples below follow this procedure:

1. Generate or obtain an RSA private and public key pair.
2. Encrypt a message with the public key.
3. Decrypt the encrypted message with the private key.

2.1 Basic OpenSSL commands

In order to understand how to use RSA keys for encryption/decryption, try the basic OpenSSL RSA commands: 

OpenSSL RSA commands to encrypt/decrypt a message in terminal (Raspberry Pi and Mac)

You should notice that RSA uses different keys of the same key pair for encrypting and decrypting a message. This is known as asymmetric since different keys are used.

Now let's start programming with RSA keys!!

2.2 Importing External RSA keys

Here are Python (Raspberry Pi) and Swift (iOS) examples showing how to import external OpenSSL-generated RSA keys in PEM file format:

Encrypt/decrypt a string with external public/private keys (Raspberry Pi Part) (iOS Part)

2.3 Using Code-generatd RSA keys

External RSA key files are fixed. If different key pairs are required while the program is running, try to generate keys in Python/Swift code:

Encrypt/decrypt a string with code-generated public/private keys (Raspberry Pi Part) (iOS Part)

Now let's move on to implement code-generated RSA keys in the client-server architecture.

3. Secure Socket Communication

Remember that:

Client: iOS device with app developed in Swift
Server: Raspberry Pi with socket server programmed in Python

There are two tutorials in this section. Both of them will explain how to transmit an encrypted message between a client and a server. The difference between the two tutorials is the opposite direction of data transmission. The principle of sending encrypted message is as below:

1. The receiving device generates an RSA private-public key pair and sends the public key to the transmitting device.
2. The transmitting device encrypts a message using the public key provided by the receiving device and sends the encrypted message to the receiving device.
3. The receiving device decrypts the encrypted message from the transmitting device using the private key.

The two tutorials with different directions of transmitting encrypted data are as below:

1. From iOS device to Python socket server (Raspberry Pi Part) (iOS Part)
2. From Python socket server to iOS device (Raspberry Pi Part) (iOS Part)

Or in terms of encrypt/decrypt in Python/Swift programming languages:

1. Encrypt in Swift and decrypt in Python (Raspberry Pi Part) (iOS Part)
2. Encrypt in Python and decrypt in Swift (Raspberry Pi Part) (iOS Part)

Note:

For Tutorial 2. Encrypt in Python and decrypt in Swift (iOS Part), you need to understand how to manage the iOS keychain in this tutorial:

Store/Retrieve/Delete RSA public/private keys with keychain (iOS Swift)

More Information:

Crypto 101 ebook (pdf)

Sending RSA encrypted message - From Python socket server to iOS device (iOS Part)

Secure Data Transmission: Raspberry Pi -> iOS device

Secure communication between a mobile device client and a server is important. This tutorial selects an iPhone as the server and uses a Raspberry Pi as the client. The communication procedure is as below:

1. iPhone generates an RSA private / public key pair and sends the public key to server.
2. Server encrypts a message using the public key provided by iPhone and sends the encrypted message to iPhone
3. iPhone decrypts the encrypted message from server using the private key

This tutorial is derived from the basic communication between an iPhone and a Python socket server built on a Raspberry Pi without encryption:

Connect an iPhone to a Simple Python Socket Server (Raspberry Pi Part) (iOS Part)

For an overview on client-server communications, see this:

Communication between iOS device (Client) and Raspberry Pi (Server)

Raspberry Pi Part

Setup a socket server in Python:

Sending RSA encrypted message - From Python socket server to iOS device (Raspberry Pi Part)

iOS Part

The Xcode version used is 7.2.1 (Swift 2.1.1).

1. Download CryptoExportImportManager. Find out the CryptoExportImportManager.swift file in the downloaded folder.

2. Create a new Single View Application project in Xcode.

3. Add CryptoExportImportManager.swift to the project just created.

4. Modify ViewController.swift as below:

import UIKit

class ViewController: UIViewController, NSStreamDelegate {
    
    //Button
    var buttonConnect    : UIButton!
    var buttonSendKey     : UIButton!
    var buttonDecryptMsg : UIButton!
    var buttonQuit       : UIButton!
    
    //Label
    var label : UILabel!
    var labelConnection : UILabel!
    
    //Socket server
    let addr = "192.168.xx.xx"
    let port = xxxx
    
    //Network variables
    var inStream : NSInputStream?
    var outStream: NSOutputStream?
    
    //Data received
    var buffer = [UInt8](count: 200, repeatedValue: 0)
    
    var inStreamLength : Int!
    
    //Key variables and constants
    var publicKey, privateKey: SecKey?
    var publicKeyString = ""
    let keySize = 1024
    let tagPrivate = "com.mycompany.tagPrivate"
    let tagPublic  = "com.mycompany.tagPublic"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        ButtonSetup()
        
        LabelSetup()
        
        KeySetup()
    }
    
    //Button Functions
    func ButtonSetup() {
        buttonConnect = UIButton(frame: CGRectMake(20, 50, 300, 30))
        buttonConnect.setTitle("Connect to server", forState: UIControlState.Normal)
        buttonConnect.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
        buttonConnect.setTitleColor(UIColor.cyanColor(), forState: UIControlState.Highlighted)
        buttonConnect.addTarget(self, action: "btnConnectPressed:", forControlEvents: UIControlEvents.TouchUpInside)
        view.addSubview(buttonConnect)
        
        buttonSendKey = UIButton(frame: CGRectMake(20, 100, 300, 30))
        buttonSendKey.setTitle("Send public key to server", forState: UIControlState.Normal)
        buttonSendKey.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
        buttonSendKey.setTitleColor(UIColor.cyanColor(), forState: UIControlState.Highlighted)
        buttonSendKey.addTarget(self, action: "btnSendKey:", forControlEvents: UIControlEvents.TouchUpInside)
        buttonSendKey.alpha = 0.3
        buttonSendKey.enabled = false
        view.addSubview(buttonSendKey)
        
        buttonDecryptMsg = UIButton(frame: CGRectMake(20, 150, 300, 30))
        buttonDecryptMsg.setTitle("Decrypt message", forState: UIControlState.Normal)
        buttonDecryptMsg.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
        buttonDecryptMsg.setTitleColor(UIColor.cyanColor(), forState: UIControlState.Highlighted)
        buttonDecryptMsg.addTarget(self, action: "btnDecryptMsg:", forControlEvents: UIControlEvents.TouchUpInside)
        buttonDecryptMsg.alpha = 0.3
        buttonDecryptMsg.enabled = false
        view.addSubview(buttonDecryptMsg)
        
        buttonQuit = UIButton(frame: CGRectMake(20, 200, 300, 30))
        buttonQuit.setTitle("Send \"Quit\"", forState: UIControlState.Normal)
        buttonQuit.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
        buttonQuit.setTitleColor(UIColor.cyanColor(), forState: UIControlState.Highlighted)
        buttonQuit.addTarget(self, action: "btnQuitPressed:", forControlEvents: UIControlEvents.TouchUpInside)
        buttonQuit.alpha = 0.3
        buttonQuit.enabled = false
        view.addSubview(buttonQuit)
    }
    
    func btnConnectPressed(sender: UIButton) {
        NetworkEnable()
        
        buttonConnect.alpha = 0.3
        buttonConnect.enabled = false
    }
    func btnSendKey(sender: UIButton) {
        let publicKeyTypeStr = "public_key=\(publicKeyString)"
        let data : NSData = publicKeyTypeStr.dataUsingEncoding(NSUTF8StringEncoding)!
        outStream?.write(UnsafePointer<UInt8>(data.bytes), maxLength: data.length)
    }
    func btnDecryptMsg(sender: UIButton) {

        let dataEncryptedSize : Int = inStreamLength

        var arrayDecrypted = [UInt8](count: dataEncryptedSize, repeatedValue: 0)
        var arrayDecryptedSize = dataEncryptedSize

        let status = SecKeyDecrypt(privateKey!, SecPadding.PKCS1, &buffer, dataEncryptedSize, &arrayDecrypted, &arrayDecryptedSize)

        if status == errSSLCrypto {
            print("errSSLCrypto") //-9809 error
            return
        } else if status != noErr {
            print("Decryption Error! \(status.description)")
            return
        }
        let messageStr = NSString(bytes: &arrayDecrypted, length: arrayDecryptedSize, encoding: NSUTF8StringEncoding)!

        label.text = "Server sent:\n\(messageStr)"
        print("Decrypt successfully:\n\(messageStr)")
        
        buttonDecryptMsg.alpha = 0.3
        buttonDecryptMsg.enabled = false
        buttonQuit.alpha = 1
        buttonQuit.enabled = true
    }
    func btnQuitPressed(sender: UIButton) {
        let data : NSData = "Quit".dataUsingEncoding(NSUTF8StringEncoding)!
        outStream?.write(UnsafePointer<UInt8>(data.bytes), maxLength: data.length)
        
        buttonQuit.alpha = 0.3
        buttonQuit.enabled = false
    }
    
    //Label setup function
    func LabelSetup() {
        label = UILabel(frame: CGRectMake(0,0,300,150))
        label.center = CGPointMake(view.center.x, view.center.y+100)
        label.textAlignment = NSTextAlignment.Center
        label.numberOfLines = 0 //Multi-lines
        label.font = UIFont(name: "Helvetica-Bold", size: 20)
        view.addSubview(label)
        
        labelConnection = UILabel(frame: CGRectMake(0,0,300,30))
        labelConnection.center = view.center
        labelConnection.textAlignment = NSTextAlignment.Center
        labelConnection.text = "Please connect to server"
        view.addSubview(labelConnection)
    }
    
    //Get keys from keychain or generate new keys
    func KeySetup() {
        
        //Reset keychain
        //deleteAllKeysInKeyChain()
        
        if (GetKeysFromKeychain()) {
            print("Key pair retrieved successfully!")
        } else {
            print("No valid key pair")
            deleteAllKeysInKeyChain()
            GenerateKeyPair()
        }
        GetPublicKeyStr()
    }

    //Other key functions - Check Keychain and get keys

    func GetKeysFromKeychain() -> Bool {
        privateKey = GetKeyTypeInKeyChain(tagPrivate)
        publicKey = GetKeyTypeInKeyChain(tagPublic)
        return ((privateKey != nil)&&(publicKey != nil))
    }
    
    func GetKeyTypeInKeyChain(tag : String) -> SecKey? {
        let query: [String: AnyObject] = [
            String(kSecClass)             : kSecClassKey,
            String(kSecAttrKeyType)       : kSecAttrKeyTypeRSA,
            String(kSecAttrApplicationTag): tag,
            String(kSecReturnRef)         : true
        ]
        
        var result : AnyObject?
        
        let status = SecItemCopyMatching(query, &result)
        
        if status == errSecSuccess {
            print("\(keyTypeStr(tag)) Key existed!")
            return result as! SecKey?
        }
        print("no \(keyTypeStr(tag)) key")
        
        return nil
    }
    
    //Get public key string from keychain
    func GetPublicKeyStr() {
        
        var unsafeData : AnyObject?
        
        let parameters = [
            kSecClass as String: kSecClassKey,
            kSecAttrKeyType as String: kSecAttrKeyTypeRSA,
            kSecAttrKeyClass as String: kSecAttrKeyClassPublic,
            kSecReturnData as String: true
        ]
        
        //Get public key string
        let status = SecItemCopyMatching(parameters, &unsafeData)
        
        if status != noErr {
            print("Get Key Error!")
            return
        }
        
        //Need CryptoExportImportManager.swift from GitHub.
        let manager = CryptoExportImportManager()
        publicKeyString = manager.exportRSAPublicKeyToPEM(unsafeData as! NSData, keyType: kSecAttrKeyTypeRSA as String, keySize: keySize)
        //print(publicKeyString) //Check this with server
    }
    
    //Generate private and public keys
    func GenerateKeyPair() {
        let privateKeyAttr: [NSString: AnyObject] = [
            kSecAttrIsPermanent: true,
            kSecAttrApplicationTag: tagPrivate
        ]
        let publicKeyAttr: [NSString: AnyObject] = [
            kSecAttrIsPermanent: true,
            kSecAttrApplicationTag: tagPublic
        ]
        
        let parameters: [String: AnyObject] = [
            kSecAttrKeyType as String: kSecAttrKeyTypeRSA,
            kSecAttrKeySizeInBits as String: keySize,
            kSecPrivateKeyAttrs as String: privateKeyAttr,
            kSecPublicKeyAttrs as String: publicKeyAttr
        ]
        
        //Generate new keys and store them in keychain
        let status = SecKeyGeneratePair(parameters, &publicKey, &privateKey)
        
        if status != noErr {
            print("SecKeyGeneratePair Error! \(status.description)")
            return
        }
        
        print("Key pair generated successfully")
    }
    
    //key type string
    func keyTypeStr(tag: String) -> String {
        return tag.stringByReplacingOccurrencesOfString("com.mycompany.tag", withString: "")
    }
    
    //Delete keys when required.
    func deleteAllKeysInKeyChain() {
        
        let query : [String: AnyObject] = [
            String(kSecClass)             : kSecClassKey
        ]
        let status = SecItemDelete(query)
        
        switch status {
        case errSecItemNotFound:
            print("No key in keychain")
        case noErr:
            print("All Keys Deleted!")
        default:
            print("SecItemDelete error! \(status.description)")
        }
    }
    
    //Network functions
    func NetworkEnable() {
        
        print("NetworkEnable")
        NSStream.getStreamsToHostWithName(addr, port: port, inputStream: &inStream, outputStream: &outStream)
        
        inStream?.delegate = self
        outStream?.delegate = self
        
        inStream?.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
        outStream?.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
        
        inStream?.open()
        outStream?.open()
        
        buffer = [UInt8](count: 200, repeatedValue: 0)
    }
    
    func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent) {
        
        switch eventCode {
        case NSStreamEvent.EndEncountered:
            print("EndEncountered")
            labelConnection.text = "Connection stopped by server"
            label.text = ""
            
            inStream?.close()
            inStream?.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
            outStream?.close()
            print("Stop outStream currentRunLoop")
            outStream?.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
            buttonConnect.alpha = 1
            buttonConnect.enabled = true
            buffer.removeAll(keepCapacity: true)

        case NSStreamEvent.ErrorOccurred:
            print("ErrorOccurred")
            
            inStream?.close()
            inStream?.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
            outStream?.close()
            outStream?.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
            labelConnection.text = "Failed to connect to server"
            buttonConnect.alpha = 1
            buttonConnect.enabled = true
            label.text = ""
        case NSStreamEvent.HasBytesAvailable:
            print("HasBytesAvailable")
            
            if aStream == inStream {
                
                inStreamLength = inStream!.read(&buffer, maxLength: buffer.count)
                
                //If data received
                if inStreamLength > 0 {
                    label.text = "Encrypted message received!"
                
                    buttonSendKey.alpha = 0.3
                    buttonSendKey.enabled = false
                    buttonDecryptMsg.alpha = 1.0
                    buttonDecryptMsg.enabled = true
                }
            }
            
        case NSStreamEvent.HasSpaceAvailable:
            print("HasSpaceAvailable")
        case NSStreamEvent.None:
            print("None")
        case NSStreamEvent.OpenCompleted:
            print("OpenCompleted")
            labelConnection.text = "Connected to server"
            buttonSendKey.alpha = 1.0
            buttonSendKey.enabled = true
        default:
            print("Unknown")
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

Result

Run both the socket server on Raspberry Pi and iOS simulator on Mac. Press the four app buttons from top to bottom. The message "Secret message from RPi server" sent by Raspberry Pi should be displayed on the iOS app and Xcode debug console:


Reference:

CryptoExportImportManager on GitHub.

Go back to Communication between iOS device (Client) and Raspberry Pi (Server)