Swift實戰-QQ在線音樂(AppleWatch版)

1.打開項目QQMusic,而後點菜單:「File-New-Target」添加appleWatch擴展項html

 

2.選擇Swift語言,把Include Notification Scene前的勾去掉 (項目暫時不須要作ios端的通知)ios

3.在 WatchKit Extension的Compile Sources 中添加QQMusic項目的須要使用的類文件swift

4.在QQMusic WatchKit Extension包的Images.xcassets裏添加資源圖片網絡

而且在QQMusic WatchKit App的Images.xcassets裏資源添加圖片app

(這兩個的區別是,WatchKit Extension的圖片是在代碼裏調用,而WatchKit App的圖片是storyboard調用)ide

5.打開Interface.storyboard進行佈局佈局


6.關聯各個控件IBOutLetspa

class InterfaceController: WKInterfaceController {

    @IBOutlet weak var iconImage: WKInterfaceImage!
    @IBOutlet weak var titleLabel: WKInterfaceLabel!
    @IBOutlet weak var lrcLabel:WKInterfaceLabel!
    @IBOutlet weak var playButton: WKInterfaceButton!
}

7.加載網絡mp3列表.net

  override func willActivate() {
        super.willActivate()
        if tableData.count==0 {
            //請求列表數據
            provider.getSongList { (results) -> () in
                let errorCode:NSInteger=results["error_code"] as NSInteger
                let result:NSDictionary=results["result"] as NSDictionary
                if (errorCode==22000) {
                    let resultData:NSArray = result["songlist"] as NSArray
                    var list=[Song]()
                    for(var index:Int=0;index<resultData.count;index++){
                        var dic:NSDictionary = resultData[index] as NSDictionary
                        var song:Song=Song()
                        song.setValuesForKeysWithDictionary(dic as NSDictionary)
                        list.append(song)
                    }
                    self.tableData=list
                    self.setCurrentSong(list[0] as Song)
                }
            }
        }
    }

說明:willActivate方法是在頁面顯示前調用。3d

8.加載當前mp3文件,和歌詞數據

 func setCurrentSong(song:Song){
      titleLabel.setText("\(song.title)-\(song.author)")
      iconImage.setImage(getImageWithUrl(song.pic_premium))
      self.audioPlayer.stop()
        isPlaying=false
      self.playButton.setBackgroundImage(UIImage(named: "player_btn_play_normal.png"))
      getCurrentMp3(song)
      getCurrentLrc(song.lrclink)
        timer?.invalidate()
        timer=NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: "updateTime", userInfo: nil, repeats: true)
    }
    
    //獲取當前mp3
    func getCurrentMp3(song:Song){
        provider.getSongMp3(song, reciveBlock: { (results) -> () in
            self.audioPlayer.contentURL=NSURL(string: results)
        })
    }
    
    //獲取歌詞
    func getCurrentLrc(lrclick:NSString){
        currentLrcData=parseLyricWithUrl(lrclick)?
    }
 //更新播放時間
    func updateTime(){
        //顯示歌詞
        if currentLrcData != nil {
            let c=audioPlayer.currentPlaybackTime
            if c>0.0{
                let all:Int=Int(c)
                // 查找比當前秒數大的第一條
                var predicate:NSPredicate = NSPredicate(format: "total < %d", all)!
                var lrcList:NSArray = currentLrcData!.filteredArrayUsingPredicate(predicate)
                if lrcList.count > 0{
                    var lrcLine:SongLrc = lrcList.lastObject as SongLrc
                    lrcLabel.setText(lrcLine.text)
                }
            }
        }
    }

 

9.播放、暫停當前歌曲

@IBAction func playSong() {
        if(isPlaying==true){
            //中止播放
            self.audioPlayer.pause()
            self.playButton.setBackgroundImage(UIImage(named: "player_btn_play_normal.png"))
            isPlaying=false
        }else{
            //開始/繼續播放
            self.audioPlayer.play()
            self.playButton.setBackgroundImage(UIImage(named: "player_btn_pause_normal.png"))
            isPlaying=true
        }
    }

10.實現上一首下一首歌曲的播放

 //上一首
    @IBAction func preSong() {
        if(currentIndex>0){
            currentIndex--
        }
        currentSong=tableData[currentIndex]
        setCurrentSong(currentSong)
    }
  
    //下一首
    @IBAction func nextSong() {
        if(currentIndex < tableData.count){
            currentIndex++
        }
        currentSong=tableData[currentIndex]
        setCurrentSong(currentSong)
    }

11.在storyBoard新建一個InterfaceController,並拖一個table控件(用於顯示全部歌曲列表),將其關聯SongListController


import Foundation
import WatchKit

class SongListController:WKInterfaceController {
    var dataSource=[Song]()
    //列表控件
    @IBOutlet weak var table: WKInterfaceTable!
    
    //接收傳過來的數據
    override func awakeWithContext(context: AnyObject?) {
        super.awakeWithContext(context)
        if let data = context as? [Song]{
           self.dataSource=data
        }
    }
    
    //顯示列表數據
    override func willActivate() {
        super.willActivate()
        table.setNumberOfRows(dataSource.count, withRowType: "SongRowType")
        for (index, song) in enumerate(dataSource) {
            if let row = table.rowControllerAtIndex(index) as? SongRowController {
                row.titleLabel.setText(song.title)
                row.subTitleLabel.setText(song.author)
            }
        }
    }
    
    //點擊某一行返回
    override func table(table: WKInterfaceTable, didSelectRowAtIndex rowIndex: Int) {
         let song = dataSource[rowIndex]
         self.dismissController()
    }
}

 

12.將table控件裏的rowcontroller關聯SongRowController.swift

import Foundation
import WatchKit

class SongRowController:NSObject {
    @IBOutlet weak var titleLabel: WKInterfaceLabel!
    @IBOutlet weak var subTitleLabel: WKInterfaceLabel!
}

13.按住control鍵,從每個controller拖到第二個,進行頁面跳轉

14.在InterfaceController.swift的contextForSegueWithIdentifier方法中設置跳轉頁面時的傳參
   //頁面使用storyBoard跳轉時傳參
    override func contextForSegueWithIdentifier(segueIdentifier: String) -> AnyObject? {
        NSLog("segueIdentifier%@", segueIdentifier)
        if segueIdentifier == "songListSegue"{
            return self.tableData
        }else{
            return nil
        }
    }

15.在SongListController.swift中的awakeWithContext方法,接收傳過來的參數

 //接收傳過來的數據
    override func awakeWithContext(context: AnyObject?) {
        super.awakeWithContext(context)
        if let data = context as? [Song]{
           self.dataSource=data
        }
    }

 

16.進行歌曲列表的數據綁定

 //顯示列表數據
    override func willActivate() {
        super.willActivate()
        table.setNumberOfRows(dataSource.count, withRowType: "SongRowType")
        for (index, song) in enumerate(dataSource) {
            if let row = table.rowControllerAtIndex(index) as? SongRowController {
                row.titleLabel.setText(song.title)
                row.subTitleLabel.setText(song.author)
            }
        }
    }

 

最終效果以下:

  

 

源碼下載地址:http://download.csdn.net/detail/fangwulongtian/8584863

轉載請註明來源:http://www.cnblogs.com/wuxian/p/4418116.html

相關文章
相關標籤/搜索