iOS开发——实战篇Swift篇&UItableView结合网络请求,多线程,数据解析,MVC实战
UItableView结合网络请求,多线程,数据解析,MVC实战
学了这么久的swift都没有做过什么东西,今天就以自己的一个小小的联系,讲一下,怎么使用swift在实战中应用MVC,并且结合后面的高级知识:网络请求,JSON数据解析一起应用到一个项目中来。
好了,废话不多说,我们直接开始吧。
首先看看最终的效果:

是不是很简单,就是个UItableView显示一些简单的数据,如果你真的觉得太简单了,那么请绕道,寻找更深入东西,但或者没有你想的那么简单,这不仅仅是一个tableView,为什么呢?下面我就给大家详细介绍一下。
一:首先,既然说到MVC,我们肯定要先从模型开始,新建一个模型类。
因为我们只是现实一张图片和一行文件,所以模型中非常简单,两行代码:
import UIKit
class DataModel: NSObject
{
// 文字
var title : String = ""
// 图片
var photh : String = ""
}
二:然后创建一个自定义Cell,并且和我们前面一样实现相应的方法,并且在里面实现相应的代码:
1:创建两个控件对应的属性:
// 文字
var titleLable : UILabel?
// 图片
var photoImageView : UIImageView?
2:实现init方法,并且在里面调用loadView方法来实现控件的初始化:
override init(style: UITableViewCellStyle, reuseIdentifier: String!)
{
super.init(style: style, reuseIdentifier: reuseIdentifier)
loadView()
}
func loadView()
{
titleLable = UILabel(frame: CGRectMake(, , , ))
titleLable!.textAlignment = NSTextAlignment.Left
titleLable!.numberOfLines =
self.addSubview(titleLable!)
photoImageView = UIImageView(frame: CGRectMake(, , , ))
self.addSubview(photoImageView!)
}
3:然后通过模型来加载数据,这里涉及到了网络请求的知识,请多留意蓝色部分代码:
func loadData(item:DataModel)
{
titleLable?.text = item.title
// 图片转换
var thumbQueue = NSOperationQueue()
var urlString = (item.photh as String)
var url = NSURL(string: urlString)!
let request = NSURLRequest(URL: url)
13 /**
14 <#(NSURLResponse!, NSData!, NSError!) -> Void##(NSURLResponse!, NSData!, NSError!) -> Void#>
15 自己命名
16 */
17
18 //NSURLConnection.sendAsynchronousRequest(request, queue: thumbQueue, completionHandler: )
19 // <#(NSURLResponse!, NSData!, NSError!) -> Void##(NSURLResponse!, NSData!, NSError!) -> Void#>
20
21
22
23 // NSURLConnection.sendAsynchronousRequest(request, queue: thumbQueue) { (response, data, error) -> Void in
24 // let image = UIImage.init(data :data)
25 // dispatch_async(dispatch_get_main_queue(), { () -> Void in
26 // self.photoImageView!.image = image
27 // })
28 //
29 // }
30
31
32 NSURLConnection.sendAsynchronousRequest(request, queue: thumbQueue, completionHandler: { response, data, error in
33 if (error != nil) {
34 println(error)
35
36 } else {
37 let image = UIImage.init(data :data)
38 dispatch_async(dispatch_get_main_queue(), { () -> Void in
39 self.photoImageView!.image = image
40 })
41
42 }
43 })
photoImageView?.layer.masksToBounds = true
photoImageView?.layer.cornerRadius =
photoImageView?.image = UIImage(named: item.photh)
}
3:下面是系统自动实现的方法;
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
三:然后就是控制器里面了
1:定义相应的属性
- 1:定义一个UItableView
- 2:定义一个可变数组
- 3:定义一个队列(这里涉及到了多线程)
- 4:定义一个网络请求的api链接
- 5:定义一个刷新控件
var tableView : UITableView!
var dataArray : NSMutableArray = []
var thumbQueue = NSOperationQueue()
let hackerNewsApiUrl = "http://qingbin.sinaapp.com/api/lists?ntype=%E5%9B%BE%E7%89%87&pageNo=1&pagePer=10&list.htm"
let refreshControl = UIRefreshControl()
2:ViewDidLoad中调用相应的方法
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.title = "自定义Cell-下拉刷新"
// 创建TableView
createTableView()
// 下载数据
loadData()
}
3:创建TableView方法的实现
func createTableView()
{
// TableView
self.tableView = UITableView(frame: CGRectMake(, , view.frame.size.width, view.frame.size.height))
self.tableView.dataSource = self
self.tableView.delegate = self
view.addSubview(self.tableView)
refreshControl.attributedTitle = NSAttributedString(string: "下拉刷新")
refreshControl.addTarget(self, action: "loadDataSource", forControlEvents: UIControlEvents.ValueChanged)
self.tableView.addSubview(refreshControl)
}
4:加载数据
- 1:通过URL发送请求
- 2:实现一步请求的发送
- 3:使用GCD多多线程实现界面的现实(在主线程中)
- 4:解析加载的json数据(这里可以使用框架SwiftyJSON)
- 5:使用刷新控件实现更好的用户交互效果
// MARK: - 加载数据
func loadDataSource()
{
var loadURL = NSURL(string: hackerNewsApiUrl)!
var request = NSURLRequest(URL: loadURL)
// 线程
var loadDataSourceQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request, queue: loadDataSourceQueue, completionHandler: { response, data, error in
if (error != nil)
{
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
dispatch_async(dispatch_get_main_queue(),
{
self.dataArray = NSMutableArray()
// 遍历数组
for dict in newsDataSource
{
var item = DataModel()
item.title = dict["title"] as! String
item.photh = dict["thumb"] as! String
self.dataArray.addObject(item)
println(dict["title"])
println(dict)
}
// 刷新时间
var sendDate = NSDate()
var dateformatter = NSDateFormatter()
dateformatter.setLocalizedDateFormatFromTemplate("yyyy年MM月dd日 hh:mm:ss")
var loactionTime = String()
loactionTime = dateformatter.stringFromDate(sendDate)
var title = NSAttributedString(string: "上次刷新时间\(loactionTime)")
self.refreshControl.attributedTitle = title
// 刷新结束
self.refreshControl.endRefreshing()
// 刷新Cell
self.tableView.reloadData()
})
}
})
}
func loadData()
{
}
5:实现UITableView数据源和代理方法,设置对应的属性来显示数据到界面上:
// MARK:- UITableViewDataSource
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
println(dataArray.count)
return self.dataArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
println(dataArray)
self.tableView.registerClass(ImageCell.self, forCellReuseIdentifier: "cell")
var cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! ImageCell
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
//cell = ImageCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell")
var item = DataModel()
item = self.dataArray[indexPath.row] as! DataModel
{
cell.loadData(item)
}
return cell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
println("row = %d",indexPath.row)
var detailVC = DetailViewController()
self.navigationController?.pushViewController(detailVC, animated: true)
}
当我们点击对应的行,就会跳到对应行的详细界面:
加载这一行中对应的数据
var detailID = NSInteger()
var detailURL = "http://qingbin.sinaapp.com/api/html/108035.html"
var webView = UIWebView()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.backgroundColor = UIColor.whiteColor()
self.title = "Detail"
self.webView.frame = CGRectMake(, , view.frame.size.width, view.frame.size.height)
self.webView.scalesPageToFit = true
self.webView.delegate = self
view.addSubview(self.webView)
loadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loadData()
{
var url = NSURL(string: self.detailURL)
var urlRequest = NSURLRequest(URL: url!)
webView.loadRequest(urlRequest)
}
// MARK: - UIWebViewDelegate
// 加载失败
func webView(webView: UIWebView, didFailLoadWithError error: NSError)
{
println(error)
}
// 加载完成
func webViewDidFinishLoad(webView: UIWebView)
{
println("完成加载\(webView)")
}
// 开始加载
func webViewDidStartLoad(webView: UIWebView)
{
println("开始加载\(webView)")
}
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool
{
return true
}
点击之后显示的节目如下:

iOS开发——实战篇Swift篇&UItableView结合网络请求,多线程,数据解析,MVC实战的更多相关文章
- iOS开发——技术精华Swift篇&Swift 2.0和Objective-C2.0混编之第三方框架的使用
swift 语言是苹果公司在2014年的WWDC大会上发布的全新的编程语言.Swift语言继承了C语言以及Objective-C的特性,且克服了C语言的兼容性问题.Swift语言采用安全编程模式,且引 ...
- iOS开发——新特性Swift篇&Swift 2.0 异常处理
Swift 2.0 异常处理 WWDC 2015 宣布了新的 Swift 2.0. 这次重大更新给 Swift 提供了新的异常处理方法.这篇文章会主要围绕这个方面进行讨论. 如何建造异常类型? 在 i ...
- iOS网络请求之数据解析
JSON解析 IOS中Json解析的四种方法 NSURLConnection-网络请求浅析 IOS开发:官方自带的JSON使用 XML 解析 GDataXMLNode应用 IOS学习:常用第三方库(G ...
- ios开发——实用技术总结Swift篇&swift常用开发技术总结
swift常用开发技术总结 懒加载:属性,数组(字典),控件... 数组(懒加载): lazy var shops:Array<Dictionary<String, String>& ...
- iOS开发——图形编程Swift篇&CAShapeLayer实现圆形图片加载动画
CAShapeLayer实现圆形图片加载动画 几个星期之前,Michael Villar在Motion试验中创建一个非常有趣的加载动画. 下面的GIF图片展示这个加载动画,它将一个圆形进度指示器和圆形 ...
- iOS开发零基础--Swift篇 元组
元组的介绍 元组是Swift中特有的,OC中并没有相关类型 它是什么呢? 它是一种数据结构,在数学中应用广泛 类似于数组或者字典 可以用于定义一组数据 组成元组类型的数据可以称为“元素” 元组的定义 ...
- iOS开发零基础--Swift篇 循环
循环的介绍 在开发中经常会需要循环 常见的循环有:for/while/do while. 这里我们只介绍for/while,因为for/while最常见 for循环的写法 最常规写法 // 传统写法 ...
- iOS开发零基础--Swift篇:逻辑分支
一. 分支的介绍 分支即if/switch/三目运算符等判断语句 通过分支语句可以控制程序的执行流程 二. if分支语句 和OC中if语句有一定的区别 判断句可以不加() 在Swift的判断句中必须有 ...
- iOS开发零基础--Swift篇:Swift中数据类型
Swift类型的介绍 Swift中的数据类型也有:整型/浮点型/对象类型/结构体类型等等 先了解整型和浮点型 整型 有符号 Int8 : 有符号8位整型 Int16 : 有符号16位整型 Int32 ...
- ios开发——实用技术篇Swift篇&播放MP3
播放MP3 // MARK: - 播放MP3 /*----- mp3 ------*/ //定时器- func updateTime() { //获取音频播放器播放的进度,单位秒 var cuTime ...
随机推荐
- Epic - Coin Change
Something cost $10.25 and the customer pays with a $20 bill, the program will print out the most eff ...
- WebApi参数传递
c# webapi的参数传递方式:1.查询字符串(query string):2.内容主体(content body) 当然也有cookie或url部分或头部信息(header)等其它传方式,这里仅讨 ...
- Android Capture Android System Audio
项目需要获取播放视频的实时音量值,最简捷的方法是监听音频输出端,取得音频输出流,再进行转换. 调查时,首先找到这篇博客: http://blog.csdn.net/jinzhuojun/article ...
- PYTHON压平嵌套列表
list 是 Python 中使用最频繁的数据类型, 标准库里面有丰富的函数可以使用.不过,如果把多维列表转换成一维列表(不知道这种需求多不多),还真不容易找到好用的函数,要知道Ruby.Mathem ...
- 【CLR】奇妙的String
- 一.背景 1. 以下代码的HashCode是否相同,它们是否是同个对象: var A = "ab" + "c"; var B = "abc&quo ...
- JDBC连接Oracle数据库的问题
场景:最近做一个java web项目,使用jdbc连接Oracle数据库,遇到了两个问题. 问题1:jdbc连接不上Ubuntu Oracle服务器? 后来发现这个问题的原因是由于连接字符串写错了,修 ...
- 在Spring MVC中使用注解的方式校验RequestParams
概述 Spring MVC支持Bean Validation,通过这个验证技术,可以通过注解方式,很方便的对输入参数进行验证,之前使用的校验方式,都是基于Bean对象的,但是在@RequestPa ...
- leetcode@ [146] LRU Cache (TreeMap)
https://leetcode.com/problems/lru-cache/ Design and implement a data structure for Least Recently Us ...
- 阿里云存储OSS之九大使用技巧
http://www.biphp.com/cloud-computing/%E9%98%BF%E9%87%8C%E4%BA%91%E5%AD%98%E5%82%A8oss%E4%B9%8B%E4%B9 ...
- xml velocity模板
. <?xml version="1.0" encoding="GBK"?> <PACKET type="REQUEST" ...