Swift简单新闻APP实例

本文介绍了利用Swift开发简单新闻APP的过程,包含APP演示,如主界面展示、点击新闻进入详情、下拉列表刷新等功能。还给出了多个关键文件代码,如AppDelegate.swift、RootTableViewController.swift等,实现了数据加载、页面跳转等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.利用swift开发一个简单的新闻APP

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

2.APP演示

主界面

点击新闻进入详情


下拉列表刷新

3.APPDelegate.swif

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. //  
  2. //  AppDelegate.swift  
  3. //  UITableViewControllerDemo  
  4. //  
  5. //  Created by 赵超 on 14-6-24.  
  6. //  Copyright (c) 2014年 赵超. All rights reserved.  
  7. //  
  8.   
  9. import UIKit  
  10.   
  11. @UIApplicationMain  
  12. class AppDelegate: UIResponder, UIApplicationDelegate {  
  13.                               
  14.     var window: UIWindow?  
  15.   
  16.   
  17.     func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {  
  18.         self.window = UIWindow(frame: UIScreen.mainScreen().bounds)  
  19.         // Override point for customization after application launch.  
  20.         self.window!.backgroundColor = UIColor.whiteColor()  
  21.         self.window!.makeKeyAndVisible()  
  22.         var root=RootTableViewController()  
  23.         var navCtrl=UINavigationController(rootViewController:root)  
  24.         self.window!.rootViewController=navCtrl  
  25.           
  26.         return true  
  27.     }  
  28.   
  29.     func applicationWillResignActive(application: UIApplication) {  
  30.         // 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.  
  31.         // 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.  
  32.     }  
  33.   
  34.     func applicationDidEnterBackground(application: UIApplication) {  
  35.         // 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.  
  36.         // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.  
  37.     }  
  38.   
  39.     func applicationWillEnterForeground(application: UIApplication) {  
  40.         // 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.  
  41.     }  
  42.   
  43.     func applicationDidBecomeActive(application: UIApplication) {  
  44.         // 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.  
  45.     }  
  46.   
  47.     func applicationWillTerminate(application: UIApplication) {  
  48.         // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.  
  49.     }  
  50.   
  51.   
  52. }  

4.RootTableViewController.swift

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. //  
  2. //  RootTableViewController.swift  
  3. //  UITableViewControllerDemo  
  4. //  
  5. //  Created by 赵超 on 14-6-24.  
  6. //  Copyright (c) 2014年 赵超. All rights reserved.  
  7. //  
  8.   
  9. import UIKit  
  10.   
  11. class RootTableViewController: UITableViewController {  
  12.   
  13.     var dataSource = []  
  14.       
  15.     var thumbQueue = NSOperationQueue()  
  16.       
  17.     let hackerNewsApiUrl = "http://qingbin.sinaapp.com/api/lists?ntype=%E5%9B%BE%E7%89%87&pageNo=1&pagePer=10&list.htm"  
  18.   
  19.     override func viewDidLoad() {  
  20.         super.viewDidLoad()  
  21.   
  22.         // Uncomment the following line to preserve selection between presentations  
  23.         // self.clearsSelectionOnViewWillAppear = false  
  24.   
  25.         // Uncomment the following line to display an Edit button in the navigation bar for this view controller.  
  26.         // self.navigationItem.rightBarButtonItem = self.editButtonItem  
  27.           
  28.          
  29.         self.tableView!.registerClass(UITableViewCell.self, forCellReuseIdentifier"cell")  
  30.           
  31.         let refreshControl = UIRefreshControl()  
  32.         refreshControl.attributedTitle = NSAttributedString(string: "下拉刷新")  
  33.         refreshControl.addTarget(self, action"loadDataSource", forControlEvents: UIControlEvents.ValueChanged)  
  34.         self.refreshControl = refreshControl  
  35.           
  36.           
  37.           
  38.          loadDataSource()  
  39.           
  40.     }  
  41.   
  42.     override func didReceiveMemoryWarning() {  
  43.         super.didReceiveMemoryWarning()  
  44.         // Dispose of any resources that can be recreated.  
  45.     }  
  46.   
  47.     // #pragma mark - Table view data source  
  48.   
  49.     override func numberOfSectionsInTableView(tableView: UITableView?) -> Int {  
  50.         // #warning Potentially incomplete method implementation.  
  51.         // Return the number of sections.  
  52.           
  53.         return dataSource.count  
  54.     }  
  55.   
  56.     override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {  
  57.         // #warning Incomplete method implementation.  
  58.         // Return the number of rows in the section.  
  59.           
  60.        
  61.         return dataSource.count  
  62.   
  63.     }  
  64.       
  65.     func loadDataSource() {  
  66.         self.refreshControl.beginRefreshing()  
  67.         var loadURL = NSURL.URLWithString(hackerNewsApiUrl)  
  68.         var request = NSURLRequest(URL: loadURL)  
  69.         var loadDataSourceQueue = NSOperationQueue();  
  70.           
  71.         NSURLConnection.sendAsynchronousRequest(request, queue: loadDataSourceQueue, completionHandler: { response, data, error in  
  72.             if error {  
  73.                 println(error)  
  74.                 dispatch_async(dispatch_get_main_queue(), {  
  75.                     self.refreshControl.endRefreshing()  
  76.                     })  
  77.             } else {  
  78.                 let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary  
  79.                 let newsDataSource = json["item"] as NSArray  
  80.                   
  81.                 var currentNewsDataSource = NSMutableArray()  
  82.                 for currentNews : AnyObject in newsDataSource {  
  83.                     let newsItem = XHNewsItem()  
  84.                     newsItem.newsTitle = currentNews["title"] as NSString  
  85.                     newsItem.newsThumb = currentNews["thumb"] as NSString  
  86.                     newsItem.newsID = currentNews["id"] as NSString  
  87.                     currentNewsDataSource.addObject(newsItem)  
  88.                     println( newsItem.newsTitle)  
  89.                 }  
  90.                   
  91.                 dispatch_async(dispatch_get_main_queue(), {  
  92.                     self.dataSource = currentNewsDataSource  
  93.                     self.tableView.reloadData()  
  94.                     self.refreshControl.endRefreshing()  
  95.                     })  
  96.             }  
  97.             })  
  98.     }  
  99.   
  100.   
  101.     override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {  
  102.       
  103.           
  104.          let cell = tableView .dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell  
  105.       
  106.         let newsItem = dataSource[indexPath.row] as XHNewsItem  
  107.         cell.textLabel.text = newsItem.newsTitle  
  108.         cell.imageView.image = UIImage(named :"cell_photo_default_small")  
  109.         cell.imageView.contentMode = UIViewContentMode.ScaleAspectFit  
  110.           
  111.       
  112.           
  113.         let request = NSURLRequest(URL :NSURL.URLWithString(newsItem.newsThumb))  
  114.         NSURLConnection.sendAsynchronousRequest(request, queue: thumbQueue, completionHandler: { response, data, error in  
  115.             if error {  
  116.                 println(error)  
  117.                   
  118.             } else {  
  119.                 let image = UIImage.init(data :data)  
  120.                 dispatch_async(dispatch_get_main_queue(), {  
  121.                     cell.imageView.image = image  
  122.                     })  
  123.             }  
  124.             })  
  125.           
  126.           
  127.         return cell  
  128.     }  
  129.       
  130.     override func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat {  
  131.         return 80  
  132.     }  
  133.   
  134.     // #pragma mark - Segues  
  135.     override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {  
  136.         println("aa")  
  137.     }  
  138.       
  139.     //选择一行  
  140.      override func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!){  
  141.         var row=indexPath.row as Int  
  142.         var data=self.dataSource[row] as XHNewsItem  
  143.         //入栈  
  144.           
  145.         var webView=WebViewController()  
  146.         webView.detailID=data.newsID  
  147.         //取导航控制器,添加subView  
  148.         self.navigationController.pushViewController(webView,animated:true)  
  149.     }  
  150.       
  151.   
  152. }  

5.WebViewController.swift

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. //  
  2. //  WebViewController.swift  
  3. //  UITableViewControllerDemo  
  4. //  
  5. //  Created by 赵超 on 14-6-24.  
  6. //  Copyright (c) 2014年 赵超. All rights reserved.  
  7. //  
  8.   
  9. import UIKit  
  10.   
  11. class WebViewController: UIViewController {  
  12.       
  13.     var detailID = NSString()  
  14.     var detailURL = "http://qingbin.sinaapp.com/api/html/"  
  15.     var webView : UIWebView?  
  16.       
  17.     func loadDataSource() {  
  18.         var urlString = detailURL + "\(detailID).html"  
  19.         var url = NSURL.URLWithString(urlString)  
  20.         var urlRequest = NSURLRequest(URL :NSURL.URLWithString(urlString))  
  21.         webView!.loadRequest(urlRequest)  
  22.     }  
  23.       
  24.     override func viewDidLoad() {  
  25.         super.viewDidLoad()  
  26.   
  27.         webView=UIWebView()  
  28.         webView!.frame=self.view.frame  
  29.         webView!.backgroundColor=UIColor.grayColor()  
  30.         self.view.addSubview(webView)  
  31.           
  32.         loadDataSource()  
  33.   
  34.   
  35.         // Do any additional setup after loading the view.  
  36.     }  
  37.   
  38.     override func didReceiveMemoryWarning() {  
  39.         super.didReceiveMemoryWarning()  
  40.         // Dispose of any resources that can be recreated.  
  41.     }  
  42.       
  43.   
  44.     /* 
  45.     // #pragma mark - Navigation 
  46.  
  47.     // In a storyboard-based application, you will often want to do a little preparation before navigation 
  48.     override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) { 
  49.         // Get the new view controller using [segue destinationViewController]. 
  50.         // Pass the selected object to the new view controller. 
  51.     } 
  52.     */  
  53.   
  54. }  

6.XHNewsItem.swift

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. //  
  2. //  XHNewsItem.swift  
  3. //  UITableViewControllerDemo  
  4. //  
  5. //  Created by 赵超 on 14-6-24.  
  6. //  Copyright (c) 2014年 赵超. All rights reserved.  
  7. //  
  8.   
  9. import Foundation  
  10.   
  11. class XHNewsItem {  
  12.     var newsTitle = NSString()  
  13.     var newsThumb = NSString()  
  14.     var newsID = NSString()  
  15. }  
内容概要:本文档为《400_IB Specification Vol 2-Release-2.0-Final-2025-07-31.pdf》,主要描述了InfiniBand架构2.0版本的物理层规范。文档详细规定了链路初始化、配置与训练流程,包括但不限于传输序列(TS1、TS2、TS3)、链路去偏斜、波特率、前向纠错(FEC)支持、链路速度协商及扩展速度选项等。此外,还介绍了链路状态机的不同状态(如禁用、轮询、配置等),以及各状态下应遵循的规则和命令。针对不同数据速率(从SDR到XDR)的链路格式化规则也有详细说明,确保数据包格式和控制符号在多条物理通道上的一致性和正确性。文档还涵盖了链路性能监控和错误检机制。 适用人群:适用于从事网络硬件设计、开发及维护的技术人员,尤其是那些需要深入了解InfiniBand物理层细节的专业人士。 使用场景及目标:① 设计和实现支持多种数据速率和编码方式的InfiniBand设备;② 开发链路初始化和训练算法,确保链路两端设备能够正确配置并优化通信质量;③ 实现链路性能监控和错误检,提高系统的可靠性和稳定性。 其他说明:本文档属于InfiniBand贸易协会所有,为专有信息,仅供内部参考和技术交流使用。文档内容详尽,对于理解和实施InfiniBand接口具有重要指导意义。读者应结合相关背景资料进行学习,以确保正确理解和应用规范中的各项技术要求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值