Swift Simple News App Example

Source: Internet
Author: User

1. Use Swift to develop a simple news appThe main use of iOS uitableviewcontroller, and UIWebView, plus HTTP request to return JSON data and parse 2.APP demoMain interfaceClick the News entry details
The drop-down list refreshes 3. Appdelegate.swif
appdelegate.swift//uitableviewcontrollerdemo////Created by Carrie on 14-6-24.//Copyright (c) 2014 Carrie.                                All rights Reserved.//import Uikit@uiapplicationmainclass Appdelegate:uiresponder, uiapplicationdelegate {    var Window:uiwindow?        Func application (application:uiapplication, Didfinishlaunchingwithoptions launchoptions:nsdictionary?), Bool { Self.window = UIWindow (Frame:UIScreen.mainScreen (). Bounds)//Override point for customization after Applicatio        N Launch. self.window!. BackgroundColor = Uicolor.whitecolor () self.window!. Makekeyandvisible () var root=roottableviewcontroller () var navctrl=uinavigationcontroller (RootViewController : root) self.window!.  Rootviewcontroller=navctrl return True} func applicationwillresignactive (application:uiapplication) {//Sent when the application are about-to-move from active to inactive state. This can occur for certain types OF temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it is        Gins the transition to the background state. Use the This method to the pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates.    Games should use this method to pause the game. } func Applicationdidenterbackground (application:uiapplication) {//Use this method to release shared resource s, save user data, invalidate timers, and store enough application state information to restore your application to its CU        Rrent state in case it is terminated later. If your application supports background execution, this method is called instead of Applicationwillterminate:when the    User quits.  } func Applicationwillenterforeground (application:uiapplication) {//called as part of the transition from the Background to the inactive state;    Here's can undo many of the changes made on entering the background. } func APPlicationdidbecomeactive (application:uiapplication) {//Restart any tasks this were paused (or not yet started) W Hile the application was inactive.    If the application is previously in the background, optionally refresh the user interface. } func applicationwillterminate (application:uiapplication) {//Called when the application are about to Termina Te. Save data if appropriate.    See also Applicationdidenterbackground:. }}

4.roottableviewcontroller.swift
roottableviewcontroller.swift//uitableviewcontrollerdemo////Created by Carrie on 14-6-24.//Copyright (c) 2014 Carrie. All rights Reserved.//import Uikitclass Roottableviewcontroller:uitableviewcontroller {var dataSource = [] va R thumbqueue = Nsoperationqueue () Let Hackernewsapiurl = "http://qingbin.sinaapp.com/api/lists?ntype=%E5%9B%BE%E7%8 9%87&pageno=1&pageper=10&list.htm "override func Viewdidload () {super.viewdidload ()//uncom         ment the following line to preserve selection between presentations//Self.clearsselectiononviewwillappear = False        Uncomment the following line to display a Edit button in the navigation bar for this view controller. Self.navigationItem.rightBarButtonItem = Self.editbuttonitem self.tableview!.         RegisterClass (uitableviewcell.self, Forcellreuseidentifier: "cell") Let Refreshcontrol = Uirefreshcontrol () Refreshcontrol.attributedtitle = NsatTributedstring (String: "Drop-down Refresh") Refreshcontrol.addtarget (Self, Action: "Loaddatasource", Forcontrolevents:uicontrol            events.valuechanged) Self.refreshcontrol = Refreshcontrol Loaddatasource () } override func Didreceivememorywarning () {super.didreceivememorywarning ()//Dispose of any resource    s that can is recreated. }//#pragma mark-table view data source override Func Numberofsectionsintableview (Tableview:uitableview?)        Int {//#warning potentially incomplete method implementation.                Return the number of sections.  Return Datasource.count} override func TableView (Tableview:uitableview, numberofrowsinsection section:int)        Int {//#warning incomplete method implementation.                     Return the number of the rows in the section. Return Datasource.count} func Loaddatasource () {self.refreshControl.beginRefreshing () var Loadurl = Nsurl. URLWithString (hackernewsapiurl) var request = Nsurlrequest (Url:loadurl) var loaddatasourcequeue = Nsoperati                Onqueue (); Nsurlconnection.sendasynchronousrequest (Request, Queue:loaddatasourcequeue, Completionhandler: {response, data,                    Error in if error {println (error) Dispatch_async (Dispatch_get_main_queue (), { Self.refreshControl.endRefreshing ()})} else {Let JSON = N Sjsonserialization.jsonobjectwithdata (data, Options:NSJSONReadingOptions.MutableContainers, Error:nil) as Nsdictionary Let Newsdatasource = json["Item"] as Nsarray var currentnewsdat Asource = Nsmutablearray () for Currentnews:anyobject in Newsdatasource {let NewsItem = Xhnewsitem () Newsitem.newstitle = currentnews["title"] as NSString newsitEm.newsthumb = currentnews["thumb"] as nsstring Newsitem.newsid = currentnews["id"] as NSString                                Currentnewsdatasource.addobject (NewsItem) println (Newsitem.newstitle)} Dispatch_async (Dispatch_get_main_queue (), {self.datasource = CURRENTNEWSDA                    Tasource Self.tableView.reloadData () self.refreshControl.endRefreshing () })}})} override Func TableView (Tableview:uitableview, Cellforrowatindexpath indexp Ath:nsindexpath), UITableViewCell {let cell = TableView. Dequeuereusablecellwithidentifier ("cel L ", Forindexpath:indexpath) as UITableViewCell let NewsItem = Datasource[indexpath.row] as Xhnewsitem c Ell.textLabel.text = Newsitem.newstitle Cell.imageView.image = UIImage (named: "Cell_photo_default_small") CE Ll.imageView.contentMode = Uiviewcontentmode.scaleaspectfit Let request = Nsurlrequest (Url:nsurl. URLWithString (Newsitem.newsthumb)) nsurlconnection.sendasynchronousrequest (Request, Queue:thumbqueue, CompletionH                 Andler: {response, data, error in if error {println (Error)} else {                    Let image = Uiimage.init (Data:d ata) Dispatch_async (Dispatch_get_main_queue (), {    Cell.imageView.image = image})}) return cell } override Func TableView (tableview:uitableview!, Heightforrowatindexpath indexpath:nsindexpath!), Cgfloa T {return +}//#pragma mark-segues override func Prepareforsegue (Segue:uistoryboardsegue, sender:a Nyobject?) {println ("AA")}//Select one line override func TableView (tableview:uitableview!, Didselectrowatindexpath IND expath:nsindexpath!) {var rOw=indexpath.row as Int var data=self.datasource[row] as Xhnewsitem//into the stack var webview=webviewc Ontroller () Webview.detailid=data.newsid//Take navigation controller, add Subview Self.navigationController.pushViewControl Ler (Webview,animated:true)}}

5.webviewcontroller.swift
webviewcontroller.swift//uitableviewcontrollerdemo////Created by Carrie on 14-6-24.//Copyright (c) 2014 Carrie. All rights Reserved.//import Uikitclass Webviewcontroller:uiviewcontroller {var detailid = NSString () var deta        Ilurl = "http://qingbin.sinaapp.com/api/html/" var webview:uiwebview? Func Loaddatasource () {var urlstring = Detailurl + "\ (detailid). html" var url = nsurl. URLWithString (urlstring) var urlrequest = Nsurlrequest (url:nsurl. URLWithString (urlstring)) webview!.        Loadrequest (URLRequest)} override func Viewdidload () {super.viewdidload () Webview=uiwebview () webview!. Frame=self.view.frame webview!. Backgroundcolor=uicolor.graycolor () Self.view.addSubview (WebView) Loaddatasource ()//Do any    Additional setup after loading the view. } override func Didreceivememorywarning () {super.didreceivememorywarning ()//Dispose of any resources t HAt can is recreated. }/*//#pragma mark-navigation//In a storyboard-based application, you'll often want to do a little PR Eparation before navigation override func Prepareforsegue (Segue:uistoryboardsegue?, Sender:anyobject?)        {//Get the new view controller using [Segue Destinationviewcontroller].    Pass the selected object to the new view controller. }    */}

6.xhnewsitem.swift
  xhnewsitem.swift//  uitableviewcontrollerdemo////  Created by Carrie on 14-6-24.//  Copyright (c) 2014 Carrie. All rights Reserved.//import Foundationclass Xhnewsitem {    var newstitle = nsstring ()    var newsthumb = nsstring () 
   var NewsID = NSString ()}


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.