logo
down
shadow

How can I obtain POST request body from WKWebView in Swift?


How can I obtain POST request body from WKWebView in Swift?

By : user3099660
Date : January 11 2021, 03:34 PM
it fixes the issue I'm answering my own question because I figured out how to do this on my own. Perhaps my question wasn't clear. My end goal was to extract the body content as a string.
Firstly, I ditched the callback I used:
code :
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
    // do stuff
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    webView.evaluateJavaScript("document.getElementById(\"my-id\").innerHTML", completionHandler: { (jsonRaw: Any?, error: Error?) in
        guard let jsonString = jsonRaw as? String else { return }
        let json = JSON(parseJSON: jsonString)
        // do stuff
    })
}


Share : facebook icon twitter icon
How to send a POST request with BODY in swift

How to send a POST request with BODY in swift


By : Gonzalo Fernández
Date : March 29 2020, 07:55 AM
this will help You're close. The parameters dictionary formatting doesn't look correct. You should try the following:
code :
let parameters: [String: AnyObject] = [
    "IdQuiz" : 102,
    "IdUser" : "iosclient",
    "User" : "iosclient",
    "List": [
        [
            "IdQuestion" : 5,
            "IdProposition": 2,
            "Time" : 32
        ],
        [
            "IdQuestion" : 4,
            "IdProposition": 3,
            "Time" : 9
        ]
    ]
]

Alamofire.request(.POST, "http://myserver.com", parameters: parameters, encoding: .JSON)
    .responseJSON { request, response, JSON, error in
        print(response)
        print(JSON)
        print(error)
    }
iOS swift post request with binary body

iOS swift post request with binary body


By : Night
Date : March 29 2020, 07:55 AM
With these it helps I want to make a POST request from iOS (swift3) which passes a chunk of raw bytes as the body. I had done some experimenting which made me thought the following worked: , The two common solutions are:
code :
let base64Encoded = data
    .base64EncodedString(options: [])
    .addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)!
    .data(using: String.Encoding.utf8)!

var body = "key=".data(using: .utf8)!
body.append(base64Encoded)

var request = URLRequest(url: url)
request.httpBody = body
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard error == nil else {
        print(error!)
        return
    }

    ...
}
task.resume()
extension CharacterSet {
    static let urlQueryValueAllowed: CharacterSet = {
        let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
        let subDelimitersToEncode = "!$&'()*+,;="

        var allowed = CharacterSet.urlQueryAllowed
        allowed.remove(charactersIn: generalDelimitersToEncode + subDelimitersToEncode)
        return allowed
    }()
}
how to make post request with row http body using swift as postman request test?

how to make post request with row http body using swift as postman request test?


By : SaiKumar Shailu
Date : March 29 2020, 07:55 AM
hope this fix your issue You can directly generate a code from postman itself. Also, for your reference, you can call post request with row body as given below.
code :
let headers = [
        "content-type": "application/json",
        "cache-control": "no-cache"
    ]

    let parameters = ["order": ["line_items": [
                                            ["variant_id": 18055889387589,
                                             "quantity": 1]
                     ]]] as [String : Any]

    let postData = try? JSONSerialization.data(withJSONObject: parameters, options: [])

    if let data = postData {
        let request = NSMutableURLRequest(url: NSURL(string: "http://")! as URL,
                                          cachePolicy: .useProtocolCachePolicy,
                                          timeoutInterval: 10.0)
        request.httpMethod = "POST"
        request.allHTTPHeaderFields = headers
        request.httpBody = data as Data

        let session = URLSession.shared
        let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
            if (error != nil) {
                print(error?.localizedDescription ?? "")
            } else {
                let httpResponse = response as? HTTPURLResponse
                print(httpResponse?.statusCode ?? 0)


                let reponseData = String(data: data!, encoding: String.Encoding.utf8)
                print("responseData: \(reponseData ?? "Blank Data")")
            }
        })

        dataTask.resume()
    }
How to send body in post request in swift

How to send body in post request in swift


By : William
Date : March 29 2020, 07:55 AM
wish of those help I think I went somewhere wrong copying/pasting code from stack overflow without understanding. , Please Try this code :
code :
    // prepare json data
    let json: [String: Any] = ["testConfigKey": "testing"]

    let parameters = try? JSONSerialization.data(withJSONObject: json)

    // create post request
    let url = URL(string: checkUserConfig)!
    var apiRequest = URLRequest(url: url)
    apiRequest.httpMethod = "POST"
    apiRequest.addValue("application/json",forHTTPHeaderField: "Content-Type")

    // insert json data to the request
    apiRequest.httpBody = parameters

    let task = URLSession.shared.dataTask(with: apiRequest) { data, response, error in
        guard let data = data, error == nil else {
            print(error?.localizedDescription ?? "No data Available")
            return
        }
        let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
        if let responseJSON = responseJSON as? [String: Any] {
            print(responseJSON)
        }
    }

    task.resume()
I can't send body in data in body in post request of swift project in any api

I can't send body in data in body in post request of swift project in any api


By : Edeline Eugene
Date : October 03 2020, 01:00 PM
To fix this issue So, as I understood correctly you're using Google Maps API and the request you're trying to perform is a GET request which means that you need to specify request parameters in the URL itself, not the body. I think your request should look like this
code :
    let googleKey = "your api key"
    let url: String = "maps.googleapis.com/maps/api/place/autocomplete/json?input=Apple&components=country:ids&input=\(str)&types=adress&key=\(googleKey)"
    Alamofire.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON
Related Posts Related Posts :
  • How to connect an iPhone app (rest) to XAMPP using a local WIFI connection?
  • Swift 4 delegate is not working with tabbar controller
  • How do i compile all contact's phone numbers into one cell - using CNContact
  • How do I change the color of two UIButtons when I press them?
  • UIViewPropertyAnimator doesn’t work as expected
  • GoogleMaps camera target in top left corner of map iOS since pod update
  • Allowing SwiftUI to import all Contacts and delete specific ones
  • Why is array in collection view getting multiplied by amount of sections?
  • How is enumerated() constant time O(1)?
  • How to get XML data and bind in tableview in iOS Swift?
  • Interface Builder Constraints Problems
  • Xcode 11 beta can't upload app to TestFlight
  • iOS odd Thread 1: Fatal error: Index out of range on iPad
  • Cannot convert json object to struct
  • How can I prevent the stopwatch from resetting after pause
  • Cannot convert value of type '() -> _' to specified type '[UIViewController]'
  • How to make a reference to a uid stored in Firestore?
  • How do you initialize/use UITableViewCells with CellStyle = .value1 programmatically?
  • How to know if Apple has received our appeal/how long does it take Apple to respond?
  • Select new item added to SwiftUI List
  • What is the correct length: argument to provide to NSRange for NSRegularExpression using a (Swift) String?
  • I am trying to delete data from database, but sometime data is deleted and sometime data is not deleted
  • How to get slider value with subview rotation angle
  • Can't pass custom UINavigationBar / UIToolbar to UINavigationController because they don't conform to AnyClass
  • Remove app before simulator or device is lunched from Xcode
  • Auto Layout constraints for container view inside UITableView header broken for different devices
  • iPhone restarts after API call
  • What is the shortcut / How do I create function after writing it's usage in Xcode
  • Convert apple time stamp to Unix time
  • No podspec found for `React-fishhook`
  • How to test touch dialog and perform real in-app purchase?
  • Compiling Metal shaders from source on iOS 13 Simulator gives PCH error
  • conan error:I need to cross build packages for os:iOS with my Macos, but when the first package was done, it broke my cp
  • Update calendar 'start of week' from phones system calendar
  • Xcode is showing some warnings
  • How to remove the default Navigation Bar space in SwiftUI NavigiationView
  • Having trouble integrating multiple pickerviews in the same view
  • SCNNode not in SCNView hierarchy, still showing & getting touches & physics
  • How can I open my SwiftUI app and perform a function using NSUseractivity from within Siri Intent Extension?
  • NSCoding decodeObject always nil
  • Passing data in a segmented Controller?
  • Facing issue in Siri Integration with custom intents
  • ARKit3 Hardware Requirement Clarification
  • ARKit3 How to use TrueDepth camera for face tracking and face meshes of other people?
  • How to discriminate while decoding using Codable Protocol in Swift?
  • 'IPA processing failed' while distributing build in Xcode Beta
  • How to debug a crash which happened when come back from background
  • Synchronising old data with NSPersistentCloudKitContainer
  • iOS app opened from web app with url redirects to Appstore
  • How to change the color of seperator in tableView?
  • Is there a better way to watch for a key-value change?
  • How to make UIBezierPath to fill from the center
  • Why on Xcode 11, UICollectionViewCell changes size as soon as you scroll (I already set size in sizeForItem AtIndexPath:
  • How to scan non LE devices using Swift?
  • Unable to infer closure type in the current context in SwiftUI
  • What is the best way to write common code and use it entire project
  • UISegmentedControl inside UIStackView, segments text not centered - iOS 13
  • Swift & ObjC bridge - cannot find protocol declaration for "WKNavigationDelegate"
  • SwiftUI How to push to next screen when tapping on Button
  • 'NSApp' is unavailable in UIKit for Mac: How to embed Mac only framework in iOS app on macOS?
  • shadow
    Privacy Policy - Terms - Contact Us © festivalmusicasacra.org