用Swift开发一个简单的新闻App

分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友 微信微信
查看查看323 回复回复4 收藏收藏 分享淘帖 转播转播 分享分享 微信
查看: 323|回复: 4
收起左侧

用Swift开发一个简单的新闻App

[复制链接]
代码买卖 发表于 2016-6-18 04:22:43 | 显示全部楼层 |阅读模式
快来登录
获取优质的苹果资讯内容
收藏热门的iOS等技术干货
拷贝下载Swift Demo源代码
订阅梳理好了的知识点专辑



1、利用Swift开发一个简单的新闻App

主要利用iOS的UITableViewController,和UIwebView,再加上HTTP请求返回json数据并解析。



2、App演示

主界面:

用Swift开发一个简单的新闻App 1

用Swift开发一个简单的新闻App - 敏捷大拇指 - 用Swift开发一个简单的新闻App 1


点击新闻进入详情:

用Swift开发一个简单的新闻App 2

用Swift开发一个简单的新闻App - 敏捷大拇指 - 用Swift开发一个简单的新闻App 2


下拉列表刷新:

用Swift开发一个简单的新闻App 3

用Swift开发一个简单的新闻App - 敏捷大拇指 - 用Swift开发一个简单的新闻App 3





3、APPDelegate.swift

[Swift] 纯文本查看 复制代码
// 
// AppDelegate.swift 
// UITableViewControllerDemo 
// 
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

[Swift] 纯文本查看 复制代码
// 
// RootTableViewController.swift 
// UITableViewControllerDemo 
// 
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

[Swift] 纯文本查看 复制代码
// 
// WebViewController.swift 
// UITableViewControllerDemo 
// 
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

[Swift] 纯文本查看 复制代码
// 
// XHNewsItem.swift 
// UITableViewControllerDemo 
// 
import Foundation 
class XHNewsItem { 
 var newsTitle = NSString() 
 var newsThumb = NSString() 
 var newsID = NSString() 
}




都看到这里了,就把这篇资料推荐给您的好朋友吧,让他们也感受一下。

回帖是一种美德,也是对楼主发帖的尊重和支持。

*声明:敏捷大拇指是全球最大的Swift开发者社区、苹果粉丝家园、智能移动门户,所载内容仅限于传递更多最新信息,并不意味赞同其观点或证实其描述;内容仅供参考,并非绝对正确的建议。本站不对上述信息的真实性、合法性、完整性做出保证;转载请注明来源并加上本站链接,敏捷大拇指将保留所有法律权益。如有疑问或建议,邮件至marketing@swifthumb.com

*联系:微信公众平台:“swifthumb” / 腾讯微博:@swifthumb / 新浪微博:@swifthumb / 官方QQ一群:343549891(满) / 官方QQ二群:245285613 ,需要报上用户名才会被同意进群,请先注册敏捷大拇指

嗯,不错!期待更多好内容,支持一把:
支持敏捷大拇指,用支付宝支付10.24元 支持敏捷大拇指,用微信支付10.24元

评分

参与人数 1金钱 +10 收起 理由
Anewczs + 10 发帖就是光荣,分享精神可嘉!.

查看全部评分

swifter 发表于 2016-6-19 18:16:18 | 显示全部楼层
容易入门~~
1起来 发表于 2016-6-20 16:17:28 | 显示全部楼层
上手快!
f4yfv24 发表于 2016-7-6 09:25:21 | 显示全部楼层
不错的文章,希望楼主多发表一些有关swift开发的文章
不是我教你诈 发表于 2016-7-6 19:17:23 | 显示全部楼层
学习一下,谢谢楼主~
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

做任务,领红包。
我要发帖

分享扩散

都看到这里了,就把这资料推荐给您的好朋友吧,让他们也感受一下。
您的每一位朋友访问此永久链接后,您都将获得相应的金钱积分奖励
热门推荐

合作伙伴

Swift小苹果

  • 北京治世天下科技有限公司
  • ©2014-2016 敏捷大拇指
  • 京ICP备14029482号
  • Powered by Discuz! X3.1 Licensed
  • swifthumb Wechat Code
  •   
快速回复 返回顶部 返回列表