2017-06-06 10 views
0

アプリがバックグラウンドまたはサスペンド状態のときにデータをサーバーにポストしようとしています。私はyesとNoのアクションでアクション可能なプッシュ通知を実装しました。はいまたはいいえをタップしてバックエンドを更新する必要があります。 アプリケーションがフォアグラウンドで実行されていても、バックグラウンドまたはサスペンド状態で失敗している場合、下のコードは正常に動作します。どのようにこれを処理するかを知ることができます。URLSession.shared.dataアプリケーションがバックグラウンドのときにタスクを呼び出す

func updateEmployeeStatus(){ 

    let json = ["id": "23", "empId": "3242", "status": "Success"] as Dictionary<String, String> 


    let jsonData = try? JSONSerialization.data(withJSONObject: json) 

    // create post request 
    let url = URL(string: "https://10.91.60.14/api/employee/status")! 
    var request = URLRequest(url: url) 
    request.httpMethod = "POST" 

    // insert json data to the request 
    request.httpBody = jsonData 

    let task = URLSession.shared.dataTask(with: request) { data, response, error in 
     guard let data = data, error == nil else { 
      print(error?.localizedDescription ?? "No data") 
      return 
     } 
     let responseJSON = try? JSONSerialization.jsonObject(with: data, options: []) 
     if let responseJSON = responseJSON as? [String: Any] { 
      print("The response is",responseJSON) 
     } 
    } 

    task.resume() 
} 

答えて

0

アプリケーションがバックグラウンド状態のときにデータタスクを開始するには、共有「URLセッション」を使用できません。あなたは、データのタスクを行うために、背景の設定

let bundleID = Bundle.main.bundleIdentifier 
let configuration = URLSessionConfiguration.background(withIdentifier: "\(bundleID).background") 
configuration.sessionSendsLaunchEvents = true 
configuration.isDiscretionary = false 
configuration.allowsCellularAccess = true 
let session = Foundation.URLSession(configuration: configuration, delegate: self, delegateQueue: nil) 

を使用して「URLSession」をインスタンス化し、そのセッションを使用する必要が

背景セッション構成を使用しているとき、あなたが完了してデータのタスクを作る傾けることに注意してくださいブロック。代わりに代理人を使用する必要があります。

希望に役立ちます。

関連する問題