这个App是用来读取 Official Google Blog 的内容,然后显示出来。

用了新建工程时用了 Master-Detail Application 这个模板。用了Core Data用来存储内容,不过每次启动App还是会删除内容,然后重新下载最新的20条。所以如果没有网络的时候打开不显示内容。

在原工程的基础上,我在Core Data中增加了date这项,为了排列时按照时间排列。获取的内容中有published和updated两个时间,用published好一些。这里只简单的转了String而不是Date类型。

//
// MasterViewController.swift
// Blog Reader
//
// Created by zcdll on 16/1/24.
// Copyright © 2016年 ZC. All rights reserved.
// import UIKit
import CoreData class MasterViewController: UITableViewController, NSFetchedResultsControllerDelegate { var detailViewController: DetailViewController? = nil
var managedObjectContext: NSManagedObjectContext? = nil override func viewDidLoad() {
super.viewDidLoad() let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let context: NSManagedObjectContext = appDel.managedObjectContext let url = NSURL(string: "https://www.googleapis.com/blogger/v3/blogs/10861780/posts?key=AIzaSyCxL3Iltcd-oLc-dFUtdDG9TTuJGWilsYw")! let session = NSURLSession.sharedSession() let task = session.dataTaskWithURL(url) { (data, response, error) -> Void in if error != nil { print(error) } else { if let data = data { //print(NSString(data: data, encoding: NSUTF8StringEncoding)) do { let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary if jsonResult.count > 0 { if let items = jsonResult["items"] as? NSArray { let request = NSFetchRequest(entityName: "BlogItems") request.returnsObjectsAsFaults = false do { let results = try context.executeFetchRequest(request) if results.count > 0 { for result in results { context.deleteObject(result as! NSManagedObject) do { try context.save() } catch {} } } } catch { print("Context fetched failed") } for item in items { if let title = item["title"] as? String { if let content = item["content"] as? String { if let date = item["published"] as? String { let updatedDate = date.componentsSeparatedByString("-08:00")[0] print(updatedDate) //print(title)
//print(content) let newPost: NSManagedObject = NSEntityDescription.insertNewObjectForEntityForName("BlogItems", inManagedObjectContext: context) newPost.setValue(title, forKey: "title")
newPost.setValue(content, forKey: "content")
newPost.setValue(updatedDate, forKey: "date") } } } //print(items)
} } } } catch {} } } } task.resume() // Do any additional setup after loading the view, typically from a nib.
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
}
} override func viewWillAppear(animated: Bool) {
self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed
super.viewWillAppear(animated)
} override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
} // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let object = self.fetchedResultsController.objectAtIndexPath(indexPath)
let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
controller.detailItem = object
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
} // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
} override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionInfo = self.fetchedResultsController.sections![section]
return sectionInfo.numberOfObjects
} override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
self.configureCell(cell, atIndexPath: indexPath)
return cell
} override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
} override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
let context = self.fetchedResultsController.managedObjectContext
context.deleteObject(self.fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject) do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
//print("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
} func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) {
let object = self.fetchedResultsController.objectAtIndexPath(indexPath)
cell.textLabel!.text = object.valueForKey("title")!.description
} // MARK: - Fetched results controller var fetchedResultsController: NSFetchedResultsController {
if _fetchedResultsController != nil {
return _fetchedResultsController!
} let fetchRequest = NSFetchRequest()
// Edit the entity name as appropriate.
let entity = NSEntityDescription.entityForName("BlogItems", inManagedObjectContext: self.managedObjectContext!)
fetchRequest.entity = entity // Set the batch size to a suitable number.
fetchRequest.fetchBatchSize = 20 // Edit the sort key as appropriate.
let sortDescriptor = NSSortDescriptor(key: "date", ascending: false) fetchRequest.sortDescriptors = [sortDescriptor] // Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: nil, cacheName: "Master")
aFetchedResultsController.delegate = self
_fetchedResultsController = aFetchedResultsController do {
try _fetchedResultsController!.performFetch()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
//print("Unresolved error \(error), \(error.userInfo)")
abort()
} return _fetchedResultsController!
}
var _fetchedResultsController: NSFetchedResultsController? = nil func controllerWillChangeContent(controller: NSFetchedResultsController) {
self.tableView.beginUpdates()
} func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
switch type {
case .Insert:
self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
case .Delete:
self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
default:
return
}
} func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch type {
case .Insert:
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
case .Delete:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
case .Update:
self.configureCell(tableView.cellForRowAtIndexPath(indexPath!)!, atIndexPath: indexPath!)
case .Move:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
}
} func controllerDidChangeContent(controller: NSFetchedResultsController) {
self.tableView.endUpdates()
} /*
// Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed. func controllerDidChangeContent(controller: NSFetchedResultsController) {
// In the simplest, most efficient, case, reload the table view.
self.tableView.reloadData()
}
*/ }
//
// DetailViewController.swift
// Blog Reader
//
// Created by zcdll on 16/1/24.
// Copyright © 2016年 ZC. All rights reserved.
// import UIKit class DetailViewController: UIViewController { @IBOutlet weak var webview: UIWebView! var detailItem: AnyObject? {
didSet {
// Update the view.
self.configureView()
}
} func configureView() {
// Update the user interface for the detail item.
if let detail = self.detailItem {
if let postWebView = self.webview { postWebView.loadHTMLString(detail.valueForKey("content")!.description, baseURL: NSURL(string: "https://googleblog.blogspot.com/")) }
}
} override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.configureView()
} override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
} }

工程:27_Blog Reader

27_Blog Reader的更多相关文章

  1. InputStream、InputStreamReader和Reader的关系

    InputStream:得到的是字节输入流,InputStream.read("filename")之后,得到字节流 Reader:读取的是字符流 InputStreamReade ...

  2. Distribution1:Distribution Reader

    在transactional replication中,在publication中执行了一个更新,例如:update table set col=? Where ?,如果table中含有大量的数据行, ...

  3. Reader与InputStream两个类中的read()的区别

    InputStream类的read()方法是从流里面取出一个字节,他的函数原型是 int read(); ,Reader类的read()方法则是从流里面取出一个字符(一个char),他的函数原型也是  ...

  4. Ubuntu 12.04安装Adobe Reader

    原本从Adobe 官方网站下载了 Adobe Reader, 是个rpm包,先用agt-get 装了rpm(sudo apt-get install rpm), 一安装(rpm -ivh AdobeR ...

  5. Adobe Reader/Acrobat修改页面底色为豆沙绿

    Adobe Acrobat_Pro_8修改PDF页面底色为豆沙绿保护视力(同样适用于Adobe Reader) http://jingyan.baidu.com/article/9989c746189 ...

  6. multithreading - Reader/Writer Locks in C++

    You Only Need To Note This: only 1 single thread can acquire an upgrade_lock at one time. others are ...

  7. AttributeError: '_csv.reader' object has no attribute 'next'

    我在使用pyhon3.4运行以下代码时报错:AttributeError: '_csv.reader' object has no attribute 'next' import csv import ...

  8. SWF READER 破解日志。

    网上传闻swf reader是破解最厉害的神器,可以内存抓取+doSWF反编译.所以去官网下了一个: SWF_Reader_2.3 不出所料,demo版本没有反编译的功能.网上搜到一个哥们尝试了下: ...

  9. Scalaz(16)- Monad:依赖注入-Dependency Injection By Reader Monad

    在上一篇讨论里我们简单的介绍了一下Cake Pattern和Reader Monad是如何实现依赖注入的.主要还是从方法上示范了如何用Cake Pattern和Reader在编程过程中解析依赖和注入依 ...

随机推荐

  1. [转] C#.Net Socket网络通讯编程总结

    1.理解socket1).Socket接口是TCP/IP网络的应用程序接口(API).Socket接口定义了许多函数和例程,程序员可以用它们来开发TCP/IP网络应用程序.Socket可以看成是网络通 ...

  2. org.openqa.selenium.SessionNotCreatedException: A new session could not be created.

    解决方案 1. 重新插拔手机. 2. 检查appium端口是否被占用,如是,杀掉占用了改端口的进程,然后重启appium. 3.

  3. JavaScript之面向对象学习四原型对象的动态性

    1.由于在原型中查找值的过程是一次搜索,因此我们对原型对象所做的任何修改都能够立即从实例上反映出来---即便是先创建了实例后修改原型也是如此.代码如下: function Person(){ } va ...

  4. SSM搭配中的web.xml的配置信息

    最近一段时间在自己学着搭建SSM框架的项目,其实这个项目自由自己不断尝试,不断失败,才能印象更深刻. 下面就说一下在项目中的web.xml的相关配置信息: <?xml version=" ...

  5. 眼花缭乱的UI,蓝牙位于何方

    我们在前面已经分析了Android启动中涉及蓝牙的各个方面,今天我们着重来看看,在蓝牙打开之前,我们能看到的蓝牙UI有哪些,这些UI又是如何实现的. 1,settings中UI的分析 首先,最常见的也 ...

  6. nodejs事件机制

    var EventEmitter = function() { this.evts = {}; }; EventEmitter.prototype = { constructor: EventEmit ...

  7. linux 定时执行任务

    测试可以了,做个笔记 系统是centos 6.3 1,直接命令 crontab -e 编辑文件,里面写时间和你想要执行的命令. 例子 */1 * * * * sh /home/guanliyang/t ...

  8. 依赖注入(DI)和控制反转(IOC)

    依赖注入(DI)和控制反转(IOC) 0X1 什么是依赖注入 依赖注入(Dependency Injection),是这样一个过程:某客户类只依赖于服务类的一个接口,而不依赖于具体服务类,所以客户类只 ...

  9. MYSQL group_concat() 函数

    看来看一下表中的数据 select * from t; 下一步来看一下group_concat函数的用法 select ID,group_concat(Name) from t group by ID ...

  10. js正则验证"汉字"

    var nickname = value; var regex = new RegExp("^([\u4E00-\uFA29]|[\uE7C7-\uE7F3]|[a-zA-Z0-9_]){1 ...