1

My app has a WebView. In this WebView, I want to upload image from photo Gallery or Camera.

I did it for Android using WebChromeClient. I have no idea how to do it in iOS using Objective-C.

CheersApp
  • 11
  • 1
  • 5

2 Answers2

0

While user tap on upload image button on webview, from webview send a ScriptMessage to iOS and in iOS catch that message on WKScriptMessageHandler of WebKit inside,

userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage)

Here message contains the Script message from webview in message.body. Then open camera or gallery according to message and take photo as native app in imagepickerDelegate and save to appropriate API. You can refresh the web view after save as well.

Here is a SO post for more elaborate answer

Arnab
  • 4,216
  • 2
  • 28
  • 50
  • Can you explain first three lines? – CheersApp Oct 30 '18 at 08:43
  • Edited, please check – Arnab Oct 30 '18 at 08:47
  • How to send a ScriptMessage to iOS and how to know user tapped on upload image button on webview? – CheersApp Oct 30 '18 at 08:54
  • That would be handled from web end, you cannot handle that from iOS. From website, when user taps on the button, website will send the message, after that you can catch the message and perform image upload from iOS end. – Arnab Oct 30 '18 at 08:56
  • [Check This](https://stackoverflow.com/questions/40761218/javascript-call-to-swift-from-uiwebview#40934377) – Arnab Oct 30 '18 at 08:57
0

Assuming your upload code is in JavaScript you can add the following into your HTML

<label for="fileupload">Upload</label>
<input id="fileupload" accept="image/*" style="display:none;" type="file">

Add a change event in js to the input field and upload your file. Here is the code in JQuery

$("#fileupload").on("change", function(value){
    var value = $("#fileupload").get(0).files[0]
    // clear file so if file is loaded a second time the change event is still triggered
    $("#fileupload").val('')
    // your code to upload the file
    uploadFile(value)
})

The only other things you'll need to do are add the "Privacy - Camera Usage Description" and "Privacy - Photo Library Usage Description" flags to your app Info.plist file to enable your app's access to the camera and photolibrary.

adamfowlerphoto
  • 2,708
  • 1
  • 11
  • 24