###前提・実現したいこと
iOSアプリでプッシュ通知を行いたいのですが、以下のようにコードを作成しました。
AppDelegate.swift
import UIKit import UserNotifications @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { if #available(iOS 10.0, *) { // iOS 10 let center = UNUserNotificationCenter.current() center.requestAuthorization(options: [.badge, .sound, .alert], completionHandler: { (granted, error) in if error != nil { return } if granted { debugPrint("通知許可") } else { debugPrint("通知拒否") } }) } else { // iOS 9 let settings = UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil) UIApplication.shared.registerUserNotificationSettings(settings) } return true } //APNsに登録が成功すると呼ばれる func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { print("deviceToken = \(deviceToken)") let characterSet: NSCharacterSet = NSCharacterSet( charactersIn: "<>" ) let deviceTokenString: String = ( deviceToken.description as NSString ) .trimmingCharacters( in: characterSet as CharacterSet ) .replacingOccurrences( of: " ", with: "" ) as String print( deviceTokenString ) let server = "register.php" let request = NSMutableURLRequest(url: NSURL(string: server)! as URL) request.httpMethod = "POST" let token = "token=\(deviceTokenString)" request.httpBody = token.data(using: String.Encoding.utf8) var response: URLResponse? let resultData = try! NSURLConnection.sendSynchronousRequest(request as URLRequest, returning: &response) let myData:NSString = NSString(data: resultData, encoding: String.Encoding.utf8.rawValue)! print(myData) } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print("error: \(error)") } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } //アプリケーションが起動している状態もしくは通知から起動した場合に呼ばれる private func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { print ("application:didReceiveRemoteNotification: " + userInfo.description); } }
regiter.php
<?php $mysqli = new mysqli($server, $userName, $password,$dbName); if ($mysqli->connect_error){ print("接続失敗:" . $mysqli->connect_error); exit(); }else{ $mysqli->set_charset("utf-8"); } $token = null; // デバイストークンを受け取る $token = $_POST['token']; if (!isset($token)) { print "no token"; exit; } $result = "no"; $query = "SELECT token FROM push_device WHERE token='$token'"; $res = $mysqli -> query($query); if($res){ //受け取ったデバイストークンがデータベースにない場合 if(!mysqli_num_rows($res)){ // テーブルに追加する $query = "INSERT INTO push_device (token) VALUES ('$token')"; if ($mysqli -> query($query)) { // 登録成功 $result = "ok"; } }else{// デバイストークンは既に登録済み $result = "ok"; } } // 結果を返す print $result;
push.php
<?php $mysqli = new mysqli($server, $userName, $password,$dbName); if ($mysqli->connect_error){ print("接続失敗:" . $mysqli->connect_error); exit(); }else{ $mysqli->set_charset("utf-8"); } // 指定したデバイストークンにペイロードを通知する関数 function pushNotification($apnsStream, $deviceToken, $payload) { // デバイストークンを16進文字列からバイナリ文字列に変換する $tokenBin = pack('H*', $deviceToken); // ペイロードの長さを取得する $len = strlen($payload); if ($len > 256)// iOS8以降は最大2キロバイトとなる return; // APNsに送信するバイト列を作成する $buf = chr( 0 ) . pack( 'n', 32 ) . $tokenBin . pack( 'n', strlen($payload ) ) . $payload; // APNsに送信する fwrite($apnsStream, $buf); } // ペイロードを作成 // 送信する文字 $alert = "テストです"; // バッジ $badge = 1; // カスタム $custom_text = "カスタムテキストです"; // キー「aps」の配列作成 $apsDict = array("alert" => $alert, "badge" => $badge); // ペイロードの作成 $payloadDict = array("aps" => $apsDict, "custom_text" => $custom_text); // 作成したペイロードをJSONでエンコードする $payload = json_encode($payloadDict); //APNsゲートウェイを指定する $url = 'ssl://gateway.sandbox.push.apple.com:2195'; // 開発用 //$url = 'ssl://gateway.push.apple.com:2195'; // Ad Hoc及び製品用 //SSL証明書 $certFile = "push_develop.pem"; // 通信を行うためのストリームコンテキストを作成する $context = stream_context_create(); // SSL証明書を使って暗号化するので、ストリームコンテキストに設定する stream_context_set_option($context, 'ssl', 'local_cert', $certFile); // APNsとの間でソケット接続を行う $stream = stream_socket_client($url, $errno, $errstr, 60,STREAM_CLIENT_CONNECT, $context); if ($stream != FALSE) { if ($mysqli) { // 全デバイストークンを取得する $query = "SELECT token FROM push_device"; $result = $mysqli -> query($query); if ($result) { // 1レコードずつ処理する while ($row = $result->fetch_assoc()) { // デバイスに通知する pushNotification($stream, $row['token'], $payload); } } } // ソケットを閉じる fclose($stream); } // DBを切断 $mysqli->close(); ?>
上記のように、コードを作成したのですがデバイスのtokenが取得できず、データベースにデータが保存されません。
また、push.phpで$stream = stream_socket_clientのところが、unableのエラーとなってしますのですが、なぜでしょうか。
初心者なので、アドバイス頂けますと幸いです。
テーブルは、id,token(text)としました。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/07/26 09:00