Wax framework concise tutorial (4) Wax HTTP + XML example

Source: Internet
Author: User

I would like to introduce the second part of the article "Building NativeiOS Apps with Wax: Creating a Sample Application". It introduces the Wax Application implementation process for retrieving twitter themes from iOS. Twitter data is encapsulated in JSON format.

However, unfortunately, domestic users cannot directly access twitter servers due to the well-known reasons. So I modified this example and changed it to HTTP + XML. The server is implemented in java. During debugging, you can place the server locally, so that it is not subject to network restrictions. In addition, server data is encapsulated in XML format. In my experience, XML is more likely to be used than JSON.

However, the problem is that wax_http does not implement XML format data. You can view its source code, which only implements three formats: text, json, and binary. If you use json, json Parsing is not required in wax_http. As shown in the example of "Building NativeiOS Apps with Wax: Creating a Sample Application", everything is transparent.

Therefore, we can only Parse XML by ourselves. This document uses the "Luaonly XML parser" method. This implementation was first originated from Alexander makeeve, and many versions are derived later.

We found a version on github, which is the modified version of the CoronaXML Module, called LuaSimple XML Parser.

This XML parser has only one simpleXml. lua file, which is easy to use-copy it to your project directory for use.

 

I. Server

 

As an example, the server code is simple enough, which is directory. jsp:

<% // Important; otherwise, garbled characters %>

<% @ Page contentType = "text/html; charset = UTF-8" language = "java" errorPage = "" %>

<%

Stringuser = request. getParameter ("user ");

Stringpass = request. getParameter ("pass ");

Out. println ("<? Xmlversion = \ "1.0 \" encoding = \ "UTF-8 \"?> ");

If (user! = Null | pass! = Null ){

Stringxml = "<list> <deptname = 'authorization' id = '01'> <linkman id = '001' name = 'Guo shuquan '/>" +

"<Linkman id = '003 'name = 'foob'/>" +

"</Dept>" + "<dept name = 'department of human strength 'id = '02'> <linkman id = '002' name = 'wang fee'>" +

"</Linkman> </dept> </list> ";

System. out. println (xml );

// Response. setCharacterEncoding ("UTF-8 ");

Out. println (xml );

} Else {

Out. println ("<login> <status> false </status> </login> ");

}

%>

The code is basically static. You can save your HTML code as a. htm file.

 

Ii. Wax implementation

Create a Single ViewApplication project. Add the Wax framework. For more information about how to install the Wax framework, see "Install Wax in XCode 4.2.

Next we are going to implement a WaxApplication. The first is the main. m file:

# Import <UIKit/UIKit. h>

# Import "wax. h"

# Import "wax_http.h"

# Import "wax_xml.h"

# Import "wax_filesystem.h"

Intmain (int argc, char * argv []) {

NSAID utoreleasepool * pool = [[NSAID utoreleasepoolalloc] init];

Wax_start ("AppDelegate. lua", luaopen_wax_http, luaopen_wax_xml, luaopen_wax_filesystem, nil );

Int retVal = UIApplicationMain (argc, argv, nil, @ "AppDelegate ");

[Pool release];

Return retVal;

}

 

Note "wax_xml.h" and "luaopen_wax_xml" in the code ". It turns out to be "wax_json.h" and "luaopen_wax_json ". We used to use wax. xml replaces wax. json, but since wax implements wax. xml, but it is not used in wax_http. In fact, "wax_xml.h" and "luaopen_wax_xml" have no meaning here.

 

Then there is AppDelegate. lua:

 

Require "MyTableViewController"

 

WaxClass {"AppDelegate", protocols = {"UIApplicationDelegate "}}

 

Function applicationDidFinishLaunching (self, application)

Local frame = UIScreen: mainScreen (): bounds ()

Self. window = UIWindow: initWithFrame (frame)

Self. controller = MyTableViewController: init ()

Local nc = UINavigationController: initWithRootViewController (self. controller)

Self. window: setRootViewController (nc)

Self. window: makeKeyAndVisible ()

End

When the application starts, it does not directly load MyTableViewController, but uses a NavigationController to load MyTableViewController. This provides us with an additional NavigationBar.

 

Finally, the implementation of MyTableViewController. lua is as follows:

 

Require ("xmlSimple ")

 

WaxClass {"MyTableViewController", UITableViewController}

 

Function init (self)

Self. super: initWithStyle (UITableViewStyleGrouped)

Self. trends = {}

 

Return self

End

 

Function viewDidLoad (self)

Self: setTitle ("Wax Http + XML example ")

Self: tableView (): setAllowsSelection (false)

Local button = UIBarButtonItem: initWithBarButtonSystemItem_target_action (UIBarButtonSystemItemRefresh, self, "loadDataFromTwitter ")

Self: navigationItem (): setRightBarButtonItem (button)

End

 

FunctionloadDataFromTwitter (self)

UIApplication: sharedApplication (): setNetworkActivityIndicatorVisible (true) -- show spinner

Wax. http. request {"http: /localhost: 8080/AnyMail/directory. jsp? User = 1 & pass = 1 ", callback = function (body, response)

UIApplication: sharedApplication (): setNetworkActivityIndicatorVisible (false) -- hide spinner

Local xml = xmlSimple: newParser ()

Local parseXml = xml: ParseXmlText (body)

If response: statusCode () = 200 then

Self. trends ={} -- Reset the list oftrends when the trends are refreshed

-- [[]

For index, value in ipairs (parseXml. list. dept) do -- iterateover a table with numerical keys

Table. insert (self. trends, "+" .. value ["@ name"]) -- append the value to the "array"

Linkman = value. linkman

Puts (# linkman)

If linkman ~ = Nil then

If # linkman> 0 then

For I, v in ipairs (linkman) do

Table. insert (self. trends, "-". v ["@ name"])

End

Else

Table. insert (self. trends, "-" .. linkman ["@ name"])

End

End

End

End

Self: tableView (): reloadData ()

End}

End

 

Function numberOfSectionsInTableView (self, tableView)

Return 1

End

 

Function tableView_numberOfRowsInSection (self, tableView, section)

Return # self. trends

End

 

FunctiontableView_titleForHeaderInSection (self, tableView, section)

If section = 0 then

Return "enterprise address book"

End

 

Return nil

End

 

Function tableView_cellForRowAtIndexPath (self, tableView, indexPath)

Local identifier = "TwitterTableViewControllerCell"

Local cell = tableView: dequeueReusableCellWithIdentifier (identifier) or

UITableViewCell: initWithStyle_reuseIdentifier (UITableViewCellStyleDefault, identifier)

 

Local object = self. trends [indexPath: row () + 1] -- Must + 1 because Lua arrays are 1 based

Cell: textLabel (): setText (object)

 

Return cell

End

 

There are not many codes. You can directly paste them into a file to run them. Many codes, such as the implementation of the TableViewDataSource method, are familiar to you in the "Wax framework concise tutorial (2. The main concern is the loadDataFromTwitter function (the function name has not been changed ...).

First, of course, require ("simpleXml "). Then construct a simpleXml object:

 

Local xml = xmlSimple: newParser ()

 

Then the ParseXmlText method is used to convert the xml string into a lua table:

LocalparseXml = xml: ParseXmlText (body)

 

In our example, the content of our XML file is:

 

<? Xml version = "1.0" encoding = "UTF-8"?>

<List>

<Dept name = 'authorization' id = '01'>

<Linkmanid = '001' name = 'Guo shuquan '/>

<Linkmanid = '003 'name = 'foob'/>

</Dept>

 

<Dept name = 'hr Department 'id = '02'>

<Linkmanid = '002' name = 'wang fee'> </linkman>

</Dept>

</List>

 

If you want to access the first linkman subnode of 2nd dept nodes, use parseXml. dept [2]. linkman. Convert to a lua table like this (only the node parseXml. dept [2]. linkman. If the content of the entire table is printed, it will be too much ):

{

AddProperty = function: 0x6a6f050,

@ Id = "002 ",

NumProperties = function: 0x6a68200,

NumChildren = function: 0x6a71a30,

Properties = function: 0x6a681e0,

@ Name = "",

AddChild = function: 0x6a71a50,

___ Children = {

},

SetName = function: 0x6a6f5a0,

Name = function: 0x6a6f0b0,

___ Name = "linkman ",

Value = function: 0x6a71db0,

___ Props = {

1 = {

Name = "id ",

},

2 = {

Name = "name ",

Value = function: 0x6a6f0b0,

},

},

Children = function: 0x6a191d0,

SetValue = function: 0x6a6f010,

}

 

 

The next thing is to traverse the Lua table. This is a matter of intra-Lua, so I don't need to talk about it. It is worth mentioning that there are three possible sub-nodes for a node. Take the linkman in dept as an example:

1. This subnode does not exist. In this case, dept [I]. linkman returns nil;

2. There are multiple subnodes. In this case, dept [I]. linkman returns an array of numeric indexes (Lua table). Each element of the array is a lua table (including all attributes and values of linkman );

3. There is only one subnode. In this case, dept [I]. linkman still returns a lua table, but this lua table directly contains all the attributes and values of linkman.

In other words, two or three cases have different processing methods. For a single subnode, we can directly access the attributes of linkman in the form of linkman [I] Or linkman [k. For multiple sub-nodes, linkman [I] can only access one lua table (linkman [k] cannot be used for access, because at this time linkman only contains the number key index, does not include text key indexes). Then, you can use the index or key of this lua table to access the linkman attribute.

 

Okay. Run Wax Application. Click Refresh in the navigation bar. TableView loads XML data as follows:

 


 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.