回答編集履歴
2
レスポンスのデータ型で処理を分岐
answer
CHANGED
@@ -47,4 +47,51 @@
|
|
47
47
|
}
|
48
48
|
```
|
49
49
|
|
50
|
-
ご参考にしてください。
|
50
|
+
ご参考にしてください。
|
51
|
+
|
52
|
+
|
53
|
+
---
|
54
|
+
|
55
|
+
これで動くでしょう。
|
56
|
+
|
57
|
+
以下のAPIで動作を確認しました。
|
58
|
+
`https://tepco-usage-api.appspot.com/latest.json`
|
59
|
+
`https://qiita.com/api/v2/items`
|
60
|
+
|
61
|
+
`SwiftyJSON`や`Argo`のようなJSONパーサを利用したほうがきっと幸せになれるでしょう。
|
62
|
+
[SwiftyJSON/SwiftyJSON](https://github.com/SwiftyJSON/SwiftyJSON)
|
63
|
+
[thoughtbot/Argo](https://github.com/thoughtbot/Argo)
|
64
|
+
|
65
|
+
```swift
|
66
|
+
.responseJSON { response in
|
67
|
+
switch response.result {
|
68
|
+
// データを取り出す
|
69
|
+
case .Success(let value):
|
70
|
+
// print(value)
|
71
|
+
let dataArray = NSMutableArray()
|
72
|
+
var dict = NSDictionary()
|
73
|
+
// レスポンスのデータ型を確認
|
74
|
+
if value is NSDictionary {
|
75
|
+
// print("value is Dictionary type.")
|
76
|
+
|
77
|
+
dict = value as! NSDictionary
|
78
|
+
dataArray.addObject(dict)
|
79
|
+
|
80
|
+
} else if value is NSArray {
|
81
|
+
// print("value is Array type.")
|
82
|
+
|
83
|
+
let count = value.count
|
84
|
+
for(var i = 0; i < count; ++i) {
|
85
|
+
dict = value[i] as! NSDictionary
|
86
|
+
dataArray.addObject(dict)
|
87
|
+
}
|
88
|
+
}
|
89
|
+
print("データ数: \(dataArray.count)")
|
90
|
+
print(dataArray[0])
|
91
|
+
// print(dataArray[0]["id"] as! Int)
|
92
|
+
// 失敗時エラー出力
|
93
|
+
case .Failure(let error):
|
94
|
+
print(error)
|
95
|
+
}
|
96
|
+
}
|
97
|
+
```
|
1
記述の変更、他アクセス先でのケース
answer
CHANGED
@@ -6,4 +6,45 @@
|
|
6
6
|
print(id)
|
7
7
|
let name = jsonDict["name"] as! String
|
8
8
|
print(name)
|
9
|
-
```
|
9
|
+
```
|
10
|
+
|
11
|
+
---
|
12
|
+
|
13
|
+
以下のように書くとどのような出力になりますか。
|
14
|
+
```swift
|
15
|
+
.responseJSON { response in
|
16
|
+
switch response.result {
|
17
|
+
// データを取り出す
|
18
|
+
case .Success(let value):
|
19
|
+
print(value)
|
20
|
+
// 失敗時エラー出力
|
21
|
+
case .Failure(let error):
|
22
|
+
print(error)
|
23
|
+
}
|
24
|
+
}
|
25
|
+
```
|
26
|
+
|
27
|
+
また、`requestUrl`を変更しても出力に違いが見られませんか。
|
28
|
+
`requestUrl`を`https://tepco-usage-api.appspot.com/latest.json`にすると、私の環境では以下のような出力になります。
|
29
|
+
|
30
|
+
```json
|
31
|
+
{
|
32
|
+
capacity = 4214;
|
33
|
+
"capacity_peak_period" = 17;
|
34
|
+
"capacity_updated" = "2012-12-24 08:30:00";
|
35
|
+
day = 25;
|
36
|
+
entryfor = "2015-12-24 16:00:00";
|
37
|
+
forecast = 0;
|
38
|
+
"forecast_peak_period" = 17;
|
39
|
+
"forecast_peak_updated" = "2012-12-24 08:30:00";
|
40
|
+
"forecast_peak_usage" = 3620;
|
41
|
+
hour = 1;
|
42
|
+
month = 12;
|
43
|
+
saving = 0;
|
44
|
+
usage = 2623;
|
45
|
+
"usage_updated" = "2015-12-24 17:05:06";
|
46
|
+
year = 2015;
|
47
|
+
}
|
48
|
+
```
|
49
|
+
|
50
|
+
ご参考にしてください。
|