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()
}

Swift简单新闻APP实例

时间: 2024-08-25 05:56:36

Swift简单新闻APP实例的相关文章

谷歌眼镜Mirror app开发之简单新闻浏览页面

Mirror app和Google glass其他APP一样,UI简洁很重要,所以我们需要设计一下怎么布局. 本人的布局如下: 有个绿色的标题,白色的简介还有蓝色的来源,布局很简单,代码如下 1 <article> 2 <img src="http://static.freebuf.com/2014/07/weixing-220x150.jpg" width="100%" height="100%"> 3 <div

用Swift语言做App开发之单元测试

作为一个有质量保障的应用程序,当然少不了单元测试:Swift开发的App也亦如此,此文将以一个简单的实例来介绍Swift中的单元测试. 这里我们使用XCode模版自带的XCTest框架,此框架包含了一个名为XCTestCase的类,所有的测试类都应该继承自它:按照约定俗成所有的测试方法名都应以test开头,并不能包含任何参数,只有这样,这些测试方法才能在运行测试时被自动执行:在每个测试方法里面,我们可以通过调用XCTAssert*函数去断言一个操作成功与否,如判等函数XCTAssertEqual

Swift简单入门教程:30分钟玩转Swift

通常来说,编程语言教程中的第一个程序应该在屏幕上打印“Hello, world”.在 Swift 中,可以用一行代码实现:    println("hello, world") 如果你写过 C 或者 Objective-C 代码,那你应该很熟悉这种形式——在 Swift 中,这行代码就是一个完整的程序.你不需要为了输入输出或者字符串处理导入一个单独的库.全局作用域中的代码会被自动当做程序的入口点,所以你也不需要main函数.你同样不需要在每个语句结尾写上分号. 这个教程会通过一系列编程

新闻APP后端系统架构成长之路

前言:一年来从接受APP后端工作到现在可谓一路艰辛,中间踏过无数坑坑洼洼,也从中学到很多很多,之前领导也多次提醒,平时多总结.把经验形成系统,但平时大部分时间一直在忙于开发.处理问题,天天马不停蹄的往前走.眼看着春节将至,16年又过去了,业务有了很大发展,我们系统也愈加完善.之前一直也没有时间静下心来后头看看,眼下随着6.0版本开发上线完毕,稍得片刻喘息,自己也想想,也是时候回头看看.总结一下了. 1,初入圣地 2,筑基:完全重构 3,金丹:踩坑..而且是踩大坑 4,元婴:面临挑战,流量来袭 5

网易新闻app左右菜单特效ios实现

效果图 图标素材是从网易新闻app里拿出来的 具体实现步骤: 1:界面搭建 >>最底部是一个普通的UIView,内部有三个控件:imageview放背景图片的.leftmenu (自定义左侧菜单).rightmenu(自定义右边菜单) >>左侧菜单思路:一个大View里边包了六个button >>   ....已经1点多了洗洗睡了....后续未完....其实亲自动手敲一个小应用才发现不是那么简单....里边要大量的自定义控件.... 网易新闻app左右菜单特效ios实现

Android Service AIDL 远程调用服务 简单音乐播放实例的实现

Android Service是分为两种: 本地服务(Local Service): 同一个apk内被调用 远程服务(Remote Service):被另一个apk调用 远程服务需要借助AIDL来完成. AIDL 是什么 AIDL (Android Interface Definition Language) 是一种IDL 语言,用于生成可以在Android设备上两个进程之间进行进程间通信(interprocess communication, IPC)的代码.如果在一个进程中(例如Activi

搜狐新闻APP是如何使用HUAWEI DevEco IDE快速集成HUAWEI HiAI Engine

6月12日,搜狐新闻APP最新版本在华为应用市场正式上线啦! 那么,这一版本的搜狐新闻APP有什么亮点呢? 先抛个图,来直接感受下-- ? 模糊图片,瞬间清晰! 效果杠杠的吧. 而藏在这项神操作背后的幕后操手, 竟然是HUAWEI HiAI Engine的图像超分辨率能力. 通过HUAWEI HiAI的图像超分能力处理的照片, 会更清晰,更锐利! 再看下图-- 就是这么任性~ 除此之外,HUAWEI HiAI Engine还提供了人脸识别. 图片识别.码识别.文本识别. 自然语音处理.自动语音识

python_爬虫_腾讯新闻app 单页新闻数据分析爬取

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px "Helvetica Neue"; color: #000000 } p.p2 { margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px "Helvetica Neue"; color: #000000; min-height: 12.0px } p.p3 { margin: 0.0px 0.0px 0.0px 0.0px;

Python---BeautifulSoup 简单的爬虫实例

对python自动化比较熟的同学,很多都懂一些爬虫方法,有些还研究的很深,下面呢我介 绍一个简单的爬虫实例,供大家参考.当然里面有很多需求是可以再学习的,下载进度的显 示.下载完成的提示等等. 一.首先我们要研究爬虫网站的架构,我这里已ring.itools.cn为例,我需要爬的是铃声. 大家可以自己去分析,这个网站的架构比较简单就不讲了. 我们最终要获取的是下面两个信息: 二.我们写下面的脚本来获取 上面的脚本呢,获取到songname和playaddr都是一组数据,即都是列表,我们需要把 他