Now we are in the Internet era, any software or app, will be more or less with the network, and the continuous occurrence of data interaction. An app that doesn't involve network programming will look low, and here we'll start using Swift to develop iOS apps, and primarily for network operational functions.
The requirement here is to get the HTML source code for a webpage, that is, to get the data from the Internet. The specific implementation is as follows:
(1) Create an iOS project, language select Swift. Then implement the following code in Viewcontroller.swift:
Override Func Viewdidload () { super.viewdidload () var str = nsstring (Contentsofurl:nsurl (string: "/HTTP// Www.baidu.com "), encoding:nsutf8stringencoding, Error:nil) println (str!) The above returned is the optional type optional value, the return value may be empty, and when I make sure there is a return value, use an exclamation point! Gets the value; }
(2) Run the program, print the results in the console: (Baidu homepage HTML content too much, I only copy out part of)
With the above code, we can successfully obtain the source code from the Web page. But because I in the above comments on the problem of the optional, I decided to optimize the code, even if the network data access is not successful or there are empty exceptions, and so on, can also give feedback to the user a hint, the optimization code as follows, note that the optional type is empty operation. Override Func Viewdidload () { super.viewdidload () var strhtml = NSString (Contentsofurl:nsurl (string: "111111" )!, encoding:nsutf8stringencoding, Error:nil) if let print = strhtml{ println (strhtml!) } else{ println ("Failed to get Network data")} }
Run the above code to return the "failed to get network data" prompt. Even if the network has an abnormal system will not crash.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
iOS project development--ios network programming get web page HTML source code