をありがとうJSONデータを受け取ったときにそれをマップするために使用できるカスタムモデルを作成して、私はFixture
と呼ぶつもりです。私はあなたが使用しているか、あなたのモデルが含まれている必要がありますどのようなので、私はちょうど
struct Fixture {
var id: Int?
var name: String?
init(from dict: Dictionary<String, AnyObject>) {
// We'll this out later
}
}
は、その後、あなたはAPIを呼び出して取得するAlamofireを使用して関数を作成する必要があるいくつかの物事を作ってあげるどのAPIを知りません応答。これは、パラメータやヘッダーのない、本当にシンプルな関数です。
Alamofire.request(/*endpoint url*/, method: .get, parameters: nil, encoding: JSONEncoding.prettyPrinted, headers: nil).responseJSON { response in
if response.response?.statusCode == 200 {
if let JSON = response.result.value {
if let response = JSON as? Dictionary<String, AnyObject> {
// This is where to take the values out of the JSON and cast them as Swift types.
//For this example I will imagine that one fixture is returned in a dictionary called "fixture"
if let dict = response["fixture"] as? Dictionary<String, AnyObject> {
let fixture = Fixture(from: dict)
}
}
}
}
}
これは本当に簡単な例です。 APIレスポンスの正確な構造によって異なるように見えます。あなたがあなたの質問をエンドポイントで更新した場合、私はこの回答を更なるヘルプで更新することができます。
我々は今、このように見えるためにそれを更新することができ、あなたのFixture
モデルでinit
方法としては:
init(from dict: Dictionary<String, AnyObject>) {
id = dict["id"] as? Int
name = dict["name"] as? String
// Again these will need to be changed to accomodate the exact response
}
私はこの無料ビデオコースを使ってiOSネットワークを学びました。開始するには知っておくべきことがすべてわかります。https://www.udacity.com/course/ios-networking-with-swift--ud42 。または別のオプションは[alamofire](https://github.com/Alamofire/Alamofire)を使用することを学ぶことです – Scriptable