質問編集履歴

3

内容編集

2020/11/19 08:48

投稿

tomaa
tomaa

スコア84

test CHANGED
File without changes
test CHANGED
@@ -324,6 +324,28 @@
324
324
 
325
325
  ```
326
326
 
327
+
328
+
329
+ メソッドの呼び出し
330
+
331
+
332
+
333
+ ```ここに言語を入力
334
+
335
+ Button(action: {
336
+
337
+ appState.getTemperature(date: "2020-11-11")
338
+
339
+ }
340
+
341
+ ) {
342
+
343
+ Text("取得")
344
+
345
+ }
346
+
347
+ ```
348
+
327
349
  実行結果
328
350
 
329
351
  ```console

2

追記記入

2020/11/19 08:47

投稿

tomaa
tomaa

スコア84

test CHANGED
File without changes
test CHANGED
@@ -222,9 +222,117 @@
222
222
 
223
223
 
224
224
 
225
-
225
+ ---
226
+
226
-
227
+ **追記**
228
+
229
+
230
+
227
-
231
+ ```swift
232
+
233
+ func getTemperature(date: String) -> Double? {
234
+
235
+ let semaphore = DispatchSemaphore(value: 0)
236
+
237
+
238
+
239
+ let endpoint: String = "https://sample.com/api/weather_ave_day/?date=(date)"
240
+
241
+
242
+
243
+ let url = URL(string: endpoint)
244
+
245
+
246
+
247
+ var urlRequest = URLRequest(url: url!)
248
+
249
+ urlRequest.addValue("token xxxxxxxxxxxxxxxxx", forHTTPHeaderField: "authorization")
250
+
251
+ // set up the session
252
+
253
+ let config = URLSessionConfiguration.default
254
+
255
+ let session = URLSession(configuration: config)
256
+
257
+
258
+
259
+ var temperature: Double = 0.0
260
+
261
+
262
+
263
+ let task = session.dataTask(with: urlRequest) {(data, response, error) in
264
+
265
+ guard error == nil else {
266
+
267
+ print("error calling GET")
268
+
269
+ return
270
+
271
+ }
272
+
273
+ // make sure we got data
274
+
275
+ guard let responseData = data else {
276
+
277
+ print("Error: did not receive data")
278
+
279
+ return
280
+
281
+ }
282
+
283
+ DispatchQueue.main.async {
284
+
285
+ do{
286
+
287
+ self.weatherInfos = try JSONDecoder().decode([WeatherInfos].self, from: responseData)
288
+
289
+ for info in self.weatherAveInfos!{
290
+
291
+ temperature += Double(info.ave_temp)
292
+
293
+ }
294
+
295
+
296
+
297
+ print("weatherInfos:(self.weatherInfos as Any)") // 11.9
298
+
299
+ }catch{
300
+
301
+ print("Error: did not decode")
302
+
303
+ return
304
+
305
+ }
306
+
307
+ }
308
+
309
+ semaphore.signal()
310
+
311
+ }
312
+
313
+ task.resume()
314
+
315
+ semaphore.wait()
316
+
317
+
318
+
319
+ print("returnValue:(temperature as Any)") // 0.0
320
+
321
+ return temperature
322
+
323
+ }
324
+
325
+ ```
326
+
327
+ 実行結果
328
+
329
+ ```console
330
+
331
+ returnValue:0.0
332
+
333
+ weatherInfos:Optional([Sample.WeatherInfos(id: 6, temp: 11.9)])
334
+
335
+ ```
228
336
 
229
337
  ### 補足情報(FW/ツールのバージョンなど)
230
338
 

1

タイトル編集

2020/11/19 08:04

投稿

tomaa
tomaa

スコア84

test CHANGED
@@ -1 +1 @@
1
- DispatchGroupを利用するwhile文のの設定の仕方
1
+ DispatchGroupを利用するwhile文の条件の設定の仕方
test CHANGED
File without changes