Knowledge about IOS Networks

Source: Internet
Author: User

I. Confirm the network environment 3g/WiFi

1. Add source files and framework to develop Web applications. Program You need to confirm the network environment, connection conditions and other information. If they are not processed, they will not be reviewed by Apple. Apple's routine reachability describes how to obtain/detect the network status. To use Reachability in an application, complete the following two steps: 1.1. add source file: to use Reachability in your program, you only need to Reachability in this routine. H and reachability. copy m to your project. Example: 1. 2. Add framework: Add systemconfiguration. Framework to the project. Example: 2. network Status reachability. h defines three network statuses: typedef Enum {notreachable = 0, // reachableviawifi is not connected, // use 3g/GPRS network reachableviawwan // use WiFi network} 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. when the current network Environment Program is started, if you want to check the available network environment, you can // check whether WiFi + (bool) isenablewifi {return ([[reachability reachabilityforlocalwifi] currentreachabilitystatus]! = Notreachable);} // whether it is 3G + (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 the network connection status is checked in real time, and notification is also necessary in network applications. When the connection status changes, you must promptly notify the user of 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 = [[reachabi Lity sharedreachability] remotehoststatus];} // notifies the network status-(void) reachabilitychanged :( nsnotification *) Note {[self updatestatus]; If (self. remotehoststatus = notreachable) {alert * Alert = [[delealloc] initwithtitle: nslocalizedstring (@ "appname", nil) message: nslocalizedstring (@ "notreachable", nil) delegate: nil cancelbuttontitle: @ "OK" otherbuttontitles: Nil]; [alert show]; [alert re Lease] ;}} // program initiator, which starts network monitoring-(void) applicationdidfinishlaunching :( uiapplication *) Application {// sets the network detection site [[reachability sharedreachability] sethostname: @ "www.apple.com"]; [[reachability sharedreachability] setnetworkstatusnotifnotifsenabled: Yes]; // sets the notification function when the network status changes [[nsicationicationcenter defacenter center] addobserver: Self selector: @ selector (reachabilitychanged :) name: @ "knetworkreachabilitychang Ednotification "Object: Nil]; [self updatestatus];}-(void) dealloc {// Delete notification object [[nsicationicationcenter 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) app Licationdidfinishlaunching :( uiapplication *) Application {//... // monitor network conditions [[nsicationicationcenter 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 nsmutableurlreq Uest * request = [nsmutableurlrequest requestwithurl: [nsurl urlwithstring: [self urlstring]; [nsurlconnection connectionwithrequest: Request delegate: Self]; 2. nsurlconnection delegate method-(void) connection :( nsurlconnection *) connection response :( nsurlresponse *) response;-(void) connection :( nsurlconnection *) connection didfailwitherror :( nserror *) error; -(void) connection :( nsurlconnecti On *) connection didreceivedata :( nsdata *) data;-(void) connectiondidfinishloading :( nsurlconnection *) connection; 3. delegate method-(void) connection :( nsurlconnection *) connection didreceiveresponse :( nsurlresponse *) response {// store data [self. receiveddata setlength: 0]; // usually the cache for receiving data is cleared here}-(void) connection :( nsurlconnection *) connection didreceivedata :( nsdata *) Data {[self. receiveddata appenddata: dat A]; // 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 {// error handling}-(void) connectiondidfinishloading :( nsurlconnection *) connection {// disconnect [uiapplication sharedapplication]. networkactivityindicatorvisible = no; nsstring * returnstring = [[nsstring alloc] initwithdata: Self. receiveddata encoding: nsutf8stringencoding]; nslog (returnst Ring); [self urlloaded: [self urlstring] data: Self. receiveddata]; firsttimedownloaded = yes;} 3: Use nsxmlparser to parse the XML file 1. set the delegate object and start parsing nsxmlparser * parser = [[nsxmlparser alloc] initwithdata: Data]; // or you can 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 netwo Rk, maid in responding to connection errors. [parser setdelegate: Self]; [parser parse]; 2. common delegate method-(void) parser :( nsxmlparser *) parser didstartelement :( nsstring *) elementname namespaceuri :( nsstring *) namespaceuri principal :( nsstring *) QNAME attributes :( nsdictionary *) attributedict; -(void) parser :( nsxmlparser *) parser didendelement :( nsstring *) elementname namespaceuri :( nsstring *) Name Spaceuri qualifiedname :( nsstring *) QNAME;-(void) parser :( nsxmlparser *) parser foundcharacters :( nsstring *) string;-(void) parser :( nsxmlparser *) parser failed :( 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] initwithc Ontentsofurl: url]; [parser setdelegate: Self]; [parser setshouldprocessnamespaces: No]; [parser attributes: 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 :( n Sstring *) namespaceuri qualifiedname :( nsstring *) QNAME attributes :( nsdictionary *) attributedict {// element start handle if (QNAME) {elementname = QNAME;} If ([elementname isinclutostring: @ "user"]) {// nslog (@ "name is % @, age is % @", [attributedict objectforkey: @ "name"], [attributedict objectforkey: @ "Age"]) ;}}- (void) parser :( nsxmlparser *) parser didendelement :( nsstring *) elementname namespaceuri :( NS String *) namespaceuri qualifiedname :( nsstring *) QNAME {// element end handle if (QNAME) {elementname = QNAME ;}}-(void) parser :( nsxmlparser *) parser foundcharacters :( nsstring *) string {// retrieve element text} nserror * parseerror = nil; [self parsexmlfileaturl: [nsurl urlwithstring: feedurlstring] parseerror: & parseerror]; using nsoperation and nsoperationqueue to start multiple threads in the App Store is very cumbersome. They have good interfaces but have poor operability. For example, when a program loads data from the Internet or locally, The interface is frozen. You can only perform operations after the program fully loads data. When you open an application, the iPhone will generate a thread containing the main method. The interfaces in the program used are all running in this thread (table views, Tab bars, alerts ...), Sometimes we will fill these views with data. Now we ask how to effectively load data and the user can operate the program freely. The method is to start a new thread for data download, and the main thread will not be blocked because of data download. Regardless programming language It is troublesome to implement multithreading. Worse, once an error occurs, it is usually quite bad. Fortunately, Apple has made many improvements in this regard from OS x10.5. The introduction of nsthread makes it much easier to develop multi-threaded applications. In addition, they introduce two completely new classes, nsoperation and nsoperationqueue. Next we will use an example to illustrate how to use these two classes to implement multithreading. This shows the basic usage of these two classes. Of course, this is not the only way to use them. If you are familiar with Java or other variant languages, you will find that the nsoperation object is similar to Java. lang. runnable interface, Just Like java. lang. as with the runnable interface, the nsoperation class is also designed to be scalable, and there is only one method to override. It is-(void) Main. The simplest way to use nsoperation is to add an nsoperation object to the nsoperationqueue queue. Once the object is added to the queue, the queue starts to process the object, until all operations on this object are completed. Then it is released by the queue. In the following example, a web page is obtained, its nsxmldocument parsing process is used, and the nsxmldocument parsed is returned to the main thread. Pageloadoperation. h @ interface pageloadoperation: nsoperation {nsurl * TargetUrl;} @ property (retain) nsurl * TargetUrl;-(ID) initwithurl :( nsurl *) URL; @ end pageloadoperation. M # import "pageloadoperation. H "# import" appdelegate. H "@ implementation pageloadoperation @ synthesize TargetUrl;-(ID) initwithurl :( nsurl *) URL; {If (! [Super init]) return nil; [self settargeturl: url]; return self;}-(void) dealloc {[TargetUrl release], TargetUrl = nil; [Super dealloc];} -(void) Main {nsstring * webpagestring = [[nsstring alloc] initwithcontentsofurl: [self TargetUrl] autorelease]; nserror * error = nil; nsxmldocument * Document = [[nsxmldocument alloc] initwithxmlstring: webpagestring options: nsxmldocumenttidyhtml error: & error]; if (! Document) {nslog (@ "% s error loading document (% @): % @", _ cmd, [[self TargetUrl] absolutestring], error); return ;} [[appdelegate shared] performselecw.mainthread: @ selector (pageloaded :) withobject: Document waituntildone: Yes]; [document release] ;}@ end as we can see, this class is quite simple. It accepts and saves a URL in its init method. When the main function is called, it creates a string using the saved URL, and pass the string to the nsxmldocumentinit method. If the XML data to be loaded has no error, the data will be passed to appdelegate, which is in the main thread. At this point, the task of this thread is completed. The nsoperation object will be released when the operation queue is canceled in the main thread. Appdelegate. h @ interface appdelegate: nsobject {nsoperationqueue * queue;} + (ID) shared;-(void) pageloaded :( nsxmldocument *) document; @ endappdelegate. M # import "appdelegate. H "# import" pageloadoperation. H "@ implementation appdelegatestatic appdelegate * shared; static nsarray * urlarray;-(ID) Init {If (shared) {[self autorelease]; return shared;} If (! [Super init]) return nil; nsmutablearray * array = [[nsmutablearray alloc] init]; [array addobject: @ "http://www.google.com"]; [array addobject: @ "http://www.apple.com"]; [array addobject: @ "http://www.yahoo.com"]; [array addobject: @ "http://www.zarrastudios.com"]; [array addobject: @ "http://www.macosxhints.com"]; urlarray = array; queue = [[nsoperationqueue alloc] init]; shared = self; return self;} • (void) AP Annotations: (nsnotification *) anotification {for (nsstring * urlstring in urlarray) {nsurl * url = [nsurl urlwithstring: urlstring]; pageloadoperation * PLO = [[pageloadoperation alloc] initwithurl: url]; [queue addoperation: PLO]; [PLO release] ;}}- (void) dealloc {[queue release], queue = nil; [Super dealloc];} + (ID) shared; {If (! Shared) {[[appdelegate alloc] init];} return shared;}-(void) pageloaded :( nsxmldocument *) document; {nslog (@ "% s do something with the xmldocument: % @ ", _ cmd, document) ;}@ end nsoperationqueue parallel control (nsoperationqueue concurrency) in the preceding simple example, it is hard to see that these operations are run in parallel, however, if your operation takes much longer than the time, you will find that the queue executes these operations at the same time. Fortunately, you can use the setmaxconcurrentoperationcount: Method of nsoperationqueue if you want to limit the number of operations for a queue at the same time. For example, [queue setmaxconcurrentoperationcount: 2];
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.