You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
cloudmusic/cloudmusic/SearchController.swift

118 lines
3.8 KiB

4 years ago
//
// SearchController.swift
// cloudmusic
//
// Created by Qihua Pan on 2020/7/3.
// Copyright © 2020 Qihua Pan. All rights reserved.
//
import UIKit
import SwiftyJSON
import CoreData
class SearchController: UIViewController {
// : Swiftmark: MARK:-
// MARK:-
let cellID = "cell"
//
@IBOutlet weak var keyword: UITextField!
//
@IBOutlet weak var musicTable: UITableView!
//
var musicList:[cloudmusic.Music]=[]
//
@IBAction func search(_ sender: UIButton) {
self.textFieldShouldReturn(keyword)
if let k=keyword{
if k.text!.count>0{
MusicRequest.search(keyword: k.text!,callback: {(json) in
debugPrint("json:\(String(describing: json))")
if let res=json{
if res["code"]==200{
self.musicList=[]
for (_,subJson):(String, JSON) in res["result"]["songs"] {
// debugPrint("index=\(index),subJson=\(subJson)")
let context=self.getContext()
let music = NSEntityDescription.insertNewObject(forEntityName: "Music", into: context) as! Music
music.id=subJson["id"].int64Value
music.name=subJson["name"].stringValue
debugPrint("id=\(music.id),name=\(String(describing: music.name))")
self.musicList.append(music)
}
self.musicTable.reloadData()
self.musicTable.isHidden=false
}else{
self.alert(message: "请求失败,请稍后再试")
}
}else{
self.alert(message: "请求失败,请稍后再试")
}
})
}else{
self.alert(message: "关键词不能为空")
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//
self.musicTable.dataSource = self
self.musicTable.delegate = self
self.musicTable.isHidden=true
// cell
self.musicTable.register(UITableViewCell.self, forCellReuseIdentifier: cellID)
self.keyword.delegate=self
self.keyword.returnKeyType=UIReturnKeyType.done
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
extension SearchController: UITableViewDataSource,UITableViewDelegate{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return musicList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellID)
cell?.textLabel?.text = "歌曲名:\(String(describing: musicList[indexPath.row].name!))"
return cell!
}
}
extension SearchController:UITextFieldDelegate{
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.keyword.resignFirstResponder()
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
self.search(UIButton())
}
}