[Swift A] - 实战-豆瓣电台总结

最近在学Swift,也是刚刚开始。这里对自己最近所学做个简单的总结:视频和代码都在下面

http://pan.baidu.com/s/1sjHd5qX

1.String和NSString的不同

1 Swift的String类型是值类型。如果你创建了一个新的字符串值,那么当其进行常量、变量赋值操作或在函数/方法中传递时,会进行值拷贝。
2 
3 在不同的情况下,都会对已有字符串值创建新的副本,并对该新副本进行传递或赋值。
4 
5 这和OC中的NSString不同,当您在OC创建了一个NSString实例,并将其传递给一个函数/方法,或者赋给一个变量,您永远都是传递或赋值同一个NSString实例的一个引用。
6 
7 除非您特别要求其进行值拷贝,否则字符串不会进行赋值新副本操作。

2.异步获取数据

1  NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler:{(response:NSURLResponse!, data:NSData!, error:NSError!)->Void in
2             var jsonResult:NSDictionary = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
3             //why just miss an excalmatory mark, the code isn't compile
4             //self.delegate?.didRecieveResults(jsonResult)
5         })

3.UI焦点的易操作

在UI的界面种可以直接在View上点击鼠标右键,并拖入相应的Controller的代码中,且生成@IBOutlet和@IBAction。代码都不用手写了,很方便。

4.视图之间的跳转,传参,回跳

1 //页面跳转时,将数据传过去
2     override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
3         var channelC:ChannelController = segue.destinationViewController as ChannelController
4         channelC.delegate = self// What TODO
5         channelC.channelData = self.channelData
6     }
1 //点击事件
2     func tableView(tableView:UITableView!, didSelectRowAtIndexPath indexPath:NSIndexPath!) {
3         //what is do this
4         var rowData:NSDictionary = self.channelData[indexPath.row] as NSDictionary
5         let channelId:AnyObject = rowData["channel_id"] as AnyObject
6         let channel:String = "channel=\(channelId)"
7         delegate?.onChangeChannel(channel)
8         self.dismissViewControllerAnimated(true, completion: nil)
9     }

5.MP3在线播放

 1 //定义一个播放器
 2     var audioPlayer:MPMoviePlayerController = MPMoviePlayerController()
 3 
 4 //设置音乐
 5     func onSetAudio(url:String) {
 6         timer?.invalidate()
 7         timeLabel.text = "00:00"
 8         
 9         self.audioPlayer.stop()
10         self.audioPlayer.contentURL = NSURL(string:url)
11         self.audioPlayer.play()
12         timer = NSTimer.scheduledTimerWithTimeInterval(0.4 , target : self, selector : "onUpdate", userInfo: nil, repeats :true)
13         
14         playBtn.removeGestureRecognizer(tap)
15         logo.addGestureRecognizer(tap)
16         playBtn.hidden = true
17     }

6.TableView列表Item的出现动画

1 func tableView(tableView: UITableView!, willDisplayCell cell: UITableViewCell!, forRowAtIndexPath indexPath: NSIndexPath!) {
2         cell.layer.transform = CATransform3DMakeScale(0.1, 0.1, 1)
3         UIView.animateWithDuration(0.25, animations:{cell.layer.transform=CATransform3DMakeScale(1, 1, 1)})
4     }

 7.UI控件汇总

 1 UIViewController
 2 UITableViewDataSource
 3 UITableViewDelegate
 4 UIImageView
 5 UILabel
 6 UIButton
 7 UIProgressView
 8 UITableView
 9 UITapGestureRecognizer
10 UIImage
11 MediaPlayer

 8.最后把代码贴出来以供学习

  1 import UIKit
  2 import MediaPlayer
  3 import QuartzCore
  4 
  5 class ViewController: UIViewController ,UITableViewDataSource, UITableViewDelegate, HttpProtocol, ChannelProtocol{
  6     
  7     @IBOutlet var logo: UIImageView
  8     @IBOutlet var timeLabel: UILabel
  9     @IBOutlet var buttonNext: UIButton
 10     @IBOutlet var progressBar: UIProgressView
 11     @IBOutlet var itemLayout: UITableView
 12     //开始点击事件
 13     @IBOutlet var tap: UITapGestureRecognizer = nil //这里必须为空,否则报错
 14     
 15     @IBOutlet var playBtn: UIImageView
 16     
 17 
 18     //to cache the picture of songs
 19     var imageCache = Dictionary<String, UIImage>()
 20     
 21     var eHttp:HttpController = HttpController()
 22     //主界面
 23     var tableData:NSArray =  NSArray()
 24     //频道列表
 25     var channelData:NSArray = NSArray()
 26     //定义一个播放器
 27     var audioPlayer:MPMoviePlayerController = MPMoviePlayerController()
 28     
 29     var timer:NSTimer?
 30     
 31     @IBAction func onTap(sender: UITapGestureRecognizer) {
 32         if sender.view == playBtn {
 33             playBtn.hidden = true
 34             audioPlayer.play()
 35             playBtn.removeGestureRecognizer(tap)
 36             logo.addGestureRecognizer(tap)
 37         } else if sender.view == logo{
 38             playBtn.hidden = false
 39             audioPlayer.pause()
 40             playBtn.addGestureRecognizer(tap)
 41             logo.removeGestureRecognizer(tap)
 42         }
 43     }
 44     
 45     override func viewDidLoad() {
 46         super.viewDidLoad()
 47         //视图加载完之后,获取数据
 48         eHttp.delegate = self
 49         eHttp.onSearch("http://www.douban.com/j/app/radio/channels")
 50         eHttp.onSearch("http://douban.fm/j/mine/playlist?channel=0")
 51         progressBar.progress = 0.0
 52         logo.addGestureRecognizer(tap)
 53         
 54     }
 55 
 56     override func didReceiveMemoryWarning() {
 57         super.didReceiveMemoryWarning()
 58         // Dispose of any resources that can be recreated.
 59     }
 60     
 61     
 62     func tableView(tableView: UITableView!, willDisplayCell cell: UITableViewCell!, forRowAtIndexPath indexPath: NSIndexPath!) {
 63         cell.layer.transform = CATransform3DMakeScale(0.1, 0.1, 1)
 64         UIView.animateWithDuration(0.25, animations:{cell.layer.transform=CATransform3DMakeScale(1, 1, 1)})
 65     }
 66     
 67     
 68     
 69     //TODO
 70     override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
 71         var channelC:ChannelController = segue.destinationViewController as ChannelController
 72         channelC.delegate = self// What TODO
 73         channelC.channelData = self.channelData
 74     }
 75     
 76     func onChangeChannel(channelId:String) {
 77         let url:String = "http://douban.fm/j/mine/playlist?\(channelId)"
 78         eHttp.onSearch(url)
 79     }
 80     
 81     func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
 82         return tableData.count
 83     }
 84     //列表展示
 85     func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
 86         let cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "songs")
 87         let rowData:NSDictionary = self.tableData[indexPath.row] as NSDictionary
 88         cell.text = rowData["title"] as String
 89         cell.detailTextLabel.text = rowData["artist"] as String
 90         //默认图片
 91         cell.image = UIImage(named:"detail.jpg")
 92         //缩略图
 93         let url = rowData["picture"] as String
 94         let image = self.imageCache[url] as? UIImage
 95         if !image?{// why do this
 96             let imgURL:NSURL = NSURL(string:url)
 97             let request:NSURLRequest = NSURLRequest(URL:imgURL)
 98             NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response:NSURLResponse!, data:NSData!, error:NSError!) -> Void in
 99                 let img = UIImage(data:data)
100                 cell.image = img
101                 //缓存图片
102                 self.imageCache[url] = img
103                 })
104         } else {// if no this else, the item will be default image
105             cell.image = image
106         }
107         
108         return cell
109     }
110     
111     func didRecieveResults(results:NSDictionary) {
112         //println(results);
113         if(results["channels"]) {
114             self.channelData = results["channels"] as NSArray
115             //self.itemLayout.reloadData()
116         } else if(results["song"]) {
117             self.tableData = results["song"] as NSArray
118             self.itemLayout.reloadData()
119             
120             let firDict:NSDictionary = self.tableData[0] as NSDictionary
121             let audioUrl:String = firDict["url"] as String
122             onSetAudio(audioUrl)
123             let imgUrl:String = firDict["picture"] as String
124             onSetImage(imgUrl)
125         }
126         
127     }
128     
129     
130     
131     func tableView(tableView:UITableView!, didSelectRowAtIndexPath indexPath:NSIndexPath!) {
132         let rowData:NSDictionary = self.tableData[indexPath.row] as NSDictionary
133         let audioUrl:String = rowData["url"] as String
134         onSetAudio(audioUrl)
135         let imgUrl:String = rowData["picture"] as String
136         onSetImage(imgUrl)
137     }
138     
139     
140     //设置音乐
141     func onSetAudio(url:String) {
142         timer?.invalidate()
143         timeLabel.text = "00:00"
144         
145         self.audioPlayer.stop()
146         self.audioPlayer.contentURL = NSURL(string:url)
147         self.audioPlayer.play()
148         timer = NSTimer.scheduledTimerWithTimeInterval(0.4 , target : self, selector : "onUpdate", userInfo: nil, repeats :true)
149         
150         playBtn.removeGestureRecognizer(tap)
151         logo.addGestureRecognizer(tap)
152         playBtn.hidden = true
153     }
154     
155     func onUpdate() {
156         let c = audioPlayer.currentPlaybackTime
157         if c > 0.0 {
158             let t = audioPlayer.duration
159             let p:CFloat=CFloat(c/t)
160             
161             progressBar.setProgress(p, animated: true)
162             
163             let allSecond:Int = Int(c)
164             let s:Int = allSecond%60
165             let m:Int = Int(allSecond/60)
166             var time:String = ""
167             if(m < 10) {
168                 time = "0\(m)"
169             } else {
170                 time = "\(m)"
171             }
172             if(s < 10) {
173                 time += ":0\(s)"
174             } else {
175                 time += ":\(s)"
176             }
177             timeLabel.text = time
178             
179         }
180     }
181     
182     
183     //设置图片
184     func onSetImage(url:String) {
185         let image = self.imageCache[url] as? UIImage
186         if !image?{// why do this
187             let imgURL:NSURL = NSURL(string:url)
188             let request:NSURLRequest = NSURLRequest(URL:imgURL)
189             NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response:NSURLResponse!, data:NSData!, error:NSError!) -> Void in
190                 let img = UIImage(data:data)
191                 self.logo.image = img
192                 //缓存图片
193                 self.imageCache[url] = img
194                 })
195         } else {// if no this else, the item will be default image
196             self.logo.image = image
197         }
198         
199     }
200 
201 }

 

 1 import UIKit
 2 
 3 
 4 protocol HttpProtocol {
 5     func didRecieveResults(results:NSDictionary)
 6 }
 7 
 8 class HttpController : NSObject {
 9     
10     var delegate:HttpProtocol?
11     
12     func onSearch(url:String) {
13         var nsUrl:NSURL = NSURL(string:url)
14         var request:NSURLRequest = NSURLRequest(URL:nsUrl)
15         //1.Closure Expression Syntax
16         //2.异步获取数据
17         
18         NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler:{(response:NSURLResponse!, data:NSData!, error:NSError!)->Void in
19             var jsonResult:NSDictionary = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
20             //why just miss an excalmatory mark, the code isn't compile
21             //self.delegate?.didRecieveResults(jsonResult)
22         })
23     }
24 }

 

 1 import UIKit
 2 import QuartzCore
 3 
 4 protocol ChannelProtocol {
 5     func onChangeChannel(channelId:String)// why is String, is not NSString
 6 }
 7 
 8 class ChannelController: UIViewController, UITableViewDataSource, UITableViewDelegate {
 9 
10     @IBOutlet var listLayout: UITableView
11     
12     var channelData:NSArray = NSArray()
13     var delegate:ChannelProtocol?
14     
15     override func viewDidLoad() {
16         super.viewDidLoad()
17         // Do any additional setup after loading the view, typically from a nib.
18     }
19     
20     override func didReceiveMemoryWarning() {
21         super.didReceiveMemoryWarning()
22         // Dispose of any resources that can be recreated.
23     }
24     
25     
26    func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
27         return 10
28     }
29     
30     func tableView(tableView: UITableView!, willDisplayCell cell: UITableViewCell!, forRowAtIndexPath indexPath: NSIndexPath!) {
31         cell.layer.transform = CATransform3DMakeScale(0.1, 0.1, 1)
32         UIView.animateWithDuration(0.25, animations:{cell.layer.transform=CATransform3DMakeScale(1, 1, 1)})
33     }
34     
35     func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
36         let cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "channel")
37         let rowData:NSDictionary = self.channelData[indexPath.row] as NSDictionary
38         cell.text = rowData["name"] as String
39         return cell
40     }
41     
42     func tableView(tableView:UITableView!, didSelectRowAtIndexPath indexPath:NSIndexPath!) {
43         //what is do this
44         var rowData:NSDictionary = self.channelData[indexPath.row] as NSDictionary
45         let channelId:AnyObject = rowData["channel_id"] as AnyObject
46         let channel:String = "channel=\(channelId)"
47         delegate?.onChangeChannel(channel)
48         self.dismissViewControllerAnimated(true, completion: nil)
49     }
50     
51     
52 }

 

posted on 2014-09-18 20:34  洛易  阅读(527)  评论(0编辑  收藏  举报