IOS Development notes (6) network programming Summary

Source: Internet
Author: User
Reproduced from: http://www.cocoachina.com/bbs/read.php? Tid-31300.html 1: Confirm network environment 3g/WiFi 1. Add source file and framework

When developing Web and other network applications, you must confirm the network environment, connection conditions, and other information. If they are not processed, they will not pass Apple's review.
Apple's routine reachability describes how to obtain/detect the network status. To use Reachability in an application, you must first complete the following two steps:

1.1. Add the source file:
To use Reachability in your program, you only need to copy the reachability. h and reachability. m in this routine to your project. For example:



1. 2. Add the framework:
Add systemconfiguration. Framework to the project. For example:


2. Network Status

Three Network statuses are defined in reachability. h:
Typedef Enum {
Notreachable = 0, // No connection
Reachableviawifi, // use 3g/GPRS network
Reachableviawwan // use WiFi
} Networkstatus;

Therefore, you can check the network status as follows:

Reachability * r = [reachability reachabilitywithhostname: @ "www.apple.com"];
Switch ([R currentreachabilitystatus]) {
Case notreachable:
// No network connection
Break;
Case reachableviawwan:
// Use a 3G network
Break;
Case reachableviawifi:
// Use a Wi-Fi network
Break;
}

3. Check the current network environment
When the program starts, if you want to detect the available network environment, you can
// Whether WiFi is enabled
+ (Bool) isenablewifi {
Return ([[reachability reachabilityforlocalwifi] currentreachabilitystatus]! = Notreachable );
}

// Whether it is 3 GB
+ (Bool) isenable3g {
Return ([[reachability reachabilityforinternetconnection] currentreachabilitystatus]! = Notreachable );
}
Example:
-(Void) viewwillappear :( bool) animated {
If ([reachability reachabilityforinternetconnection]. currentreachabilitystatus = notreachable )&&
([Reachability reachabilityforlocalwifi]. currentreachabilitystatus = notreachable )){
Self. navigationitem. hidesbackbutton = yes;
[Self. navigationitem setleftbarbuttonitem: Nil animated: No];
}
}

4. Real-time notification of Link Status
Real-time check of network connection status and notification are also necessary in network applications. When the connection status changes, you must promptly notify the user:

Reachability 1.5
// My. appdelegate. h
# Import "reachability. H"

@ Interface myappdelegate: nsobject <uiapplicationdelegate> {
Networkstatus remotehoststatus;
}

@ Property networkstatus remotehoststatus;

@ End

// My. appdelegate. m
# Import "myappdelegate. H"

@ Implementation myappdelegate
@ Synthesize remotehoststatus;

// Update the network status
-(Void) updatestatus {
Self. remotehoststatus = [[reachability sharedreachability] remotehoststatus];
}

// Notifies the network status
-(Void) reachabilitychanged :( nsnotification *) Note {
[Self updatestatus];
If (self. remotehoststatus = notreachable ){
Uialertview * Alert = [[uialertview alloc] initwithtitle: nslocalizedstring (@ "appname", nil)
Message: nslocalizedstring (@ "notreachable", nil)
Delegate: Nil cancelbuttontitle: @ "OK" otherbuttontitles: Nil];
[Alert show];
[Alert release];
}
}

// Program initiator to start Network Monitoring
-(Void) applicationdidfinishlaunching :( uiapplication *) Application {

// Set the site for network detection
[[Reachability sharedreachability] sethostname: @ "www.apple.com"];
[[Reachability sharedreachability] setnetworkstatusicationsenabled: Yes];
// Set the notification function when the network status changes
[[Nsicationcenter center defacenter center] addobserver: Self selector: @ selector (reachabilitychanged :)
Name: @ "knetworkreachabilitychangednotification" Object: Nil];
[Self updatestatus];
}

-(Void) dealloc {
// Delete the notification object
[[Nsicationcenter center defacenter center] removeobserver: Self];
[Window release];
[Super dealloc];
}

Reachability 2.0

// Myappdelegate. h
@ Class reachability;

@ Interface myappdelegate: nsobject <uiapplicationdelegate> {
Reachability * hostreach;
}

@ End

// Myappdelegate. m
-(Void) reachabilitychanged :( nsnotification *) Note {
Reachability * curreach = [Note object];
Nsparameterassert ([curreach iskindofclass: [reachability class]);
Networkstatus status = [curreach currentreachabilitystatus];

If (status = notreachable ){
Uialertview * Alert = [[uialertview alloc] initwithtitle: @ "appname ""
Message: @ "notreachable"
Delegate: Nil
Cancelbuttontitle: @ "yes" otherbuttontitles: Nil];
[Alert show];
[Alert release];
}
}

-(Void) applicationdidfinishlaunching :( uiapplication *) Application {
//...

// Monitor network conditions
[[Nsicationcenter center defacenter center] addobserver: Self
Selector: @ selector (reachabilitychanged :)
Name: kreachabilitychangednotification
Object: Nil];
Hostreach = [[reachability reachabilitywithhostname: @ "www.google.com"] retain];
Hostreach startcycler];
//...
}

Ii. Use nsconnection to download data

1. Create an nsconnection object and set the delegate object

Nsmutableurlrequest * request = [nsmutableurlrequest requestwithurl: [nsurl urlwithstring: [self urlstring];
[Nsurlconnection connectionwithrequest: Request delegate: Self];

2. nsurlconnection delegate delegation Method
-(Void) connection :( nsurlconnection *) connection didreceiveresponse :( nsurlresponse *) response;
-(Void) connection :( nsurlconnection *) connection didfailwitherror :( nserror *) error;
-(Void) connection :( nsurlconnection *) connection didreceivedata :( nsdata *) data;
-(Void) connectiondidfinishloading :( nsurlconnection *) connection;

3. Delegate Methods
-(Void) connection :( nsurlconnection *) connection didreceiveresponse :( nsurlresponse *) response {
// Store data
[Self. receiveddata setlength: 0]; // generally, the cache for receiving data is cleared first.
}

-(Void) connection :( nsurlconnection *) connection didreceivedata :( nsdata *) Data {
/* Appends the new data to the stored ed data */
[Self. receiveddata appenddata: Data]; // you may receive the data multiple times and add the new data to the end of the existing data.
}

-(Void) connection :( nsurlconnection *) connection didfailwitherror :( nserror *) error {
// Handle errors
}

-(Void) connectiondidfinishloading :( nsurlconnection *) connection {
// Disconnect
[Uiapplication sharedapplication]. networkactivityindicatorvisible = no;
Nsstring * returnstring = [[nsstring alloc] initwithdata: Self. receiveddata encoding: nsutf8stringencoding];
Nslog (returnstring );
[Self urlloaded: [self urlstring] data: Self. receiveddata];
Firsttimedownloaded = yes;
}

Iii. Use nsxmlparser to parse XML files

1. Set the delegate object and start Parsing
Nsxmlparser * parser = [[nsxmlparser alloc] initwithdata: Data]; // you can also use initwithcontentsofurl to directly download the object, but this is not the case for one reason:
// It's also possible to have nsxmlparser download the data, by passing it a URL, but this is not desirable
// Because it gives less control over the network, especially in responding to connection errors.
[Parser setdelegate: Self];
[Parser parse];

2. Common delegate Methods
-(Void) parser :( nsxmlparser *) parser didstartelement :( nsstring *) elementname
Namespaceuri :( nsstring *) namespaceuri
Qualifiedname :( nsstring *) QNAME
Attributes :( nsdictionary *) attributedict;
-(Void) parser :( nsxmlparser *) parser didendelement :( nsstring *) elementname
Namespaceuri :( nsstring *) namespaceuri
Qualifiedname :( nsstring *) QNAME;
-(Void) parser :( nsxmlparser *) parser foundcharacters :( nsstring *) string;
-(Void) parser :( nsxmlparser *) parser parseerroccurred :( nserror *) parseerror;

Static nsstring * feedurlstring = @ "http://www.yifeiyang.net/test/test.xml ";

3. Application Example
-(Void) parsexmlfileaturl :( nsurl *) URL parseerror :( nserror **) Error
{
Nsxmlparser * parser = [[nsxmlparser alloc] initwithcontentsofurl: url];
[Parser setdelegate: Self];
[Parser setshouldprocessnamespaces: No];
[Parser setshouldreportnamespaceprefixes: No];
[Parser setshouldresolveexternalentities: No];
[Parser parse];
Nserror * parseerror = [parser parsererror];
If (parseerror & error ){
* Error = parseerror;
}
[Parser release];
}

-(Void) parser :( nsxmlparser *) parser didstartelement :( nsstring *) elementname namespaceuri :( nsstring *) namespaceuri
Qualifiedname :( nsstring *) QNAME attributes :( nsdictionary *) attributedict {
// Element start handle
If (QNAME ){
Elementname = QNAME;
}
If ([elementname isinclutostring: @ "user"]) {
// Output Attribute Value
Nslog (@ "name is % @, age is % @", [attributedict objectforkey: @ "name"], [attributedict objectforkey: @ "Age"]);
}
}

-(Void) parser :( nsxmlparser *) parser didendelement :( nsstring *) elementname namespaceuri :( nsstring *) namespaceuri
Qualifiedname :( nsstring *) QNAME
{
// End handle of the element
If (QNAME ){
Elementname = QNAME;
}
}

-(Void) parser :( nsxmlparser *) parser foundcharacters :( nsstring *) String
{
// Obtain the text of an element
}

Nserror * parseerror = nil;
[Self parsexmlfileaturl: [nsurl urlwithstring: feedurlstring] parseerror: & parseerror];

Related Article

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.