Environment: IOS 6.1 and xcode 4.6
1. Create a new project
1. Open xcode, file --> New --> project... --> Empty Application
2. The project name is nsurlconnectiondemo. If none of the following options are selected, the creation is complete.
Ii. Create a View Controller
3. file --> New --> file --> Objective-C Class
4. Create a subclass of uiviewcontroller named testviewcontroller.
3. Create a View Controller instance
5. Introduce in appdelegate. m
# Import "testviewcontroller. H"
6. Add testviewcontroller to the form
-(Bool) Application :( uiapplication *) Application didfinishlaunchingwitexceptions :( nsdictionary *) launchoptions
{
Self. Window = [[[uiappswalloc] initwithframe: [[uiscreenmainscreen] bounds] autorelease];
Testviewcontroller * rootcontroller = [[testviewcontrolleralloc] init];
Self. Window. rootviewcontroller = rootcontroller;
Self. Window. backgroundcolor = [uicolorwhitecolor];
[Self. windowmakekeyandvisible];
[Rootcontroller release];
Returnyes;
}
7. Add two variables to testviewcontroller. h.
@ Interface testviewcontroller: uiviewcontroller {
Nsmutabledata * pagedata;
Uiwebview * webview;
}
8. Add the button and uiwebview in testviewcontroller. M.
-(Void) viewdidload
{
[Superviewdidload];
// Do any additional setup after loading the view.
Uibutton * button = [uibuttonbuttonwithtype: uibuttontyperoundedrect];
[Self. View addsubview: button];
[Button settitle: @ "start" forstate: uicontrolstatenormal];
[Button setframe: cgrectmake (300, 40)];
[Button addtarget: selfaction: @ selector (Openurl) forcontrolevents: uicontroleventtouchupinside];
Webview = [[uiwebviewalloc] initwithframe: cgrectmake (0, 50,320,400)];
[Webviewsetuserinteractionenabled: No];
[Webviewsetbackgroundcolor: [uicolorclearcolor];
[Webview setopaque: No];
[Self. View addsubview: webview];
}
9. Events for Button clicking
-(Void) Openurl
{
Nsurl * url = [nsurlurlwithstring: @ "http://www.baidu.com"];
Nsmutableurlrequest * request = [[nsmutableurlrequestalloc] initwithurl: URL cachepolicy: nsurlrequestreloadignoringlocalcachedatatimeoutinterval: 60];
Pagedata = [[nsmutabledata alloc] init];
[Request sethttpmethod: @ "get"];
[Request addvalue: @ "text/html" forhttpheaderfield: @ "Content-Type"];
Nsurlconnection * conn = [[nsurlconnectionalloc] initwithrequest: Request delegate: Self];
[Request release];
[Conn release];
}
10. Two methods for implementing the nsurlconnection proxy
-(Void) connection :( nsurlconnection *) aconn didreceivedata :( nsdata *) Data {
[Pagedata appenddata: Data];
}
-(Void) connectiondidfinishloading :( nsurlconnection *) aconn {
Nsstring * Results = [[nsstringalloc] initwithdata: pagedataencoding: nsutf8stringencoding];
[Webviewloadhtmlstring: Results baseurl: Nil];
}
<End>