2017-12-12 8 views
0

iOS用の開発を練習するために、iPhone用の非常に基本的なレッドクライアントを構築しています。私は選択したサブディレクトリのJSONを解析するようにしましたが、解析されたJSONのタイトルをUITableViewに表示することはできません。私が現時点で抱えている問題は、UITableViewがロードされる前にJSONデータをポピュレートする "postList"配列を取得できないということです。したがって、表ビューのセルにデータが移入されると、postList配列の要素にはデータが移入されません。どのようにこれを修正するための任意のアイデア?JSONデータでUITableViewを実装する

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { 

@IBOutlet weak var tableView: UITableView! 

let URL = "https://www.reddit.com/r/swift/.json" 

var postList : [PostList] = Array(repeating: PostList(), count: 26) 
//var postList : [PostList] = [] 
override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 
    tableView.dataSource = self 
    tableView.delegate = self 
} 

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

} 
//Setting up tableView 
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return 5 
} 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    var cell = tableView.dequeueReusableCell(withIdentifier: "aroundMeCell", for: indexPath) 

    getPosts(url: URL, row: indexPath.row, cell: cell) 
    let title = postList[indexPath.row].title 
    cell.textLabel?.text = title 
    return cell 
} 


//Receiving posts using Alamofire 
func getPosts(url: String, row: Int, cell: UITableViewCell) { 
    Alamofire.request(url, method: .get) 
     .responseJSON { response in 
      if response.result.isSuccess { 
       let postJSON : JSON = JSON(response.result.value!) 
       //print(postJSON) 
       self.createPostListArray(json: postJSON, row: row, cell: cell) 

      } else { 
       print("Error: \(String(describing: response.result.error)) aaaaaa") 
      } 
    } 
} 

func createPostListArray(json: JSON, row: Int, cell: UITableViewCell) { 

    let titlePath : [JSONSubscriptType] = ["data", "children", row, "data", "title"] 
    let postPath : [JSONSubscriptType] = ["data", "children", row, "data", "selftext"] 

    //Making sure I can unwrap both 
    if(json[titlePath].string != nil && json[postPath].string != nil){ 
     let inTitle = json[titlePath].string! 
     let inPost = json[postPath].string! 
     postList[row].title = inTitle 
     postList[row].post = inPost 
    } 
    else{ 
     print("error") 
    } 
} 
+0

私はcellForRowAtからあなたが呼び出しのチェーンを介して細胞を渡し、Alamofire.requestを呼び出し、その後、セルは、(それがそうでデキューすることができ、...)その端末の場所に到着し、多くの問題を参照してください"createPostListArray"にあり、使用されていません。私の場合、このコードは悪い匂いがする。 –

+2

おそらく問題はありませんが、 'Array(repeat:count:'構文で配列を作成することはできません。配列を 'cellForRowAt'で' viewDidLoad'で行います。 – vadian

+0

StackOverflowで他の質問を参照しようとしましたか?質問タイトルを検索する[多くの質問を返す](https://stackoverflow.com/search?q=Populate + UITableView + + JSON + data)と同様の問題:o) – agrm

答えて

1

コードには複数の問題があります。

1-。空の配列var postList = [PostList]()を作成し、応答時にdelete要素を追加することができます。

2 - cellForRowAtでAPIを呼び出すことはまったくお勧めできません。 理由:このメソッドが呼び出されるたびに、APIを呼び出します。このAPIと呼ばれるデキューごとにテーブルビューをスクロールしているというシナリオを考えてみましょう。

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { 

@IBOutlet weak var tableView: UITableView! 

let URL = "https://www.reddit.com/r/swift/.json" 

var postList = [PostList]() 
override func viewDidLoad() { 
    super.viewDidLoad() 
    getPosts(url: URL) 
    tableView.dataSource = self 
    tableView.delegate = self 
} 

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

} 
//Setting up tableView 
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return postList.count 
} 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    var cell = tableView.dequeueReusableCell(withIdentifier: "aroundMeCell", for: indexPath) 
    let title = postList[indexPath.row].title 
    cell.textLabel?.text = title 
    return cell 
} 


//Receiving posts using Alamofire 
func getPosts(url: String) { 
    Alamofire.request(url, method: .get) 
    .responseJSON { [weak self] response in 
     if response.result.isSuccess { 
        let postJSON : JSON = JSON(response.result.value!) 
       //print(postJSON) 
       self?.createPostListArray(json: postJSON) 
       self?.tableView.reloadData() 

      } else { 
       print("Error: \(String(describing: response.result.error)) aaaaaa") 
      } 
    } 
} 

func createPostListArray(json: JSON) { 
    //parse your json here, or read about objectMapper a pod. This will help you in parsing and if you are using swift 4, read encode json. 
} 
0

まず、viewDidLoad()でapi呼び出しを行います。配列を宣言します。

 var postList = [PostList] 

api呼び出し成功ブロックの後にself.tableview.reloadData()を実行します。

関連する問題