logo
down
shadow

Swift can't send URLRequest at all?


Swift can't send URLRequest at all?

By : Julien Banse
Date : November 23 2020, 01:01 AM
help you fix your problem DO NOT test network asynchronous requests on a commande line project. The execution flow will stop before the asynchronousRequest terminates... You would need to add a run loop for that. Check out this link for an example.
You should take the habit to print out everything you get from a request, to understand what is going on. You can comment out everything after you are sure the request is working as expected.
code :
var url : String = "http://google.com?test=toto&test2=titi"

var request : NSMutableURLRequest = NSMutableURLRequest()
request.URL = NSURL(string: url)
request.HTTPMethod = "GET"

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(),

    completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in

        println("OK")

        var strData = NSString(data: data, encoding: NSUTF8StringEncoding)

        println("Body: \(strData)\n\n")
        println("Response: \(response)")

        var err:NSError?
        let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary

        if (jsonResult != nil) {
            println("jsonresult : \(jsonResult)")
            // process jsonResult
        } else {
            println(err.debugDescription)
            // couldn't load JSON, look at error
        }
})


Share : facebook icon twitter icon
How send parameters for URLRequest

How send parameters for URLRequest


By : LaurenceC
Date : March 29 2020, 07:55 AM
This might help you I have send parameters for my backend in PHP but i have code and i not send parameters look , You need to use the 'variables' field in the URLRequest object:
code :
var request:URLRequest = new URLRequest(url);
request.method = URLRequestMethod.POST;
var variables:URLVariables = new URLVariables();
variables.param1 = ...
variables.param2 = ...
variables.param3 = ...
request.data = variables;

var urlLoader:URLLoader = new URLLoader();
urlLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
urlLoader.addEventListener(Event.COMPLETE, urlLoader_complete);
urlLoader.addEventListener(IOErrorEvent.IO_ERROR, urlLoader_error);
urlLoader.load(request);
Swift: Adding SSL key to URLRequest

Swift: Adding SSL key to URLRequest


By : Kurt
Date : March 29 2020, 07:55 AM
hope this fix your issue Swift 4 Assuming you have purchased yourself an SSL certificate, Google how to convert your SSL bundle certificate (.crt file) to .der format using OpenSSL in Terminal. Locate the .der file you created in your file system and drag it into your project folder in Xcode. Next, go to your project root and under Build Phases, click on the drop down list 'Copy Bundle Resources' and click the + button to add the .der file to the resource list.
Next you will need to make a class that implements URLSessionDelegate (in my case I called it URLSessionPinningDelegate) and when you formulate your URLSession call, you will pass in this class as the delegate. You should have a look at how to implement SSL certificate pinning for instructions on how to implement this class. This site here has a perfect and functioning explanation of how to do that.
code :
if let url = NSURL(string: "https://www.example.com") { // Your SSL server URL
var request = URLRequest(url: url as URL)
let password = "" // Your password value
request.setValue("Authorization", forHTTPHeaderField: password)

let session = URLSession(
configuration: URLSessionConfiguration.ephemeral,
delegate: URLSessionPinningDelegate(),
delegateQueue: nil)
let task = session.dataTask(with: request, completionHandler: { (data, response, error) in
            if error != nil {
                print("error: \(error!.localizedDescription): \(error!)")
            } else if data != nil {
                if let str = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) {
                    print("Received data:\n\(str)")
                } else {
                    print("Unable to convert data to text")
                }
            }
        })

        task.resume()
URLRequest with headers in Swift

URLRequest with headers in Swift


By : Pushpendra Pateria
Date : March 29 2020, 07:55 AM
should help you out You have to add .resume() after dataTask{...}.
As a result, it would look like this:
code :
session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) in
    if let data = data{
        do{
            let json = try JSONSerialization.jsonObject(with: data)
            print(json)
        }
        catch {
            print(error)
        }
    }

}).resume
Interceptors for URLRequest and URLSession for adding custom header fields for all URLRequest?

Interceptors for URLRequest and URLSession for adding custom header fields for all URLRequest?


By : user2046897
Date : March 29 2020, 07:55 AM
wish help you to fix your issue How can i add custom Interceptor in URLRequest and URLSession for all URLRequest in app. So i can add my own custom HTTPHeader Fields at one place for all http request, there is alamofire Interceptor but i don't want to use alamofire, i want Interceptor in urlsession and urlrequest in swift 4. I extend the urlrequest but not work for me.
code :
 //Here is the answer for "Custom Header Fields" for all URLRequest.   

extension URLRequest {
        init(_ url: URL) {
            self.init(url: url)
            self.setValue("Value", forHTTPHeaderField: "fieldNamme")
        }
    }

//how to use
func aBC(){
    //how to call it.
    let myUrl = URL(string: "Your url string")
    let request =  URLRequest(myUrl) //this will work and add custom header
    //let request =  URLRequest(url: myUrl) // this will not work because it call the super init method of urlrequest.

    request.httpMethod = "POST"
    do {
        request.httpBody = try JSONSerialization.data(withJSONObject: ["bodyParam" : "value"], options: [])
    } catch let error {
        return
    }

    let dataTask = URLSession.shared.dataTask(with: request) {
        data,response,error in

        do {
            //.
           // .
           // .
        } catch let error as NSError {
        }
    }
    dataTask.resume()
}
Swift Generic URLRequest

Swift Generic URLRequest


By : Michael
Date : March 29 2020, 07:55 AM
Hope that helps Preface: This code's a mess of inconsistent indentation and unnecessary whitespace (it reads like a double-spaced essay lol), I cleaned it up.
Looks like your function needs to take a T, but not just any T, but one that is constrained to being Encodable. This is a common observation: more general generic parameters are compatible with more types, but can do we less with them. By containing T to Encodable, we can use it with JSONEncoder.encode.
code :
import Foundation

struct Person: Codable {
    var fName: String
    var lName: String
}

struct Location: Codable {
    var city: String
    var state: String
}

// stubs for making compilation succeed
let apiKey = "dummy"
let withAPIKey = true
enum HTTPMethod: String { case GET } 

private func createRequest<Body: Encodable>(method: HTTPMethod, url: URL, withBody body: Body) throws -> URLRequest { 

    var newRequest = URLRequest(url: url)
    newRequest.httpMethod = method.rawValue

    newRequest.httpBody = try JSONEncoder().encode(body)

    if withAPIKey {
        newRequest.setValue(apiKey, forHTTPHeaderField: "APIKEY")
    }

    return newRequest
}

let data = Person(fName: "John", lName: "Smith")
let location = Location(city: "Atlanta", state: "Georgia")
Related Posts Related Posts :
  • Unclear about releasing CFDictionaryRef
  • CordovaError: Promise rejected with non-error: Error code 65
  • How to append NSMutable strings into a UILabel
  • CustomCell label value does not change
  • Display ad in iAd Bannerview iAd Network
  • Warning: "Could not get traitsetID for iPhone11,6" (Assets.xcassets)
  • Changing root view controller after iOS app has loaded.
  • SocketRocket and iOS certificate pinning
  • Draggable UIButton Snap To a Circle Path
  • Running FireBase in the background
  • resizing UIPopoverController to fit UITableController
  • UICollectionView Exception Crash
  • targeting iOS5 - will it work on iOS6 also?
  • FBLoginView get email
  • Scale UIImages height to UIImageView height
  • Creating a custom progress indicator in ios
  • NSRunLoop API difference
  • Is it possible to inject custom settings into my iOS application "Notifications" settings dialog?
  • UIAlertview not accepting string as message
  • Axis change of stackView giving layout error
  • How to use AVAssetResourceLoader?
  • How to write block definition using properties?
  • iOS connect/reconnect to Bluetooth device when using external-accessory and MFi
  • Saving XMPP Multi User chat messages through XMPP MessageArchiving in iOS
  • Deciding iOS version: pros and cons
  • iOS: Resigned app cannot access keychain through security API
  • How can I set To and Subject fields in an E-Mail being sent by UIDocumentInteractionController?
  • Updating uilabel in view controller underneath another
  • Maximum time Intervel for NSTimer
  • Delete Core Data Entry from Table View Controller
  • How to unload UIViewcontroller from memory?
  • Compressing UIImage as Far as Possible?
  • Optimizing workflow to update internally owned cocoapods dependencies?
  • Formatting an NSDate with Abbreviated Month/Day Names
  • I'm creating a quiz game with 4 answers and I want to add score
  • Tap Gesture to Hide Navigation Bar, Tab Bar, and Status Bar
  • FBSessionStateClosedLoginFailed when I am logged in through Settings
  • CGRect positioning according to center point
  • iOS: Update table view datasource with animations without core data
  • iOS : Where to start for AliPay integration?
  • Routing App Coverage File missing but not needed?
  • Drawing on a zoomable view
  • Append NSStrings and NSNumber to NSMutableArrays and make NSMutable dictionary
  • Terminating app due to uncaught exception 'NSRangeException' when calling dequeueReusableCellWithReuseIdentifier:forInde
  • Collision without physics (Cocos2D + Box2D iOS)
  • Creating a percentage based iOS layout
  • Update tableView row from AppDelegate Swift 4
  • Assigning return value of a class method to a variable error
  • how to display circular progress in delphi ios apps?
  • I can't figure how to fix this Expected identifier or '('
  • How to Test APIs in Swift 4?
  • Link error /Build/Products/Debug-iphonesimulator file not found
  • working with a very large JSON object in iOS
  • Turn off part of the iPhone Screen
  • Phonegap 3.0 app with facebook login using xCode
  • How to add interstitial admob ads to my ios project
  • adding tapku calendar to ios app
  • Add an alertcontroller in a global swift file?
  • Take square image with Cordova (Phonegap) Camera API?
  • Amazon S3 policy allowing only upload not overwrite
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org