Network requests generally divided into synchronous requests and asynchronous requests, synchronous requests if the access time is too long, will cause the interface card dead state, the user experience is not very good. However, if the request is faster, you can also consider using synchronous access. Now learn to sync Access first.
(1) Implement the following code in the Viewdidload () method:
Override Func Viewdidload () { super.viewdidload () var data = Nsurlconnection.sendsynchronousrequest ( Nsurlrequest (Url:nsurl (string: "http://www.baidu.com")!), Returningresponse:nil, Error:nil) if let d = data{ println (NSString (data:d, encoding:nsutf8stringencoding)!) Print HTML }else{ println ("Failed to get Network data")} }
The output will print out the Web page HTML successfully.
(2) Print out the HTTP protocol header
Implement the following code in Viewdidload ():
Override Func Viewdidload () { super.viewdidload () var resp:nsurlresponse? var data = Nsurlconnection.sendsynchronousrequest (Nsurlrequest (Url:nsurl (string: "http://www.baidu.com")!), Returningresponse: &resp, Error:nil) if let R = resp{ println (R) //Print HTTP protocol header; } }
The output results are as follows:
。
(3) Print error message
In the network operation, the occasional error is unavoidable, we can print out errors, so that we check the wrong, the print error code is as follows:
Override Func Viewdidload () { super.viewdidload () var resp:nsurlresponse? var error:nserror? var data = Nsurlconnection.sendsynchronousrequest (Nsurlrequest (Url:nsurl (string: "http://www.baidu.com")!), Returningresponse: &resp, Error: &error) if let E = error{ println (E) //Print HTTP protocol header; } }
When we test the code, we can shut down the network, and then we get an error: When I test, the following errors occur:
。
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
iOS project development--use synchronous request to get web page source code