Swift簡單新聞APP執行個體

來源:互聯網
上載者:User

標籤:swift   app   簡單   

1.利用swift開發一個簡單的新聞APP主要利用IOS的UITableViewController,和UIwebView,再加上HTTP請求返回json資料並解析2.APP示範主介面點擊新聞進入詳情
下拉式清單重新整理3.APPDelegate.swif
////  AppDelegate.swift//  UITableViewControllerDemo////  Created by 趙超 on 14-6-24.//  Copyright (c) 2014年 趙超. 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 application 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 is 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 begins the transition to the background state.        // Use this method to 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 resources, save user data, invalidate timers, and store enough application state information to restore your application to its current 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 you can undo many of the changes made on entering the background.    }    func applicationDidBecomeActive(application: UIApplication) {        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.    }    func applicationWillTerminate(application: UIApplication) {        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.    }}

4.RootTableViewController.swift
////  RootTableViewController.swift//  UITableViewControllerDemo////  Created by 趙超 on 14-6-24.//  Copyright (c) 2014年 趙超. All rights reserved.//import UIKitclass RootTableViewController: UITableViewController {    var dataSource = []        var thumbQueue = NSOperationQueue()        let hackerNewsApiUrl = "http://qingbin.sinaapp.com/api/lists?ntype=%E5%9B%BE%E7%89%87&pageNo=1&pagePer=10&list.htm"    override func viewDidLoad() {        super.viewDidLoad()        // Uncomment the following line to preserve selection between presentations        // self.clearsSelectionOnViewWillAppear = false        // Uncomment the following line to display an 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: "下拉重新整理")        refreshControl.addTarget(self, action: "loadDataSource", forControlEvents: UIControlEvents.ValueChanged)        self.refreshControl = refreshControl                                 loadDataSource()            }    override func didReceiveMemoryWarning() {        super.didReceiveMemoryWarning()        // Dispose of any resources that can be 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 rows in the section.                     return dataSource.count    }        func loadDataSource() {        self.refreshControl.beginRefreshing()        var loadURL = NSURL.URLWithString(hackerNewsApiUrl)        var request = NSURLRequest(URL: loadURL)        var loadDataSourceQueue = NSOperationQueue();                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 = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary                let newsDataSource = json["item"] as NSArray                                var currentNewsDataSource = 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 = currentNewsDataSource                    self.tableView.reloadData()                    self.refreshControl.endRefreshing()                    })            }            })    }    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {                     let cell = tableView .dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell            let newsItem = dataSource[indexPath.row] as XHNewsItem        cell.textLabel.text = newsItem.newsTitle        cell.imageView.image = UIImage(named :"cell_photo_default_small")        cell.imageView.contentMode = UIViewContentMode.ScaleAspectFit                            let request = NSURLRequest(URL :NSURL.URLWithString(newsItem.newsThumb))        NSURLConnection.sendAsynchronousRequest(request, queue: thumbQueue, completionHandler: { response, data, error in            if error {                println(error)                            } else {                let image = UIImage.init(data :data)                dispatch_async(dispatch_get_main_queue(), {                    cell.imageView.image = image                    })            }            })                        return cell    }        override func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat {        return 80    }    // #pragma mark - Segues    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {        println("aa")    }        //選擇一行     override func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!){        var row=indexPath.row as Int        var data=self.dataSource[row] as XHNewsItem        //入棧                var webView=WebViewController()        webView.detailID=data.newsID        //取導航控制器,添加subView        self.navigationController.pushViewController(webView,animated:true)    }    }

5.WebViewController.swift
////  WebViewController.swift//  UITableViewControllerDemo////  Created by 趙超 on 14-6-24.//  Copyright (c) 2014年 趙超. All rights reserved.//import UIKitclass WebViewController: UIViewController {        var detailID = NSString()    var detailURL = "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 that can be recreated.    }        /*    // #pragma mark - Navigation    // In a storyboard-based application, you will often want to do a little preparation 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 趙超 on 14-6-24.//  Copyright (c) 2014年 趙超. All rights reserved.//import Foundationclass XHNewsItem {    var newsTitle = NSString()    var newsThumb = NSString()    var newsID = NSString()}


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.