Tuesday, December 29, 2015

Connect iOS device to MySQL database on a server (iOS Part)

This post shows how to create a PHP+MySQL service on Raspberry Pi for iPhone / iPad to access using the HTTP POST method.

Raspberry Pi Part


The server service is created on a Raspberry Pi. See this:

iOS Part

1. Create a project with Xcode. Edit ViewController.swift as:

import UIKit

class ViewController: UIViewController {
    
    let urlString = "http://192.168.xx.xx/iosmysql.php"
    
    var labelRead : UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let button = UIButton(frame: CGRectMake(70, 100, 200, 20))
        button.setTitle("Read Database", forState: UIControlState.Normal)
        button.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
        button.setTitleColor(UIColor.cyanColor(), forState: UIControlState.Highlighted)
        button.addTarget(self, action: "btnPressed:", forControlEvents: UIControlEvents.TouchUpInside)
        view.addSubview(button)
        
        let label = UILabel(frame: CGRectMake(50,200,250,30))
        label.text = "Data from Server:"
        label.textAlignment = NSTextAlignment.Center //Align to center
        view.addSubview(label)
        
        labelRead = UILabel(frame: CGRectMake(50,250,300,300))
        labelRead.numberOfLines = 0 //Multi-lines
        
        //Use a font with fixed width for layout.
        labelRead.font = UIFont(name: "Courier", size: labelRead.font.pointSize-2)
        view.addSubview(labelRead)
    }
    
    func btnPressed(sender: UIButton) {
        
        let request = NSMutableURLRequest(URL: NSURL(string: urlString)!)
        request.HTTPMethod = "POST"
        
        let postString = "username=myusername&password=mypassword&tablename=fruit"
        request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
        
        let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: {data, response, error in
            if (error == nil) {
                
                let result = NSString(data: data!, encoding: NSUTF8StringEncoding)!
                
                //Execute UI code immediately
                dispatch_async(dispatch_get_main_queue(), {
                    self.labelRead.text = result as String
                })
            } else {
                print(error)
            }
        })
        task.resume()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

In this example, parameters sent to PHP using the HTTP POST method are username, password, and tablename of the MySQL database on Raspberry Pi.

2. Build the code. This error happens:


App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.

This is because Apple has introduced App Transport Security (ATS) in iOS9, but the URL used here is an insecure HTTP URL instead of a secure HTTPS URL. To allow HTTP connections, modify Info.plist by adding:




3. Build and Run the code again after modifying Info.plist. Pressing the "Read Database" button gives the result:


This result is the same as the result obtained using MySQL monitor commands on Raspberry Pi:


References:
Connect iOS device to HTTP GET/POST PHP service (Raspberry Pi Part) (iOS Part)
Access and show content of a database in MySQL with PHP

2 comments: