Convert URLRequest to NSMutableURLRequest
The basics of this are get a mutable copy, update the mutable copy then update request with the mutable copy.
let mutableRequest = ((self.request as NSURLRequest).mutableCopy() as? NSMutableURLRequest)!
URLProtocol.setProperty(true, forKey: "", in: mutableRequest)
self.request = mutableRequest as URLRequest
It would be better to use avoid the forced unwrap.
guard let mutableRequest = (self.request as NSURLRequest).mutableCopy() as? NSMutableURLRequest else {
// Handle the error
return
}
URLProtocol.setProperty(true, forKey: "", in: mutableRequest)
self.request = mutableRequest as URLRequest
Note: self.request
must be declared var
not let
.
How to convert NSURLRequest to NSMutableURLRequest in Swift 3?
I just figured it out. Dang it was too obvious.
let mreq = req.mutableCopy() as! NSMutableURLRequest
becomes
var mreq = req
how to convert NSmutableURLRequest to URLRequest in Swift 4?
Few points I would like to add :
1. Unwrap optional properly, use if-let/guard-let
.
2. NS is most of the time from Objective-C, so remove NS and it's swift (most of the times)
func requestForAccessToken(authorizationCode: String) {
let grantType = "authorization_code"
let redirectURL = "https://com.appcoda.linkedin.oauth/oauth".addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
var postParams = "grant_type=\(grantType)&"
postParams += "code=\(authorizationCode)&"
postParams += "redirect_uri=\(String(describing: redirectURL))&"
postParams += "client_id=\(linkedInKey)&"
postParams += "client_secret=\(linkedInSecret)"
guard let url = URL(string: accessTokenEndPoint) else {
return
}
let postData = postParams.data(using: .utf8) // Suggested by rmaddy
var request = URLRequest(url: url)
//let request = NSMutableURLRequest(url: NSURL(string: accessTokenEndPoint)! as URL)
request.httpMethod = "POST"
request.httpBody = postData
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let session = URLSession(configuration: URLSessionConfiguration.default)
let task: URLSessionDataTask = session.dataTask(with: request) { (data, response, error) in
}
task.resume()
}
Changing url for NSMutableURLRequest after its being initialized
There is a method on NSMutableURLRequest called - (void)setURL:(NSURL *)theURL
Here's an example:
NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:url];
NSURL *anotherURL = [NSURL URLWithString:@"http://www.yahoo.com"];
[req setURL:anotherURL];
Specifically, the method documentation is at:
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableURLRequest_Class/Reference/Reference.html#//apple_ref/occ/instm/NSMutableURLRequest/setURL:
How to Extend URLRequest
You can just create a URLRequest custom initializer and set a default value for the parameters:
extension URLRequest {
init(_ url: URL, userAgent: String = "your default user agent", cachePolicy: CachePolicy = .useProtocolCachePolicy, timeInterval: TimeInterval = 60) {
self.init(url: url, cachePolicy: cachePolicy, timeoutInterval: timeInterval)
setValue(userAgent, forHTTPHeaderField: "User-Agent")
}
}
struct NumbersResult { }
func fetchNumbersFromServer(request: URLRequest, completion: @escaping (NumbersResult) -> ()) {
URLSession.shared.dataTask(with: request) { data, response, error in
// handle response
}.resume()
}
let url = URL(string: "https://www.google.com")!
let request = URLRequest(url) // you can also pass another userAgent, cachePolicy and timeInterval here if needed
fetchNumbersFromServer(request: request) { numbers in
}
Swift 3 WKWebView 'URLRequest'; did you mean to use 'as' to explicitly convert? ( BUG )
Use URL and URLRequest instead:
let url = URL(string: "https://facebook.com")!
webView.load(URLRequest(url: url))
This is quite similar to https://stackoverflow.com/a/37812485/2227743: you either use NSURL and have to downcast it as URL, or you directly use the new Swift 3 structs.
If you follow the error message, your example would become:
let url = NSURL(string: "https://facebook.com")!
webView.load(URLRequest(url: url as URL))
It could be even worse:
let url = NSURL(string: "https://facebook.com")!
webView.load(NSURLRequest(url: url as URL) as URLRequest)
All this works but of course it's much better to start using URL and URLRequest in Swift 3, without using all this downcasting.
Related Topics
How to Get Label Name from Button
Rotate a Imageview Around a Pivot Point in iOS
What am I Doing Wrong with Allowsfractionalunits on Nsdatecomponentsformatter
Hidden Property Cannot Be Changed Within an Animation Block
Code Coverage Result Is Not Accurate to Real Coverage in Xcode 7
Saving Audio After Effect in iOS
Dismiss Keyboard with Swipe Gesture
Get Index of Object from Array of Dictionary with Key Value
Passing Data Between View Controllers Without Segue
How to Add .Plist File to All Targets in Xcode
Compiler Error When Assigning the Delegate for a Protocol in Swift iOS
iOS Pod Install Gcm and Pnchartswift
Changing Selectedimage on Uitabbaritem in Swift
Swift: Bring View from Stack View to Front
How to Call Rating View from JSON and Show the Rating in My Table View
In Swift, Can a Function Be a Type
How Would I Store a Video into Firebase Storage from Swift
Transit Mkdirectionsrequest Produces Null Error Error Domain=Mkerrordomain Code=5 "(Null)"