본문 바로가기
모바일개발(Mobile Dev)/IOS개발(ObjectC)

How To Make an iPhone App Connect to a MySQL Database

by 테크한스 2015. 11. 27.
반응형

written by http://codewithchris.com/iphone-app-connect-to-mysql-database/


How To Make an iPhone App Connect to a MySQL Database

This is Chapter 2 of 5
This article is the second chapter of my guide on Building Apps With MySQL and WordPress.

This guide shows you how to make three different MySQL/Wordpress powered apps that all leverage the benefit of having a web hosting account.

The first chapter shows you how to sign up for one.

In this chapter, we’ll set up our MySQL database and create the first app that will read data from it.

The title of this article is a little “off” because the app won’t directly connect to the MySQL database in order to retrieve data, however, this is the way that most people phrase it when they ask me this question! Let’s take a look at the outline of what we’re going to accomplish in this tutorial:


1. How to setup your database

Once you’ve received your confirmation email from signing up, you can now create a new database in your Bluehost control panel.

Start by clicking the database menu item:

Next you’ll get to the database screen where you’ll do 3 things:
– Create a new database
– Create a new database user
– Add the user to the database


1.1 Create a new database

So in the screenshot below, I’ve named my database sampledb.
Then click “Create Database”.

Creating a new database with Bluehost


1.2 Create a new database user

Next, we need to create a new database user.
Give the user a name and password and click “Create User”.

Creating a new database user


1.3 Add the user to the database

Finally, we need to give this user access to the newly created database so in the form below, choose the database you created from the dropdown and choose the user that you just created and click “Add”.

Adding a user to the database

For now, let’s grant this user all the privileges so that we can set up our database tables.
Later on, we’ll remove most of these privileges and limit the user to just reading data to secure it.
Alternatively, you can create two new database users, one with only read privileges and one with all privileges to act as an administrator.

Adding database user privileges in Bluehost

Click “Make Changes” and now we’re ready to go!

2. How to connect your iPhone app to a MySQL database

In this section, I’m going to explain how we’re going to get our iPhone app to connect to the MySQL database and we’ll also create some database tables and fill it with some data.

First, let’s explain how we’re going to do this.

Unfortunately the iPhone app is not going to be able to connect directly to our MySQL database. What we need is to create a middle-man that will facilitate the database operations.

This is where the PHP web service comes in. The web service is going to sit on our web server and when the iPhone app sends a request to it, it’s going to query the database for the requested data and then return it to the iPhone app in a format that it can understand.

Now, you’re not limited to using PHP to write your web service but PHP and MySQL usually go hand in hand so that’s what we’ll be doing today.

Here’s a diagram of what the system looks like:

How an iPhone app connects to a remote MySQL database

So before we build the iPhone app or the PHP web service, let’s create some database tables and fill it with data.

In this example app, I’m going to demonstrate a common scenario of pulling a list of locations down from the database and displaying the locations in a tableview (scrollable list).

When the user taps on a location, it will show a map view with a pin indicating the location.

So, in our database we’re going to want to store a list of locations.


2.1 Launching phpMyAdmin

Start by going back out to your Bluehost control panel and looking for the phpMyAdmin icon.
It should be under the “Database Tools” section. When you find it, click it to go into the database management tool.
(If you don’t see the icon, double check the menu at the top that you’re in the “cPanel” tab and not “Home”)

Bluehost phpMyAdmin icon

When you encounter the login screen, you should login with the same database user credentials that you created earlier.

phpMyAdmin login screen

By logging in as the database user that you created, you’ll have access to the new database you created because you granted this user access to it!

After you log in, you’ll see your database on the left hand side.

phpMyAdmin select database

Click the database that you created and the right hand side will change to allow us to create a new database table.


2.2 Creating a database table

Creating a new database table in phpMyAdmin

Call your new database table “Locations”, enter “4” for the number of columns and click “Go”.

In the pop up dialog, you’ll be able to customize the 4 table columns. Follow the screenshot below and then click “Save”.

Creating columns in a MySQL database table

On the next screen, you’ll see your newly created database table.


2.3 Inserting data into the database table

We’re going to insert a couple of locations into the table now so click “Insert” as shown below:

Inserting data into the database table

I decided to add the locations of the Apple and Google headquarters. You can fill in the same thing or fill in some different locations of your own!

If you need to find the lat long of an address, just use this website.

When you’re ready, click the last “Go” button to insert both rows into your database table.

Adding locations to our database table

Now you’ll see the actual SQL statement which added the data!
SQL stands for Structured Query Language and it’s a programming language to express queries from simple ones to really complex ones that involve multiple tables and constraints.

When you’re using this web interface, phpMyAdmin, to work with your database, you’re running SQL statements in the background when you click a “Go” or “Save” button.

If you’re working with databases a lot, it would really pay to learn SQL!

After inserting rows into the table

Next, click the “Browse” button and see the data in the table.

Browsing our Locations MySQL table

Now that we have some sample data in the MySQL database, let’s move on to creating that PHP web service that’ll connect to the MySQL database and query it for the list of locations (and then return the results to the iPhone app).

3. How to write a simple PHP web service to query your MySQL database and return the results to your iPhone app

Now let’s create a simple PHP service to query our database for the results.


3.1 Creating the PHP service

Open up a text editor and paste the following code into it, then save it as service.php:

In line 4, you’ll want to change the following placeholders:
-username : use the username of the db user that you set up in step 1
-password : use the password for the db user
-dbname : use the name of the database you created in step 1

Read the comments in the code above to see what each line does.

When you save the file, it should have a .php extension like this:
PHP file in finder


3.2 Uploading the PHP file to the server

Now you can use your favorite FTP client to upload this file to the root of your web host so that you can access this file from: http://yourdomain.com/service.php.

If you’re unsure of what FTP means, you can also upload this file from your Bluehost control panel.

Login to your cPanel and look for the “File Manager” icon:

Bluehost cPanel file manager icon

Click into that icon and it’ll bring you to a screen where you can see all the files on your web host.

In the left side panel, you’ll see a tree view navigation.

You want to click “public_html” which will open up the folder, then click “Upload” as shown below:

going to public_html in your file manager and uploading a file

On the next screen, choose “service.php” from your local system and upload the file.

Now you’ll be able to access it from: http://yourdomain.com/service.php.

Test this by going to that URL in your browser.

You should see something like this:

JSON results from the php service and MySQL database!

Now we’re ready to build the iPhone app that will read this feed!

4. How to make an iPhone app that will parse the MySQL database results and show them in a table view


4.1 Creating a new Xcode project
We’re going to start by creating a new single view application Xcode project.

Create a new Xcode single view application

Next, go to Main.Storyboard and let’s add a table view element to the view controllers view.

In the lower right hand corner, search for table view in the library pane and you should see the Table View and Table View Cell elements come up.

If you don’t see them, then double check that you’re looking at the correct tab as indicated by the screenshot below.

First drag and drop the Table View element over to your view (not the “table view controller” element!). If you hover over your view for a second or two before dropping it, the element will expand to cover the entire view. If not, then you can manually adjust the size.

Next, drag and drop a Table View Cell over the Table View.

You should end up with something like this:

Adding a table view and table view cell to the view

We also need to give the table cell a reuse identifier which we’re going to use later on.
So click the cell, then in the attributes inspector, change the Identifier to “BasicCell”. If you don’t see this box, check the tab you’re looking at.

Setting reuse identifier on the table cell

Now we’re going to expose the table view element to the View Controller code behind so that we can reference it when we’re writing our Objective-C code.

So let’s go into “Assistant Editor” view by clicking the top right corner “tuxedo” icon.

It’ll split your view into two panes and you’ll want the storyboard in the left pane and theViewController.h file on the right pane.
If you don’t see ViewController.h on the right side, just click the breadcrumb to change what it’s showing to ViewController.h.

Then you can hold control, click the table view element from the storyboard and drag your mouse over to the right hand side under the @interface tag.

You’ll see a blue line follow your cursor. You want to let go of your mouse and you’ll see a popup to prompt you for a name.

Name it “listTableView”. Now using this property name, you can reference this table view element when you write your Objective-C code in ViewController.m!

Exposing the table view as an IBOutlet

Your ViewController.h will look like this afterwards:

Note: If you need a refresher on connecting UIElements from the Storyboard to the view controller, check out this video/article.


4.2 Creating the model for the data

We want to follow MVC convention and create a separate class to handle the data so go ahead and right click the root folder in your file navigator and choose “New File…”.

Note: If you’re unfamiliar with MVC, you can read about this design pattern here

Adding new classes in Xcode 5

In the next dialog box, choose Objective-C class and name it HomeModel and subclass NSObject as shown below:

Adding the home model into our project

While we’re at it, let’s also create a class to represent the items we’ll be downloading.

Add another new class to your Xcode project, but this time call it Location and subclass NSObject.

Adding the location class to our Xcode project

Go into Location.h and add some properties like this:

Now let’s go into HomeModel.h and set up the header file.

We’ll need to declare a protocol which lets other classes know which methods it should expect to handle if it wants to get notified of certain events.

Note: The delegate pattern and protocols are something that I teach and go through inmy course.

So in HomeModel.h, change it to look like this:

In lines 3-7, we declare our HomeModel protocol and we also declare a delegate property in line 11.
This let’s other classes know that if they want to handle the delegate methods in the protocol, they must conform to the protocol and set themselves as the delegate (assign themselves to the delegate property)

You’ll see this in action later on.

We also declare a public method called “downloadItems” in line 13 with the intention that calling this method will kick start the process to retrieve the locations from the MySQL database.

Now in HomeModel.m, we have to implement the “downloadItems” method:


4.3 Downloading and parsing the JSON feed

If you recall in the previous section when we worked on the PHP service, we returned the results as JSON.

Now we can actually download and parse those items here in the HomeModel class. Specifically, in the “downloadItems” method that we created!

First, go back to HomeModel.h and we’re going to specify that this class conforms to the NSURLConnectionDataDelegate.

We’re using the NSURLConnection class to download the JSON feed and conforming to the NSURLConnectionDataDelegate will let us implement the appropriate delegate methods that get fired with certain events happen during the downloading.

Your HomeModel.h should look like this (line 9 is modified):

Now flip to HomeModel.m and add this code:

Remember to change the URL to your own php service in line 15.

Now the model is ready to download the items and notify the delegate when the “downloadItems” method is called.

The next thing we have to do is modify ViewController so that it calls this method to trigger the download and captures the delegate method of the HomeModel so it knows when to populate the table view.


4.4 Populating the table view with locations

Now we’re focusing our attention back to ViewController.

The table view element gets filled by answering its calls for data when it attempts to display rows.

Just like how we created the HomeModelProtocol so that other classes could interact with it, the UITableView class also has some protocols of its own.

You guessed it, we’re going to conform to those protocols with the ViewController class.
We’re also going to conform to the HomeModelProtocol because we want to get notified when the items have been downloaded.

So in ViewController.h, change it like this (line 2 and 4-5 changed):

Then in ViewController.m, add code like this:

There’s a lot happening in this file.

In lines 4-9, we’re declaring some instance variables for this class to keep track of the HomeModel object and an array to store the retrieved items.

In the “viewDidLoad” method, we’re setting this ViewController object as the datasource and delegate for the table view element.
This will let us implement the table view delegate methods farther down to populate the table view with data.

We also create a HomeModel object, set this ViewController object as the delegate for the HomeModel object and call the downloadItems method on it.

In Lines 40-49, you can see us implement the HomeModel’s protocol method “itemsDownloaded”.
In this method, we store the results passed back to us and call “reloadData” on the table view which will cause it to fire the methods farther below.

The methods after Line 51 will get called and correspond to displaying data.

In the method at Line 53, “numberOfRowsInSection”, we have to return the expected number of rows.
Then that will cause the table view to call the method at Line 59 that many number of times (one for each row).
It will only call that method if the row is in view.

In the method at Line 53, “cellForRowAtIndexPath”, this method expects us to create a table view cell, initialize it with some data and return it for display.

So what we do is get a copy of the cell we added in the Storyboard. We gave it an identifier of “BasicCell” if you remember.

This method will also tell us which row of data it’s trying to display, so we can use this information to access our feed data array to get the appropriate Location object that this table row is trying to display.

We configure the table cell with the data from the Location object and return it.

At this point, if you run the app, you should see your table view populate with the addresses from the MySQL database!

Showing MySQL database data in a table view!


4.5 Adding a second view controller: the map view

This section is going to seem very familiar to those who have gone through the map view tutorial already.

We’re going to do something similar here when an address is selected from the table view.

First let’s go into Main.Storyboard to add a second view controller.

Start by clicking your view controller to make sure it’s selected. You’ll know it’s selected because there’s a blue outline around it.

Then go up to the Editor menu and select “Embed in”, “Navigation Controller”.

Embed view controller in a navigation controller in Xcode

Once you do that, you’ll see a Navigation Controller appear in your storyboard.

In the lower right library pane, search for View Controller and drag and drop a new one beside your existing view controller.

Adding a second view controller to your Storyboard

Next, search for Map View in the library pane and drag and drop that into the second view controller.

Adding a map view in the storyboard

We also need to expose this map view element to the code behind of the second view controller but before we can do that, we actually need to create a custom class for this second view controller that we added through the storyboard.

So right click the root folder in your file navigator and select “New File”.
We’re going to add a new Objective-C class named “DetailViewController” and it’s going to subclass “UIViewController”.

Adding detail view controller

After adding this class, go back to Main.Storyboard and select your second view controller by clicking it and making sure there’s a blue outline around it.
Usually clicking the views top edge will select it.

Setting the custom class of a view controller through storyboards

After doing this, we can now open “Assistant Editor” and expose the map view as an IBOutlet (if you forgot how to do this, go back to the previous section when we did it for the Table View element).

Remember, on the left hand pane, you want to see the storyboard and the on the right hand pane, you want to see DetailViewController.h.

Name this IBOutlet “mapView”.

Unfortunately at this point, Xcode will be complaining about line 5 because it doesn’t know the MKMapView class.

We need to add the MapKit framework to our Xcode project.


4.6 Adding the MapKit framework

Click the project node in your file navigator and the right side pane will change to the project settings.

Project settings in Xcode 5

Scroll all the way down until you see the section titled “Linked Frameworks and Libraries”

Then click the little “+” button and search for “MapKit” in the dialog box that pops up.
Double click the “MapKit.framework” entry to add it to your project.

Adding the MapKit framework to Xcode 5

Now back in DetailViewController.h, import the framework and Xcode won’t complain.
While we’re here, also import the Location class and add a property to hold the location that this view controller will be mapping.

We’re close to the finish line!


4.7 Transitioning to the map view

The last thing to do is to transition to the map view when an address is selected from the table view.

In Main.Storyboard, we have to add a segue for the transition. The segue is like a transition that we can call in our code to trigger a screen transition.

Adding a segue to a second view controller in storyboard

Note: If adding additional view controllers and segues is foreign to you, I recommend you to check out this article/video about working with multiple views in your iPhone app which is where I demonstrate what it is and how to do it.

We still have to give this segue an identifier so we can trigger it programmatically in our code behind so select the segue and in the inspector in the right hand side, flip the tabs until you see a box saying “identifier”. Type in “detailSegue”.

Naming the segue in your storyboard

Now in ViewController.m, we can add code to trigger the segue when the user taps on an address.

Add the following code in the @interface section (line 3 and line 9 are new):

Still in ViewController.m, add the following method implementations before the @end tag.

In the above code, the “didSelectRowAtIndexPath” is another UITableView delegate method that gets triggered when the user taps a row.

Since this ViewController object already conforms to the UITableViewDelegate and it has already assigned itself as the delegate for the table view element, it can implement the “didSelectRowAtIndexPath” method.

In this method, we make a note of which Location object the user tapped on by tracking it with an instance variable, _selectedLocation.

Then we call the “performSegueWithIdentifier” method which will trigger a segue to happen.

Remember the segue we added through the storyboard? We named it “detailSegue” and it transitions to the detail view.

So when that’s what is going to happen. Before it actually happens though, “prepareForSegue” gets called and we get an opportunity to execute some code before the view finishes transitioning.

At this point, the DetailViewController object has already been created. We’re merely getting a reference to it via “segue.destinationViewController”.

We set its selectedLocation property to the Location object that the user tapped on earlier.

This will let DetailViewController work with the Location object once its view has loaded.

And now when the user taps an address, the view will transition to the second view controller.


4.8 Mapping the location

In the DetailViewController, we have access to the location object that we’re supposed to map because it was set in the prepareForSegue method of ViewController just before the transition happened.

However, if we try to set the map location in the “viewDidLoad”, the map hasn’t finished initializing yet and we won’t see the animation to our desired location.

Instead, we’re going to override the “viewDidAppear” method and place the code there to zoom into the desired latitude and longitude.

Your DetailViewController.m will look like this (the important method to note is “viewDidAppear”):

Now when you run the app, you should get your list of addresses and when you select one of them, you’ll transition to the map view where it’ll show you the location of it!

Mapping a location from the MySQL database

Conclusion

So there you have it! How to connect to a MySQL database from an iPhone app or more accurately put, how to retrieve data from a MySQL databased from your app.


반응형

'모바일개발(Mobile Dev) > IOS개발(ObjectC)' 카테고리의 다른 글

IOS image file path  (0) 2015.11.28
php prepare stmt json type call  (0) 2015.11.28
Getting Data From Web Services in JSON Format  (0) 2015.11.27
mysqli_stmt::bind_param  (0) 2015.11.23
making Stopwatch  (0) 2015.11.20