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

@UIApplicationMain
class 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 UIKit

class 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 UIKit

class 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 Foundation

class XHNewsItem {
    var newsTitle = NSString()
    var newsThumb = NSString()
    var newsID = NSString()
}


Create funky, impressive applications using Swift About This Book Learn Swift language features quickly, with playgrounds and in-depth examples Implement real iOS apps using Swift and Cocoapods Create professional video games with SpriteKit, SceneKit, and Swift Who This Book Is For This book is intended for those who want to learn to develop apps in Swift the right way. Whether you are an expert Objective-C programmer or new to this platform, you'll learn quickly, grasping the code of real-world apps to use Swift effectively. Prior experience in development for Apple devices would be helpful, but is not mandatory. What You Will Learn Explore the features of Swift Connect to a server and parse JSON data Take advantage of CocoaPods to use third-party libraries Utilize a clean and effective architecture to decrease complexity and speed up development Work with the most useful parts of the iOS SDK Build video games with SpriteKit and SceneKit Develop apps from start to finish Implement a weather app using fake data In Detail When Apple announced Swift at the WWDC, the iOS developer community became excited about the opportunities to improve the way in which they build iOS apps. Swift is a user-friendly language with a smooth learning curve; it is safe, robust, and flexible, and it introduces new ways to solve old problems. Swift by Example is a fast-paced, practical guide that shows you how to develop iOS apps using Swift. Through the development of six different apps, you'll learn how to use either the right feature of the language or the right tool to solve a given problem. By the end of the book you will be able to build well-designed apps, effectively use AutoLayout, and develop a video game. Table of Contents Chapter 1: Welcome to the World of Swift Chapter 2: A Memory Game in Swift Chapter 3: A TodoList App in Swift Chapter 4: A Pretty Weather App Chapter 5: Flappy Swift Chapter 6: Polishing Flappy Swift Chapter 7: Cube Runner Chapter 8: Completing Cube Runner
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

赵侠客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值