How to get form input value from evaluateJavaScript method in WKWebView in swift 4? - swift4

In my project UIWebView is being used for display forms and when user input data and submit the form, the javascript method of UIWebView is being used to get resulting string as:
let formstring: String = formWebView.stringByEvaluatingJavaScript(from: "document.getElementById('json').value;") ?? ""
in above formstring I get this as result:
{"personnel":"testName","textarea1":"testxyz","status":"1"}
Now I need to migrate from UIWebview to WKWebview as UIWebview is deprecated now. For this I have implemented the WKWebview and the form is displaying in it. but when I try to get value from javascript I get nothing as:
formWebView.evaluateJavaScript("document.getElementById('json').value;", completionHandler: {(result,error)in
if error != nil{
print(result)
formstring = result as! String
}
})
In above lines 'result' is always nil.
May be I am unable to understand what exactly is going on with UIWebView or I can't find out how to get output from WKWebView. The thing is I need to get form input from javascript in my code.
How to get it?

Related

How to generate QRCode image with parameters in swift?

I need to create QRCode image with app registered users 4 parameters, so that if i scan that QRCode image from other device i need to display that user details, that is my requirement.
here i am getting registered user details: with these parameters i need to generate QRCode image
var userId = userModel?.userId
var userType = userModel?.userType
var addressId = userModel?.userAddrId
var addressType = userModel?.userAddrType
according to [this answer][1] i have created QRCode with string... but i. need to generate with my registered user parameters
sample Code with string:
private func createQRFromString(str: String) -> CIImage? {
let stringData = str.data(using: .utf8)
let filter = CIFilter(name: "CIQRCodeGenerator")
filter?.setValue(stringData, forKey: "inputMessage")
filter?.setValue("H", forKey: "inputCorrectionLevel")
return filter?.outputImage
}
var qrCode: UIImage? {
if let img = createQRFromString(str: "Hello world program created by someone") {
let someImage = UIImage(
ciImage: img,
scale: 1.0,
orientation: UIImage.Orientation.down
)
return someImage
}
return nil
}
#IBAction func qrcodeBtnAct(_ sender: Any) {
qrImag.image = qrCode
}
please suggest me
[1]: Is there a way to generate QR code image on iOS
You say you need a QR reader, but here you are solely talking about QR generation. Those are two different topics.
In terms of QR generation, you just need to put your four values in the QR payload. Right now you’re just passing a string literal, but you can just update that string to include your four properties in whatever easily decoded format you want.
That having been said, when writing apps like this, you often want to able to scan your QR code not only from within the app, but also any QR scanning app, such as the built in Camera app, and have it open your app. That influences how you might want to encode your payload.
The typical answer would be to make your QR code payload be a URL, using, for example, a universal link. See Supporting Universal Links in Your App. So, first focus on enabling universal links.
Once you’ve got the universal links working (not using QR codes at all, initially), the question then becomes how one would programmatically create the universal link that you’d supply to your QR generator routine, above. For that URLComponents is a great tool for encoding URLs. For example, see Swift GET request with parameters. Just use your universal link for the host used in the URL.
FWIW, while I suggest just encoding a universal link URL into your QR code, above, another option would be some other deep linking pattern, such as branch.io.

I can’t access PDFDocument properties after initialising PDFView

I’m working on a react native app with a bridge from Swift to handle PDF files. I am trying to simply get the total number of pages of a given PDF document.
I have tried to initialise the PDFView class and set a document url. But when I try pdfView.document!.pageCount, I cannot access the int because pdfView.document is nil
pdfView = PDFView()
pdfView.document = PDFDocument(url: url)
pageCount = pdfView.document!.pageCount // crashes here every time
I would expect pageCount to hold the value of the total number of pages in the document. Instead the app crashes due to unexpected unwrapping of nil optional.
Unexpected wrapping of nil optional means that the PDF document doesn't exist. You need to either check the URL or the location of the PDF document.
I suggest you don't use force unwrap ('!') unless necessary. Use '??' instead and give a default value.

How to show pdf data from a filestream

I am working against a REST API where you can make a call and then receive a image or pdf. I am using URLSession.shared.dataTask to make the call and when there is a image the call is a success (but it takes quite a long time, more then 5 seconds) and I can show the image in a UIImageView. But when there is a pdf, I don't know how to handle the result. The API returns the image / pdf as a ”filestream”.
When I print the data to the console it prints the size (bytes) and its the same size as in the server so in some way I have the correct data, I just don't know how to view the pdf.
I am using swift 3, iOS 10, xcode 8.
First of all you may want to ask your question into two part. Please edit it and ask the second part again.
There are two parts in this topic
1. Downloading the PDF and save it in File System
2. Get the pdf that saved in File System and read it using UIWebView or UIDocumentInteractionController
So, I will explain for the first one.
The first one can be done if you use REST HTTP client : Alamofire : Elegant HTTP Networking in Swift. So no need to use URLSession for such case and you will have to write so many lines if you do. It's simple and easy. So, I want you to try it. If you need URLSession instead, leave comment.
So how to download pdf using Alamofire :
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
//.documentDirectory means it will store in Application Document Folder
let fileURL = documentsURL.appendPathComponent("data.pdf")
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
Alamofire.download(urlString, to: destination).response { response in
print(response)
if response.error == nil, let filePath = response.destinationURL?.path {
// do anything you want with filePath here.
// Here what you have to do Step 2. (Read the file that you downloaded)
}
}
This download procedure doesn't include requesting download link with encoded parameters. It was just simple way.

How to load NSUserDefaults data on a Today Extension in Swift?

I've already searched a lot but any answer fixed the problem.
I've created an app group, selected it on both app and today extension, they're linked to the same group now. I'm trying to load data from the app and display it on a table view on the today extension, the thing is that I'm getting a crash saying that my array is nil, and it cannot be nil. I don't know why tho, cause I'm putting the data into the array. Here is my code:
func handleData() {
let defaults = NSUserDefaults(suiteName: "MY APP GROUP HERE")
if let descriptionsArr = defaults?.valueForKey("descriptions") as? [String] {
descriptions = descriptionsArr
}
defaults?.synchronize()
}
So, I'm pretty sure the app group is spelled right, and the value key. What could it be that is making my array nil? Really need help!
Thanks.

Text output from "Just" library in Swift

I am writing a program in Swift that uses Just to fetch a webpage. I am new to Swift and know very little about it. My code is simple:
let r = Just.get("https://www.google.com/")
print(r.statusCode!)
print(r.text)
I would expect to see the contents of the downloaded web page, however, the output is:
200
nil
How can I retrieve the text contents of the response?
The problem is in your URL. If you'll try this, your response won't be nil:
let r = Just.get("https://medium.com/")
print(r.text!)
}