2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ブラウザアプリ作り(1) とりあえず動く状態にする→iOSアプデで不要に...

Last updated at Posted at 2020-03-15

Youtubeなどの動画を観ながら別の作業をしたい。
よくある場面としては実況動画を見ながら関連する情報を検索する、というのがあります。あるいはTwitterのTLを見ながらYoutubeの動画音楽を再生したいということもありますよね(YoutubeMusicに課金するのはなんか悔しい)。そこで、これらのニーズに応えられるブラウザアプリを作っていきたいと思います。

今回進んだのは以下です。
・WKWebViewを使った2画面ブラウザ
・セーフエリアの設定
・動画のブラウザ内再生

まず、ブラウザの実装です。
以下のサイトを参考にさせていただきました。
SwiftUIでWebViewを使う

コードは上Qiita記事の円コピなので省略します。WebView.swiftを新しく作成して、ContentView.swiftでWebView(loadUrl:)で呼び出すんですね。非常にわかりやすいです。
スクリーンショット

次に、画面を分割してみます。
VStackでビューを2つ並べてみます。
スクリーンショット

いい感じです。
次に、高さを調整します。Youtubeには画面の3割を、残りを他に割きます。
参考:SwiftUIの肝となるGeometryReaderについて理解を深める

ContentView.swift
struct ContentView: View {
    var body: some View {
    GeometryReader {geometry in
      VStack{
            WebView(loadUrl: "https://www.twitter.com")
              .frame(width: geometry.size.width, height: geometry.size.height * 7 / 10)
              WebView(loadUrl: "https://www.youtube.com")
        }
    }
  }
}
スクリーンショット 画面を7:3で分けられました。

下のセーフエリアがもったいないので、ここも使えるようにします。VStackに

.edgesIgnoringSafeArea(.bottom)

をつけてやります。

最後に、デフォルトだとYoutubeを再生し始めると全画面になってしまうのですが、これが起きないようにします。

参考:How can I add web view preferences to a swift ui web view

変更するのは先ほど作成したWebView.swiftです。

WebView.swift
import SwiftUI
import WebKit

struct WebView: UIViewRepresentable {
    var loadUrl:String
    var allowsInlineMediaPlayback: Bool{true}

    func makeUIView(context: Context) -> WKWebView {
      let webConfiguration = WKWebViewConfiguration()
      webConfiguration.allowsInlineMediaPlayback = true
      return WKWebView(frame: .zero, configuration: webConfiguration)
    }

    func updateUIView(_ uiView: WKWebView, context: Context) {
        uiView.load(URLRequest(url: URL(string: loadUrl)!))
    }
}
スクリーンショット

これで、ひとまず使える当初の目的にかなったアプリにはなりました。
まだまだ機能が足りていないので、随時勉強&追加していきます。

今回作成したコード
https://github.com/KanikaniYou/MultiTube

追記:iOSのアップデートで、このアプリの必要性が皆無になってしまいました。ちょっと別のアプリを考えます。

2
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?