2016-06-23 6 views
1

私はAlamofire要求からのデータでグループ化されたテーブルを移入しようとしてきました。私はこれまで、配列の静的データをテーブルに埋め込んでいましたが(写真のように)、何時間も試してみて、試してみましたが、JSONデータの使い方を考えていませんでした。それはあまり差をつけるべきではありませんが、記録のためにはこれはSwift 3です。移入グループ化されたAlamofireから表とSwiftyJSON

ご協力いただければ幸いです。ありがとう。ここで

Here's what the layout looks like

素晴らしい働いている私の静的コード、です。

import UIKit 
import Alamofire 
import SwiftyJSON 

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { 

    //static Data Here: 
    var array = [ ["Clients", "John Doe", "Joe Bloggs"],["Departments", "HR", "Admin", "Finance"]] 
    let cellReuseIdentifier = "cell" 
    @IBOutlet var tableView: UITableView! 

    override func viewDidLoad() { 
     tableView.delegate = self 
     tableView.dataSource = self 
     super.viewDidLoad() 
    } 
    func numberOfSections(in tableView: UITableView) -> Int { 
     return array.count 
    } 

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return array[section].count - 1 
    } 

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

     let cell:AreasCustomCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! AreasCustomCell 

     cell.areasPreview.contentMode = .scaleAspectFit 
     request(.GET, "https://url.here.com", parameters: ["file": "default.png"]).response { (request, response, data, error) in 
      cell.areasPreview.image = UIImage(data: data!, scale:0.5) 
      } 

     cell.areasCellLabel.text = array[indexPath.section][indexPath.row + 1] 
     return cell 
    } 
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { 
     return array[section][0] 
    } 

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
     print("You tapped cell number \(indexPath.row).") 
     //More things planned here later! 
    } 
} 

私が扱っているJSONのフォーマットもここにあります。

content =  { 
    clients =   (
        { 
      desc = "Description here"; 
      group = client; 
      id = "group_7jsPXXAcoK"; 
      name = "John Doe"; 
     }, 
        { 
      desc = "Description here"; 
      group = client; 
      id = "group_19MrV7OLuu"; 
      name = "Joe Bloggs"; 
     } 
    ); 
    departments =   (
        { 
      desc = "Description here"; 
      group = department; 
      id = "group_PhAeQZGyhx"; 
      name = "HR"; 
     }, 
        { 
      desc = "Description here"; 
      group = department; 
      id = "group_RMtUqvYxLy"; 
      name = "Admin"; 
     }, 
        { 
      desc = "Description here"; 
      group = department; 
      id = "group_T50mxN6fnP"; 
      name = "Finance"; 
     } 
    ); 
}; 
state = success; 

これまで私は正しい方向にステップしているJSONデータを保持する新しいクラスを追加しました。

class Group { 

    let id : String 
    let name : String 
    let desc : String 
    let group : String 

    init(dictionary : [String : AnyObject]) { 
     id = dictionary["id"] as? String ?? "" 
     desc = dictionary["desc"] as? String ?? "" 
     name = dictionary["name"] as? String ?? "" 
     group = dictionary["group"] as? String ?? "" 
    } 
} 

最後に、viewDidLoadから呼び出されるJSONデータを最初に取得する機能を示します。

func getData() 
{ 
    let defaults = UserDefaults.standard() 
    let token = defaults.string(forKey: defaultsKeys.userToken) 
    let email = defaults.string(forKey: defaultsKeys.userEmail) 
    request(.POST, "https://url.here.com/api/v2.php", parameters: ["type": "areas", "uEmail": email!, "token": token!]) 
     .responseJSON { response in 
      var json = JSON(response.result.value!) 
      let state = json["state"].stringValue 
      if(state == "error"){ 
       print(json["message"].stringValue) 
      } else { 
       print(response.result.value) 
       //Send JSON data here to Table! 
      } 
    } 
} 

答えて

1
typealias APIResultHandler = ((response: Int, json: JSON) -> Void) 

func performAPICall(url: NSURL, method: String, body: String?, resultHandler: APIResultHandler) { 
    let session = NSURLSession(configuration: .defaultSessionConfiguration()) 
    let tokenRequest = NSMutableURLRequest(URL: url) 
    tokenRequest.HTTPMethod = method 
    if body != nil && method == Constant.POST { 
     tokenRequest.HTTPBody = body!.dataUsingEncoding(NSUTF8StringEncoding) 
    } 
    let dataTask = session.dataTaskWithRequest(tokenRequest) { 
     (let data, let response, let error) in 
     if let httpResponse = response as? NSHTTPURLResponse { 
      if error == nil { 
       let json = JSON(data: data!) 
       resultHandler(response: httpResponse.statusCode, json: json) 
      } else { 
       print("Error during \(method) Request to the endpoint \(url).\nError: \(error)") 
      } 
     } 
    } 
    dataTask.resume() 
} 

構造体クライアント{ VAR番号:文字列 するvar DESC:文字列 VAR名:文字列

init() { 
    id = "" 
    desc = "" 
    name = "" 
} 

}

するvar clientArray:[クライアント] = [] (key1 = value1)& key2 =(value2)& key3 =(value3)& KEY4 =(value4)& KEY5 =(VALUE5)」等...のviewDidLoad FUNC オーバーライド(){ super.viewDidLoad()

performAPICall(url, method: "POST", body: body) { 
      json in 
     //this will have your full response 
     print(json) 

     //put this as a class variable instead in the call 
     var clientArray: [Client] = [] 

     let clients = json["clients"] 
     for client in clients { 
       var thisClient = Client() 
       thisClient.id = json["id"].string 
       thisClient.desc = json["desc"].string 
       thisClient.name = json["name"].string 
       clientArray.append(thisClient) 
     } 
     tableview.reloadData() 
    } 

}

FUNC用のtableView(のtableView:のUITableView、cellForRowAtindexPath :IndexPath) - > UITableViewCell {

if section == 0 { 
     let cell:AreasCustomCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! AreasCustomCell 

     cell.areasPreview.contentMode = .scaleAspectFit 
     cell.areasCellLabel.text = clientArray[indexPath.row] 
    } 

    if section == 1 { 
     //do stuff for the other cell 
    } 
} 
1

申し訳ありませんが、リクエストから返信を受け取った場合、クロージャは3つの値を返します。 例:

:あなたは、一般的に、swiftyJSONで作業する場合、あなたはそのようなデータを取得することができます。この時点で、そう

if let httpResponse = response as? NSHTTPURLResponse { 
     if httpResponse.statusCode == 200 { 
      //do something with data 
     } 
} 

のような200結果の応答を確認したい

request(gibberish: DoesntMatter) { 
    data, response, error in 
} 

if let httpResponse = response as? NSHTTPURLResponse { 
     if httpResponse.statusCode == 200 { 
      let json = JSON(data: data) 
     } 
} 

API呼び出しを非同期に実行され、我々は、応答が終了したときに知っておく必要がありますされているので、今この時点でJSONを取得するための最良の方法は、閉鎖しています。

func performAPICall(url: NSURL, resultHandler: ((json: JSON) -> Void)) { 

      let session = NSURLSession(configuration: .defaultSessionConfiguration()) 
      let tokenRequest = NSMutableURLRequest(URL: url) 
      tokenRequest.HTTPMethod = "GET" 

      let dataTask = session.dataTaskWithRequest(tokenRequest) { 
       (let data, let response, let error) in 
       if let httpResponse = response as? NSHTTPURLResponse { 
        if error == nil { 
          if httpResponse.statusCode == 200 { 
           let json = JSON(data: data!) 
           resultHandler(json) 
          } else { 
           print("Failed request with response: \(httpResponse.statusCode)") 
          } 
        } else { 
         print("Error during GET Request to the endpoint \(url).\nError: \(error)") 
        } 
       } 
      } 
      dataTask.resume() 
    } 

は、その後、あなたは関数を呼び出すと、あなたはそのようなデータとするために好きなものを実行します。

performAPICall(url) { 
       json in 
      //this will have your full response 
      print(json) 
      //parse the json easily by doing something like 
      var clientArray: [Group] = [] 

      let clients = json["clients"] 
      for client in clients { 
       var thisClient = Group() 
       thisClient.id = json["id"].string 
       thisClient.desc = json["desc"].string 
       thisClient.name = json["name"].string 
       //not quite sure how to store this one 
       thisClient.group = json["group"].anyObject 
       clientArray.setByAddingObject(thisClient) 
      } 
      //make sure to call tableView.reloadData() when you give the tableViews //it's value. 
    } 

あなたは、同様のinitを介してこれを行うことができますが、適切に機能必ず設定してください。それ以外の場合は、オブジェクトの値をゼロまたは空に初期化します。また、あなたのJSON応答は文字列ではない値を返しています。あなたがそれを保存する適切な方法を見つけるためにそれを混乱させることを確認してください。お役に立てれば!

+0

レスポンスのおかげで、レスポンスがいつ終了するかを知ることが重要になった理由を理解しました。まず、performAPICallをPOSTリクエストにするにはどうすればよいですか。私は、JSONを取得するためにいくつかの値を送る必要があります。 最後に、画像に表示されているように、グループクラスをどのようにテーブルに入れるのですか?つまり、別々のグループ化されたセルを使用していますか? ありがとうございました:) – Aloogy

1

私はこれをたくさん使っています。 methodパラメータに "POST"または "GET"を渡し、bodyパラメータにボディを入力するか、GETリクエストの場合はnilを入力するだけです。 Reachabilityの部分を削除することはできますが、私は通常、API呼び出しを使ってネットワーク接続をチェックする何らかの形式を使用したいので、接続していなければすぐにエラーを診断できます。あなたはそれに使うことができるいくつかの異なるgitプロジェクトがあります。現在の警告コントローラは、私がUIViewControllerに配置した単なる拡張で、警告メッセージを簡単にします。

ここでの唯一のトリッキーな部分は、本体です。ちょうどこの設計

「キー1 =(値1)& KEY2 =(値2)& KEY3 =(VALUE3)& KEY4 =(value4)& KEY5 =(VALUE5を以下の文字列としての体を渡すよりも、RESTfulな設計を以下の場合ならば) "など...

これは、私が信じているクリーナーですが、まだ私のプロジェクトでは必要ではないと思っています。

typealias APIResultHandler = ((response: Int, json: JSON) -> Void) 

    func performAPICall(url: NSURL, method: String, body: String?, resultHandler: APIResultHandler) { 
     if Reachability.isConnectedToNetwork() == true { 
      print("Internet connection OK") 
      let session = NSURLSession(configuration: .defaultSessionConfiguration()) 
      let tokenRequest = NSMutableURLRequest(URL: url) 
      tokenRequest.HTTPMethod = method 
      if body != nil && method == Constant.POST { 
       tokenRequest.HTTPBody = body!.dataUsingEncoding(NSUTF8StringEncoding) 
      } 
      let dataTask = session.dataTaskWithRequest(tokenRequest) { 
       (let data, let response, let error) in 
       if let httpResponse = response as? NSHTTPURLResponse { 
        if error == nil { 
         let json = JSON(data: data!) 
         resultHandler(response: httpResponse.statusCode, json: json) 
        } else { 
         print("Error during \(method) Request to the endpoint \(url).\nError: \(error)") 
        } 
       } 
      } 
      dataTask.resume() 
     } else { 
      print("Internet connection FAILED") 
      presentAlertController("No Internet Connection", message: "Make sure your device is connected to the internet.") 
     } 
    } 
+0

これは応答を返します。これは関数呼び出しの終了をチェックするだけです。 – Sethmr

+0

いいえ、私がそれぞれ削除した投稿を再掲載するのではなく、実際にJSONデータを**グループ化されたテーブル**に手伝ってもらえますか?私が追加したイメージのようにレイアウトしたいので、グループ化されたビットが私に絡みついています。 これまでに私に与えてくれた助けをありがとう。 – Aloogy

+0

jsonから情報を抽出し、APIリクエストを処理する方法を理解していますか?その場合は、それに応じて配列に配置してください。 – Sethmr

0

私は時間がかかりませんが、今は時間がありません。月曜日に仕事をした後は、次回はコードを見るのに数分かかるでしょう。私のメールアドレスは[email protected]です。私にメールを送ってください。あなたがまだそれを理解できなければ、私はあなたを助けます。クロージャー、非同期のもの、API呼び出し、その他のものを混乱させると、最初に起動するときに混乱することがあります。彼らには良い記事がたくさんあります。 SWIFTのような素敵なサイズの本を得ることをお勧めします。私は、あなたが本のいくつかの無料のPDFのオンラインを見つけることができると確信しています。それらを前から読むことは、スタックオーバーフローをスキミングすることによって得るのが難しい基盤を与えるでしょう。

関連する問題