Reputation: 251
I am developing an iOS app built in Swift with two webViews using WKWebView. One of the web has a default sound that sounds every time the webView loads (the web is not mine). So I need to stop or don't allow the webView to reproduce any sound. There is any method to get this? I tried some code but it doesn't work. I'm using xCode 9 and Swift 4.
This is the code I've tried (but it doesn't work):
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
}
catch let error as NSError {
print(error)
}
do {
try AVAudioSession.sharedInstance().setActive(false)
}
catch let error as NSError {
print(error)
}
This is my code:
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
@IBOutlet weak var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "theWeb")
let request = URLRequest(url: url!)
webView.navigationDelegate = self
webView.load(request)
}
}
Thank you for your responses and sorry for my question, I'm new to programming.
Upvotes: 2
Views: 3232
Reputation: 299265
The elements in question are these:
<audio src="audio/alarm.mp3" preload="auto" loop="true" class="alarm mp3" type="audio/mp3"></audio>
<audio src="audio/alarm2.mp3" preload="auto" loop="true" class="urgent alarm2 mp3" type="audio/mp3"></audio>
The first thing I would try is changing the WKWebViewConfiguration
. In order to do that, you have to create the WKWebView
programmatically and insert it into your view. You can't do this with Interface Builder unfortunately. Here's some untested code that may work. (If it doesn't we can dig into this further, but this is where I'd start. The next step if this doesn't work is to implement a WKNaviagtionDelegate
to deny the audio load requests.)
let config = WKWebViewConfiguration()
config.mediaTypesRequiringActionForPlayback = WKAudiovisualMediaTypeAll
webView = WKWebView(frame: view.bounds, configuration: config)
view.addSubview(webView)
If your web view doesn't fill the entire view, then a convenient way I've found to make this work is to add a blank UIView
in Interface Builder and lay it out where you want it. Then just put the webView in that blank view at runtime (and make it the same size). This is nice because it lets you do all the layout in IB, but still insert the web view where needed.
Upvotes: 1