Wednesday, December 23, 2015

Connect iOS device to HTTP GET/POST PHP service (iOS Part)

This post shows how to make an iPhone / iPad connect  a PHP service on Raspberry Pi using HTTP GET / POST methods.

Raspberry Pi Part

Follow the instructions in:

Connect iOS device to HTTP GET/POST PHP service (Raspberry Pi Part)

iOS Part

1. Modify ViewController.swift as below:


import UIKit

class ViewController: UIViewController {
    
    let urlString = "http://192.168.xx.xx/ios.php"
    
    var labelRead : UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let buttonGet = UIButton(frame: CGRectMake(70, 100, 200, 20))
        buttonGet.setTitle("GET", forState: UIControlState.Normal)
        buttonGet.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
        buttonGet.setTitleColor(UIColor.cyanColor(), forState: UIControlState.Highlighted)
        buttonGet.addTarget(self, action: "getPressed:", forControlEvents: UIControlEvents.TouchUpInside)
        view.addSubview(buttonGet)
        
        let buttonPost = UIButton(frame: CGRectMake(70, 200, 200, 20))
        buttonPost.setTitle("POST", forState: UIControlState.Normal)
        buttonPost.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
        buttonPost.setTitleColor(UIColor.cyanColor(), forState: UIControlState.Highlighted)
        buttonPost.addTarget(self, action: "postPressed:", forControlEvents: UIControlEvents.TouchUpInside)
        view.addSubview(buttonPost)
        
        let label = UILabel(frame: CGRectMake(50,300,250,30))
        label.text = "Message from Server:"
        label.textAlignment = NSTextAlignment.Center //Align to center
        view.addSubview(label)
        
        labelRead = UILabel(frame: CGRectMake(50,350,250,100))
        labelRead.textAlignment = NSTextAlignment.Center
        labelRead.numberOfLines = 0 //Multi-lines
        view.addSubview(labelRead)
    }
    
    func getPressed(sender: UIButton) {
        
        let component = NSURLComponents(string: urlString)
        component?.queryItems = [NSURLQueryItem(name: "language", value: "Swift"), NSURLQueryItem(name: "product", value: "iPhone")]

        let request = NSMutableURLRequest(URL: (component?.URL)!)
        request.HTTPMethod = "GET"
        
        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()
    }
    func postPressed(sender: UIButton) {
        
        let request = NSMutableURLRequest(URL: NSURL(string: urlString)!)
        request.HTTPMethod = "POST"

        let postString = "name=Peter&age=20"
        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 GET method are language and product, while parameters using the POST method are name and age.

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:



More information about ATS:

Open an insecure internet image
Working with Apple's App Transport Security
Apple will require HTTPS connections for iOS apps by the end of 2016

3. Build and Run the code again after modifying Info.plist. The results:

GET:


POST:


No comments:

Post a Comment