2017-01-24 37 views
1

ウェブサイトからデータを解析し、ボタンを押してテーブルビューに表示しようとしています。私はswift 3、Xcode 8.2ベータ版を使用しており、配列に格納するデータやtableViewに表示するデータを取得できません。ここに私のtableViewCellクラスは次のとおりです。ここでtableview swiftへのデータの解析3

class TableViewCell: UITableViewCell { 
@IBOutlet weak var userIdLabel: UILabel! 
@IBOutlet weak var titleLabel: UILabel! 
override func awakeFromNib() { 
    super.awakeFromNib() 
    // Initialization code 
} 

が私のViewControllerのコードは次のとおりです。

import UIKit 
class SecondViewController: UIViewController, UITableViewDelegate,UITableViewDataSource { 
let urlString = "https://jsonplaceholder.typicode.com/albums" 
@IBOutlet weak var tableView: UITableView! 
    var titleArray = [String]() 
    var userIdArray = [String]() 
@IBAction func getDataButton(_ sender: Any) { 
    self.downloadJSONTask() 
    self.tableView.reloadData() 
} 
override func viewDidLoad() { 
    super.viewDidLoad() 
    tableView.dataSource = self 
    tableView.delegate = self 
} 
override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
} 

func downloadJSONTask() { 
    let url = NSURL(string: urlString) 
    var downloadTask = URLRequest(url: (url as? URL)!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 20) 
    downloadTask.httpMethod = "GET" 


    URLSession.shared.dataTask(with: (url! as URL), completionHandler: {(Data, URLResponse, Error) -> Void in 
     let jsonData = try? JSONSerialization.jsonObject(with: Data!, options: .allowFragments) 
      print(jsonData as Any) 
     if let albumArray = (jsonData! as AnyObject).value(forKey: "") as? NSArray { 
      for title in albumArray{ 
       if let titleDict = title as? NSDictionary { 
        if let title = titleDict.value(forKey: "title") { 
         self.titleArray.append(title as! String) 
         print("title") 
         print(title) 
        } 
        if let title = titleDict.value(forKey: "userId") { 
         self.userIdArray.append(title as! String) 
        } 
        OperationQueue.main.addOperation ({ 
         self.tableView.reloadData() 
        }) 
       } 
      }     
     }   
    }).resume()  
    } 
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ 
    return titleArray.count 
    } 
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell 
    cell.titleLabel.text = titleArray[indexPath.row] 
    cell.userIdLabel.text = userIdArray[indexPath.row] 
    return cell 
    } 
    } 

答えて

0

あなたのコードでは、多くの、多くの問題がありますが、最悪の事態はスウィフトにNSArray/NSDictionaryを使用することです。

JSONは、辞書の配列であるあなたが

var titleArray = [String]() 
var userIdArray = [Int]() 

は別の最も不特定のAnyにJSONデータをキャスト決してあなたの配列を宣言する必要がありますので、キーtitleの値が、userIDの値はIntあるStringです立ち入り禁止。実際のタイプに常にキャストしてください。別の大きな問題は、クロージャのDataパラメータがネイティブ構造体と衝突することです(Swift3)。 常に小文字のパラメータラベルを使用してください。あなたのコードでリクエストはまったく使用されません。 Swift 3では、常にネイティブ構造体URLDataURLRequestなどを使用します。最後に、.allowFragmentsは、JSONがコレクション型ではっきりと始まるのでナンセンスです。

let url = URL(string: urlString)! 
let request = URLRequest(url: url, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 20) 
URLSession.shared.dataTask(with: request) { (data, response, error) in 
    if error != nil { 
     print(error!) 
     return 
    } 

    do { 
     if let jsonData = try JSONSerialization.jsonObject(with:data!, options: []) as? [[String:Any]] { 
      print(jsonData) 
      for item in jsonData { 

       if let title = item["title"] as? String { 
        titleArray.append(title) 
       } 
       if let userID = item["userId"] as? Int { 
        userIdArray.append(userID) 
       } 
       DispatchQueue.main.async { 
        self.tableView.reloadData() 
       } 
      } 
     } 
    } catch let error as NSError { 
     print(error) 
    } 
}.resume() 

PS:2つの別個の配列をデータソースとして使用することは恐ろしいことです。オプションのバインディングの1つが失敗し、配列内の項目の数が異なるとします。これはランタイムクラッシュの招待状です。

+0

ありがとうございました。私はあなたが見ることができるように、データをセルに適切にロードする方法を整理しようとしています。手伝ってくれてどうもありがとう。セルにデータをロードするときに、この行にエラーが表示されます。「cell.userIdLabel.text = userIdArray [indexpath.row]」の「Intの値をString型に割り当てることができません」というエラーが表示されます。セルテキストラベルにIntをロードする方法はありますか? – JeffBee

+0

もう一度 'Int'型を必要としない場合は' userIdArray'を '[String]'として宣言し、 'userIdArray.append(" \(userID) ")' – vadian

+0

配列に値を入れてください!このプロジェクトは学習経験であり、あなたの助けは非常に貴重です。私はアプリケーション開発の初心者です。私はあなたの推薦に従います。 – JeffBee

関連する問題