NSURLConnection sendSynchronousReques replacement
This is the minimum code you would need to make an async request, if you are replacing a lot of calls you should make an API layer and reuse code rather than copy/pasta everywhere.
let url = URL(string: "http://myURL.com")!;
let request = URLRequest(url: url)
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
let dictionary = try! JSONSerialization.jsonObject(with: data!, options: .allowFragments)
}
task.resume()
ios Cancel NSURLConnection Swift
NSURLConnection
's sendAsynchronousRequest
is not a cancelable request. But NSURLConnection
is deprecated, anyway, and you should use NSURLSession
. And NSURLSession
's dataTask
is cancelable.
So, instead of:
NSURLConnection.sendAsynchronousRequest(request, queue: queue) { response, data, error in
do {
....code.....
}
}
You can use:
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
do {
....code.....
}
}
task.resume()
And, if you need to cancel it, you can do task.cancel()
.
What are the difference among NSURLConnection, NSURLSession and AFNetworking?
Difference among NSURLConnection
, NSURLSession
The entire model is different.
NSURLSession
is designed around the
assumption that you'll have a lot of requests that need similar
configuration (standard sets of headers, etc.), and makes life much
easier if you do.
NSURLSession
also provides support for background downloads, which
make it possible to continue downloading resources while your app
isn't running (or when it is in the background on iOS). For some use
cases, this is also a major win.
NSURLSession
also provide a grouping of related requests, making it
easy to cancel all of the requests associated with a particular work
unit, such as canceling all loads associated with loading a web page
when the user closes the window or tab.
NSURLSession
also provides nicer interfaces for requesting data
using blocks, in that it allows you to combine them with delegate
methods for doing custom authentication handling, redirect handling,
etc., whereas withNSURLConnection
if you suddenly realized you
needed to do those things, you had to refactor your code to not use
block-based callbacks.
Difference among NSURLConnection
, NSURLSession
and AFNetworking?
NSURLConnection
andNSURLRequest
are the provided Cocoa classes
for managing connections. In iOS 7, Apple added NSURLSession.But I think you'll find AFNetworking to be a framework that
further simplifies network requests (notably complex HTTP requests).
If you don't want to use third-party frameworks for any reason, you
can useNSURLConnection
and/orNSURLSession
directly. It just
takes a little more coding.For information on
NSURLConnection
andNSURLSession
see the URL
Loading System Programming Guide.Find from reference1 and reference2
Thank rob and dgatwood for such an amazing Answer...
URL File Size With NSURLConnection - Swift
The response parameter has the type
AutoreleasingUnsafeMutablePointer
which means that you can pass the address of an optional NSURLResponse
as argument:
var response : NSURLResponse?
NSURLConnection.sendSynchronousRequest(request, returningResponse: &response , error: nil)
You can then conditionally cast the returned response to a NSHTTPURLResponse
:
if let httpResponse = response as? NSHTTPURLResponse {
println(httpResponse.expectedContentLength)
}
Note that you should check the return value of sendSynchronousRequest()
, which
is nil
if no connection could be made.
It is also recommended to call this
method only from a separate thread (or use sendAsynchronousRequest()
instead)
because it can take a while to make a connection
– in particular when using a cellular network – and the main thread would be
blocked otherwise.
Swift 3 NSURLSession/NSURLConnection HTTP load failed when connecting to a site with authentication
Okay well I didn't know how to fix this but I discovered that Alamofire can be used to do what I needed. This is a local project for inventory management so I wasn't concerned about the security of bypassing the certificates. My code is here:
Manager.delegate.sessionDidReceiveChallenge = { session, challenge in
var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
var credential: URLCredential?
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust, let trust = challenge.protectionSpace.serverTrust {
disposition = URLSession.AuthChallengeDisposition.useCredential
credential = URLCredential(trust: trust)
} else {
if challenge.previousFailureCount > 0 {
disposition = .cancelAuthenticationChallenge
} else {
credential = Manager.session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)
if credential != nil {
disposition = .useCredential
}
}
}
return (disposition, credential)
}
private var Manager: Alamofire.SessionManager = {
// Create the server trust policies
let serverTrustPolicies: [String: ServerTrustPolicy] = [
"https://SERVER:PORT": .disableEvaluation
]
// Create custom manager
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = Alamofire.SessionManager.defaultHTTPHeaders
let manager = Alamofire.SessionManager(
configuration: URLSessionConfiguration.default,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
)
let sessionManager = SessionManager(
serverTrustPolicyManager: ServerTrustPolicyManager(
policies: ["https://SERVER:PORT": .disableEvaluation]
)
)
return manager
}()
open class MyServerTrustPolicyManager: ServerTrustPolicyManager {
// Override this function in order to trust any self-signed https
open override func serverTrustPolicy(forHost host: String) -> ServerTrustPolicy? {
return ServerTrustPolicy.disableEvaluation
}
}
NSURLConnection finished with error - code -1002 when trying to encode URL in iOS
You are not creating your URL
correctly. You are passing a path to the string
argument. You need to use the URL(fileURLWithPath:)
initializer.
let url = URL(fileURLWithPath: path)
Only use the URL(string:)
initializer if the string you pass is a valid URL beginning with a URL scheme.
Related Topics
Xcode 7 Error: "Missing iOS Distribution Signing Identity For ..."
Adding a Closure as Target to a Uibutton
Changing Specific Text's Color Using Nsmutableattributedstring in Swift
How to Use Uiview Autoresizingmask Property Programmatically
Opening View Controller from App Delegate Using Swift
Trying to Convert Firebase Timestamp to Nsdate in Swift
How to Create .Ipa File Using Xcode
Nsurlconnection Using iOS Swift
Sqlite File Location Core Data
How to Create Radio Buttons and Checkbox in Swift (Ios)
Reading Nfc Tags with iPhone 6/iOS 8
Passing Parameters to Addtarget:Action:Forcontrolevents
Importing Project-Swift.H into a Objective-C Class...File Not Found
Wkwebview Equivalent for Uiwebview's Scalespagetofit