2015-08-27 2 views
0

У меня есть таблица для работы, и я могу заполнить ее, когда я использую письменный массив (например, values = [""]), поэтому я знаю, что он работает.Заполнение таблицы с внешними значениями базы данных в swift

Но я использую json с swiftyjson, чтобы получить информацию в своем столе, которая является частью правой страницы слайда, которую я сделал с mmdrawer. Когда я println выход json, я получаю всю необходимую мне информацию, но ее не принимают в таблицу или другие переменные/массивы.

Как заставить этот код работать?

import UIKit 

class RightSideViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { 

    var songname = [String]() 
    var menuImage = [String]() 




    override func viewWillAppear(animated: Bool) { 
     super.viewWillAppear(animated) 
     self.navigationController?.navigationBarHidden = true 
    } 

    override func prefersStatusBarHidden() -> Bool { 
     return true 
    } 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     getmusiclist() 

    } 

    func getmusiclist(){ 

     let search:NSString = "music" as NSString 

    let url = NSURL(string:"http://xxxxxx/music-manager.php") 
    let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData 
    var request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 2.0) 
    request.HTTPMethod = "POST" 

    // set Content-Type in HTTP header 
    let boundaryConstant = "----------V2ymHFg03esomerandomstuffhbqgZCaKO6jy"; 
    let contentType = "multipart/form-data; boundary=" + boundaryConstant 
    NSURLProtocol.setProperty(contentType, forKey: "Content-Type", inRequest: request) 

    // set data 
    var dataString = "search=\(search)" 
    let requestBodyData = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding) 
    request.HTTPBody = requestBodyData 

    // set content length 
    //NSURLProtocol.setProperty(requestBodyData.length, forKey: "Content-Length", inRequest: request) 

    var response: NSURLResponse? = nil 
    var error: NSError? = nil 
    let dataReply = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&error) 

    var results = NSJSONSerialization.JSONObjectWithData(dataReply!, options: nil, error: &error) as! NSDictionary 

    var jsonOutput = JSON(data: dataReply!) 
     println(jsonOutput) 
     let musicListArray = jsonOutput.arrayValue 

     dispatch_async(dispatch_get_main_queue(), { 
      for playlist in musicListArray 
      { 
       let trackname = playlist["track_name"].stringValue 
       println("trackName: \(trackname)") 
       self.songname.append(trackname) 
      } 
      /* dispatch_async(dispatch_get_main_queue(),{ 
       self.tableView.reloadData() 

       })*/ 
      }) 

    } 


    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 

    func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
     return 1 
    } 

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ 
     return songname.count; 
    } 


    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ 

     var mycell = tableView.dequeueReusableCellWithIdentifier("playerCell", forIndexPath: indexPath) as! MusicTableViewCell 

     mycell.artistLabel?.text = songname[indexPath.row] 


     return mycell 

    } 
} 

В конце концов, я хотел бы взять на себя имя, жанр и потоковый URL и AVPlayer играть - будет, что будет что-то я могу добавить к этому коду?

+0

После self.songname.append (название дорожки), вызовите tableView.reloadData() – Shripada

+0

я дам, что попробовать и посмотреть, если он работает – carlosx2

+0

я зову его, как это/* dispatch_async (dispatch_get_main_queue(), { self.tableView.reloadData() }) */Мне нужно поместить его непосредственно после songname.append – carlosx2

ответ

0

проблема с той частью, что я забыл добавить выход uitableview в uiviewcontroller. Я добавил его, и теперь ошибка исчезла. Я все еще должен понять, почему я не получаю ничего, но кажется, что я получаю данные от jsonOutput.arrayvalue.

Смежные вопросы