Create your own I am am OS application of Web services, the first part

Recommended for you: Get network issues from WhatsUp Gold. Not end users.
Follow the steps in this tutorial to learn how to create a iOS application Web service is called iGlobe.

In my previous TechRepublic series, we use the existing Web services to create iOS applications ("create a Web service, parts A and two"). In this series, we will create a Web service at iGlobe for different applications, this is a game, I long ago.

Basically, we want users to be able to mark a place or person, and get the action point. (won the money pot with the most points at the end of the game competition) in order to do this, applications to interact, we will create a Web service. Our Web service will need to be able to:

In this tutorial, we will use a helper class called SantiappsHelper, which contains the code to run those connected to Web. In this case, often referred to as a separate class library, need to take care of these processes. If you only need a class (in our example) an example, you create a Singleton model. You only want to connect with a case, because you don't want to create instances of classes, connected with many receiving, and disconnect - this might end up in multiple connections to the same resource at different times, which may confuse you or server.

What is here, we will in this series:

1. Create database Web

2. Create a Web service is

3. The front end created iOS (the story board)

4. Data acquisition

5. Add bump API

6. Throw in society

Step 1: create the Web database

Web services are usually large information database, the database will need a table to store all the information we mentioned above. Four main methods we and database: create, read, update, delete (CRUD) data. So, let, a short detour, talk about database - in particular, their structure, and how we interact with them.

Database

Database, it can be written to a file (such as Word or PowerPoint). The information in these files have a predetermined structure, Word and PowerPoint know how to read and access to it, what do you want, let you edit it, then stored, the problem is only Word will read the docx file, only PowerPoint can read pptx files. The great advantage database to store information, they can be read in a very compact way and many different interface. Simple database, multiple interfaces can read it.

Most web hosting services are usually provided free of charge, we will use a database. My web hosting service phpMySQL, including free package. If you want other databases such as MSSQL, you need a paid service.  Figure AIs my database management interface looks like.

Figure A

1

We have a two meter iglobe localhost: users and the tag database. User table( Figure B)Contain a primary key and a user name, a password, the password, first and last name, and e-mail, phone number, address, and the regular stuff.

Figure B

1

Tag list( Figure C)Also has its own primary key (TAGID), the corresponding user name, an identifier, label the longitude and latitude, date created, its value, how many points the user. One country areas, this is implemented, as the project progresses (it already works in since 2011).

Figure C

1

The second step: create a Web service end

Our Web service idea is to read and any data users that their request or they write from the table. This part will require some PHP you know. Let us start looking for what kind of code to read a table looks like.

<?php

include_once("JSON.php");
$json = new Services_JSON();

$link = mysql_pconnect("localhost", "user", "pass") or die("Could not connect");
mysql_select_db("iglobe") or die("Could not select database");

$arr = array();

$rs = mysql_query("SELECT * FROM users");
while($obj = mysql_fetch_object($rs)) {
	$arr[] = $obj;
}

Echo $json->encode($arr);

?>

First, we include the json.php file, in order to access your JSON file on the server (please make sure your network server or host, to provide you with at least PHP 5.2). Then, we make a connection to the database, using the database user name and password, and the database host. Now, we create an array of objects, so when we perform mysql_query from all the entries in the table are collected user to $RS, we can put the object till we reach [] object. Finally, we come to $JSON $ARR and encoding echo it onto the screen.

Once this code, and ready with your database (including some records), your browser can directly to the file (I call it myserver.com / getusers.php). I obtained the following results:

[{"id":"35","username":"zlitsami ","password":"932d1c42a4e4880e57037994fd3584b1","password_hint":"","lastname":"","firstname":"","email":"","phone":"","address1":"","address2":"","city":"","state":"","zip":"","country":"","url":"","permissions":"1","udid":"9","userCreated":"2013-01-01 14:27:22","time_queued":null,"time_sent":null}, {another}, {another}]

This is a lot of elements in the array. Each element is the table user. Each entry is a key to the dictionary. Familiar?

Now that we know how to read information from our database, to create the code written to the database.

<?php
$con = mysql_connect("localhost","user","pass");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("iglobe", $con);

$sql="INSERT INTO  tags (username, latitude, longitude, country,destintyudid,points) VALUES ('$_POST[sender]','$_POST[latitude]','$_POST[longitude]','$_POST[country]','$_POST[receiver]','$_POST[points]')";

if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }

echo "1 record added to tags";

mysql_close($con)
?>

Once again we connect to our database, we created a SQL statement to insert values (these values from one form, in the online or on mobile devices). We execute the SQL statement to contact us, and validate the user echo results. I call this file writephp.php.

Before, we moved to iOS, let the Internet test our service. Creates a HTML file called Writeform.html, this code is saved:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>
<body>
<form action="writephp.php" method="post">
  <table style="text-align: left; width: 100%;" border="0"
 cellpadding="2" cellspacing="2">
    <tbody>
      <tr>
        <td>Name:</td>
        <td><input name="sender" type="text"></td>
        <td></td>
      </tr>
      <tr>
        <td>UDID(unnecessary):</td>
        <td><input name="udid" type="text"></td>
        <td></td>
      </tr>
      <tr>
        <td>Latitude:</td>
        <td><input name="latitude" type="text"></td>
        <td></td>
      </tr>
      <tr>
        <td>Longitude:</td>
        <td><input name="longitude" type="text"></td>
        <td></td>
      </tr>
      <tr>
        <td>Country</td>
        <td><input name="country" type="text"></td>
        <td></td>
      </tr>
      <tr>
        <td>Receiver</td>
        <td><input name="receiver" type="text"></td>
        <td></td>
      </tr>
      <tr>
        <td></td>
        <td></td>
        <td><input type="submit"></td>
      </tr>
    </tbody>
  </table>
&nbsp;&nbsp;&nbsp;&nbsp;<br>
</form>
</body>
</html>

Now, you Webpage browser loading form and submit the data to your database.

I don't want this Web service is too complex, because I want to keep your focus on the iOS side, let us create a form, from the end of our service for a particular user read. Create another HTML file called Testform.html, this code is saved:

<HTML>
<head>

<form action="readpoints.php" method="post">
User: <input type="text" name="userNa"/>
<input type="submit" />

</form>
</head>
</HTML>

And the creation of PHP counterpart: 

<?php

include_once("JSON.php");
$json = new Services_JSON();

$link = mysql_pconnect("localhost", "user", "pass") or die("Could not connect");
mysql_select_db("iglobe") or die("Could not select database");

$username = $_POST["userNa"];

$result = mysql_query("SELECT username, SUM(points) AS PUNTOS FROM tags WHERE username='$username' GROUP BY username");
// THIS RETURNS ARRAY NOT READ PROPERLY BY iOS JSON
$resultado = array();
while($obj = mysql_fetch_object($result)) {
	$resultado[] = $obj;
}
Echo $json->encode($resultado);

?>

As soon as we get more data to the database, we will use this code after the last one.

So far, we have a resource, return to a specific user, readpoints.php, this is what the so-called Web service endpoint. Can have a lot of Web service endpoint. We may be in a game or application, once gained a lot of users, to fill a Leadership Council, for example. From invoice database, rather than one by one, we may want to get a lot of transactions. Therefore, a group of input data to our own and create endpoint management. In our example, we must be able to through a group of users of Web services. Our file looks like this:

<?php

include_once("JSON.php");
$json = new Services_JSON();

//1. PROCESS RECEIVED ARRAY
$handle = fopen("php://input", "rb");
$http_raw_post_data = '';
while (!feof($handle)) {
    $http_raw_post_data .= fread($handle, 8192);
}
fclose($handle);

//1.1 Just decode to see what kind of object it is
$post_data = json_decode($http_raw_post_data,true);

if (is_array($post_data))
    $response = array("status" => "ok", "code" => 0, "original request" => $post_data);
else
    $response = array("status" => "error", "code" => -1, "original_request" => $post_data);

//2. CALL DB QUERY
$link = mysql_pconnect("localhost", "username", "password") or die("Could not connect");
mysql_select_db("iglobe") or die("Could not select database");

//3. CREATE FINAL ARRAY TO RETURN
$arrayToReturn = array();

//4. CYCLE THROUGH USERS
foreach ($post_data as $value) 
{
  //CREATE QUERY
  $result = mysql_query("SELECT username, SUM(points) AS PUNTOS FROM tags WHERE username='$value' GROUP BY username");

  //EXECUTE QUERY & ADD EACH USER/POINTS DICTIONARY TO $resultado ARRAY
  $resultado = array();
  while($obj = mysql_fetch_object($result)){
	$arrayToReturn[] = $obj;
  }
}
Echo $json->encode($arrayToReturn);
?>

The basic PHP code, need to pass, array, as we mentioned before traversing the database, get points for each user. This is important, because our application is saved to the Web server database has many trips.

Step 3: create a iOS front end (the story board)

Now, we want to iOS the story board or the front of our work. Then, we hard coded data, and obtained from the actual back-end network, in this way, we can see the front will be needed in the data model, then we can obtain network data and replace our data, these data models. We will learn two ways to obtain the data: inline, messy code and clean code.

Follow the steps below:

 

  1. Create a new empty project use the story board, ARC, iPhone, no core data.
  2. Into the storyboard, and drag to the grid UITableViewController.
  3. Create a class UsersListViewController. Plot, choose the site, in the Identity inspector to make our scene UsersListViewController type from the drop-down list.
  4. Run a quick test, to ensure that our TVC work.
  5. Construction and operation. You should get an empty tableview.

 

Let us recall in this section, we will do what:

 

 

It is now second nature to you, so I will fight through the concrete.

Here the property code: 

@property (nonatomic, strong) NSArray *testArray;

Here's the viewDidLoad code:

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.testArray = [[NSArray alloc] initWithObjects:@"me", @"you", @"them", nil];
    NSLog(@"array %d", [self.testArray count]);
}

Here is the number of the returned array code: 
return [self.testArray count];

Here is the code cFRAIP: 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    // Configure the cell...
    cell.textLabel.text = [self.testArray objectAtIndex:indexPath.row];
    return cell;
}

In the construction and operation, selection in the story board of the UITableViewCell, in the "property" check, make sure that you use the battery as the reuse of identifiers. The application you should work.

If the construction and operation, the user should be displayed on the tableview. ! This is what we want to do - that is, to display a list of users in the tableview, then add some, like a score.

Figure DIs a model, our application will be what appearance. In nature, we will have a tab bar controller three views: user management, map and description. We will throw an application log view start. This should give you a what kind of tasks, we need to perform, in order to achieve this point.

a)Login now view controller

b)In addition to the user and transmit information

C)Access to the user data from the Web service

Fig. four) points on the map

E)Display in a view of that

Figure D

1

You should be able to re create in your story board. The basic steps here is:

1. Choose your existing UsersViewController site, from the "Edit" menu, select "embedded in the tab bar controller. You should have a scene and a class of UsersViewController, and identity inspector, field should be set to the type of its class.

2. The clear add embedded tableview in a tab bar (clear, I mean that it does not have any label or other control) of the second scene. Now drag a UIMapView to. Added on top of a UINavigationBar and two buttons (plot and concave and convex) on either side of the. Create it a class MapViewController, set its type. MKMapView the IBOutlet attribute added and two UIBarButtonItem IBOutlet attributes, and connect them. Add MKMapViewDelegate.

3. For the last view to add another UIViewController, and drag it to a UIWebView and UINavigationBar. Create its class file and name it InstructionsVC. UIWebView add a IBOutlet property, and the link. Add UIWebViewDelegate, don't forget to set the scene type.

4. Add a UIViewController, ModalViewController( Figure EWhat mine looks like), and create the IBOutlet attribute - this is the four labels, static text (user, pass, e-mail, and pass to...). Has three UITextFields with placeholder text, to guide the user. Three distinct operations UIButtons. Icon is a button set and background image, it will be "button, the user will use the Web server to upload their own image.

Now we can create other types of file TagListController, label / user mode, and comments/ PlacemarkVC.

Figure E

1

Visualization application for one or two minutes for the layout will be similar to we now have a better idea of where we want to go, then, comparing the initial sketches, you let the visualization of your application.

In the second part, we will connect to the Web service, and access to the actual data. "You create your own I we OS the application of Web service, the second part

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Avery at November 29, 2013 - 1:39 AM