Q&A
###前提・実現したいこと
iOSアプリケーションの改造をしています。
apiから値を取得しにいくうちに画面が進んでしまい、別の処理が動いてしまいます。
取得した値によって処理を変えたいのですが、同期・非同期の処理をどのようにいれるのが
正しい(というか一般的?)のかがわかりません。
普通はこのようにするものだ、というものがありましたら教えていただきたいです。
###該当のソースコード
swift
1AppDelegate.swift 2 3func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool { 4 //apiからデータを取得する 5 //ここで行う処理を待ってから次へ行きたい 6 getMemberInfo() 7 8 //取得したデータをもとに処理を行う 9 ... 10 11 //データ取得する前にhogeViewControllerの中の処理が動いてしまう 12 window?.rootViewController = hogeViewController 13} 14 15func getMemberInfo(){ 16 //共通で使うAPI呼び出し部分 17 let ret: [AnyHashable: Any]? = getInfo(data1, data2) 18 19 //取得に失敗するときはサーバがおちてる 20 if ( ret == nil ){ 21 DispatchQueue.main.async { 22 let alertController = UIAlertController(title: "Error",message: "データとれませんでした.再起動してください", preferredStyle: UIAlertControllerStyle.alert) 23 let okAction = UIAlertAction(title: "アプリを閉じる", style: UIAlertActionStyle.default){ (action: UIAlertAction) in 24 exit(0) 25 } 26 alertController.addAction(okAction) 27 self.window?.rootViewController?.present(alertController,animated: true,completion: nil) 28 } 29 return 30 }else{ 31 //データがとれたらUserDefaultとかに保存する処理 32 … 33 } 34} 35 36Utility.swift 37 func getInfo(_ data1: String, whithdata2 data2: String) -> [AnyHashable: Any]? { 38 //リクエスト用のパラメータを設定 39 var url: String = "http://~" 40 let param: String = "data1=" + data1 + "&data2=" + data2 41 42 let condition = NSCondition() 43 var parsedData: [AnyHashable : Any]? = nil 44 var encURL: NSURL = NSURL() 45 46 encURL = NSURL(string:url.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)!)! 47 var r = URLRequest(url: encURL as URL, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 20) 48 r.httpMethod = "POST" 49 r.httpBody = param.data(using: String.Encoding.utf8) 50 51 let task = URLSession.shared.dataTask(with: r) { (data, response, error) in 52 if error == nil { 53 do { 54 if error != nil { 55 condition.unlock() 56 } 57 let httpResponse: HTTPURLResponse? = (response as? HTTPURLResponse) 58 //200が成功 59 if httpResponse?.statusCode != 200 { 60 condition.unlock() 61 } 62 parsedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [AnyHashable : Any] 63 } catch let error as NSError { 64 condition.unlock() 65 } 66 } 67 condition.signal() 68 condition.unlock() 69 } 70 condition.lock() 71 task.resume() 72 73 condition.wait() 74 condition.unlock() 75 76 return parsedData 77 } 78 79
###補足情報(言語/FW/ツール等のバージョンなど)
Xcode9.1
Swift3
回答1件
あなたの回答
tips
プレビュー
下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。