「swift」カテゴリーアーカイブ

Swift2

HTMLのあれをとってくる

https://qiita.com/_tid_/items/8705275813e740d693ef

webView.evaluateJavaScript("document.documentElement.innerHTML") { value, error in
    print(value as? String as Any)
}

これはHTML全文になるので

 

webView.evaluateJavaScript("document.getElementById('tes').innerHTML") { value, error in
    print(value as? String as Any)
}

で,HTML内に

<p id="tes">2019</p>

いれておくと,

optinal(“2019”)と表示される.

 


IDをWKWebkitからとれなかったので,cookieから取る

まずPHPでcookieにuseridを設定

//cookie設定(Swift用)
$userid = $_SESSION["id"];
setcookie('userid', $userid,time()+60*60*24*7);
echo $_COOKIE[‘userid’];

 

Swiftでcookieを取得・ただしこれはiOS11用

        //セッション取得
        let cookieStore = webView.configuration.websiteDataStore.httpCookieStore

//        webView.configuration.websiteDataStore.httpCookieStore.getAllCookies {
//            print($0)//全部取る
//        }

                cookieStore.getAllCookies() { (cookies) in
            for cookie in cookies {
                if cookie.domain == "hoge.com" &&
                    cookie.name == "userid" {
                    // UserDefaultsに保存
                    let cookieData = NSKeyedArchiver.archivedData(withRootObject: cookie)
                    UserDefaults.standard.set(cookieData, forKey: "Cookie")
                    UserDefaults.standard.synchronize()
                    print(cookie.value)//これでuseridだけとれる
                }
            }
        }
        //

XCODEのコンソールに表示される

参考

https://qiita.com/haru15komekome/items/fdbdea6d755545468ac8


特定のURLで実行させたい(途中)

 

extension ViewController: WKNavigationDelegate {//の中に書く

// 読み込み開始後に実行
 func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
     //URLチェック
     //0.5秒後に実行する
     DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
         // 0.5秒後に実行したい処理
         
     }
 }

参考
https://swift.tecc0.com/?p=669

https://qiita.com/s_emoto/items/dc3d61626155f5cf83e7

これのまとめ

extension ViewController: WKNavigationDelegate {

の中にかきます

// 読み込み開始後に実行
   func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
       //URLチェック
       let currentUrl:URL? = webView.url
       let url = currentUrl?.absoluteString
       
       // 特定のURLで分岐処理
       if url!.contains("https://hoge.com") { //動的URLなのでcontain使用url!<-は
           
           //print("URLが含まれる")
           // 0.5秒後に実行したい処理
           DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
               
               //セッション取得
               let cookieStore = webView.configuration.websiteDataStore.httpCookieStore
               //        webView.configuration.websiteDataStore.httpCookieStore.getAllCookies {
               //            print($0)
               //        }
               cookieStore.getAllCookies() { (cookies) in
                   for cookie in cookies {
                       if cookie.domain == "life-log.org" &&
                           cookie.name == "userid" {
                           // UserDefaultsに保存
                           let cookieData = NSKeyedArchiver.archivedData(withRootObject: cookie)
                           UserDefaults.standard.set(cookieData, forKey: "Cookie")
                           UserDefaults.standard.synchronize()
                           print(cookie.value)//cookieのuseridをsessionに表示
                       }
                   }
               }
               ////セッションここまで
               
           }
       }
       
   }

 

containsの参考

https://qiita.com/osamu1203/items/3ee63291c37d91428b55

 


 

こんな夜更けにSwiftかよ

急ぎの開発案件ですがAndroidは作成中っぽいのでSwiftコードで

Simple Web Viewのチュートリアル実行
https://qiita.com/fromage-blanc/items/079bc8d6da34ac90fecf

こSimulatorで制作中のサイトチェック,JS系動作OK
動画が見づらいと言うのでこのサイトを見るも普通に動画再生確認.問題が起きたときに再確認.

iPhoneXに対応?
https://jidouka.work/?p=248

XR等にお対応をどうするのか,,

Push通知実装

参考

https://qiita.com/toshi586014/items/5dea32faab94828fae75

can’t find gem cocoapods 出たので,
sudo gem install cocoapods

pod init できた

pod isntallする.参考WEBにそって,公式より1つ多くSDKインスト

  pod 'Firebase/Core'
  pod 'Firebase/Messaging'

XCODEでエラーでた

Could not build Objective-C module ‘Firebase’

手順,

https://dev.classmethod.jp/smartphone/iphone/remove-xcode-derived-data/

1.Xcodeを終了
2.該当プロジェクトの「DerivedData」ファイルを削除

(消し方がわからない方は関連リンクをご覧ください。)
3.ProjectName.xcworkspaceを削除

(ProjectNameはプロジェクト名が入ります。)
4.「Podfile.lock」ファイルと「Pods」フォルダを削除
5.「pod install」で再度ポッドを追加
6.新しく生成された「ProjectName.xcworkspace」ファイルを開きビルド

特に1と6が重要
これで,Firebaseとの通信できた.

Firebaseから通知送るときは,
(1)実機であること

(2)通知送る画面の最下部にあるサウンドバッジを有効にする.

 

ここから,個別端末に通知の内容

このあたりを参考にした
https://qiita.com/miyae/items/623c7869714b894a1b83

これも参考に
https://cpoint-lab.co.jp/article/201811/%E3%80%90%E5%82%99%E5%BF%98%E9%8C%B2%E3%80%91firebase-cloud-messaging%E3%81%A7%E3%81%AE%E3%83%97%E3%83%83%E3%82%B7%E3%83%A5%E9%80%9A%E7%9F%A5%E3%81%AE%E9%80%81%E4%BF%A1%E3%81%AB%E3%81%A4%E3%81%84/


まず,個別端末通知の方法

AppDelegate.swiftに

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let deviceTokenStr: String = deviceToken.reduce("", { $0 + String(format: "%02X", $1) })
    print("APNsトークン: \(deviceTokenStr)")

    // APNsトークンを、FCM登録トークンにマッピング


    if let fcmToken = InstanceID.instanceID().token() {
        print("FCMトークン: \(fcmToken)")
    }
}

を追加.これのFCMトークンがデバイスID.XCODEのコンソールで見ることができる

 

この情報元に,PHPでメッセージを送る

&lt;?php
class Notification {
  private static $apiKey = "ここにサーバーキー";  // Firebase console:Overview &gt; プロジェクトの設定 &gt; クラウドメッセージング &gt; サーバーキー
  private static $url = "https://fcm.googleapis.com/fcm/send";

  static public function send($pushTokens,$title,$message) {
    $headers = [
      "Authorization: key=".self::$apiKey,
      "Content-Type: application/json"
    ];

    $fields = [
      "registration_ids" =&gt; is_array($pushTokens) ? $pushTokens : [$pushTokens],
      "priority" =&gt; "high",
      "notification" =&gt; [
        "title" =&gt; $title,
        "text" =&gt; $message
      ]
    ];

    $handle = curl_init();
    curl_setopt($handle, CURLOPT_URL, self::$url);
    curl_setopt($handle, CURLOPT_POST, true);
    curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($handle, CURLOPT_POSTFIELDS, json_encode($fields));
    $result = curl_exec($handle);
    curl_close($handle);
    return $result;
}
}
?&gt;

これを送信するPHP

<?php

//クラス読み込み
require_once './messageClass.php';
//クラス生成
//$message = new Notification();

$pushTokens='';//ここにデバイスID
$title="はろー";
$message="ぼくどらやき";

Notification::send($pushTokens, $title, $message);

?>