How to make HTTP request in Swift?

You can use URL, URLRequest and URLSession or NSURLConnection as you’d normally do in Objective-C. Note that for iOS 7.0 and later, URLSession is preferred. Using URLSession Initialize a URL object and a URLSessionDataTask from URLSession. Then run the task with resume(). let url = URL(string: “http://www.stackoverflow.com”)! let task = URLSession.shared.dataTask(with: url) {(data, response, error) … Read more

NSURLSession concurrent requests with Alamofire

Yes, this is expected behavior. One solution is to wrap your requests in custom, asynchronous NSOperation subclass, and then use the maxConcurrentOperationCount of the operation queue to control the number of concurrent requests rather than the HTTPMaximumConnectionsPerHost parameter. The original AFNetworking did a wonderful job wrapping the requests in operations, which made this trivial. But … Read more

Send POST request using NSURLSession

You could try using a NSDictionary for the params. The following will send the parameters correctly to a JSON server. NSError *error; NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil]; NSURL *url = [NSURL URLWithString:@”[JSON SERVER”]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; [request addValue:@”application/json” forHTTPHeaderField:@”Content-Type”]; [request addValue:@”application/json” forHTTPHeaderField:@”Accept”]; [request setHTTPMethod:@”POST”]; … Read more

How to use special character in NSURL?

Swift 2 let original = “http://www.geonames.org/search.html?q=Aïn+Béïda+Algeria&country=” if let encodedString = original.stringByAddingPercentEncodingWithAllowedCharacters( NSCharacterSet.URLFragmentAllowedCharacterSet()), url = NSURL(string: encodedString) { print(url) } Encoded URL is now: “http://www.geonames.org/search.html?q=A%C3%AFn+B%C3%A9%C3%AFda+Algeria&country=“ and is compatible with NSURLSession. Swift 3 let original = “http://www.geonames.org/search.html?q=Aïn+Béïda+Algeria&country=” if let encoded = original.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed), let url = URL(string: encoded) { print(url) }

Swift: How do I return a value within an asynchronous urlsession function?

You should add your own completionHandler closure parameter and call it when the task completes: func googleDuration(origin: String, destination: String, completionHandler: (Int?, NSError?) -> Void ) -> NSURLSessionTask { // do calculations origin and destiantion with google distance matrix api let originFix = origin.stringByReplacingOccurrencesOfString(” “, withString: “+”, options: NSStringCompareOptions.LiteralSearch, range: nil); let destinationFix = destination.stringByReplacingOccurrencesOfString(” … Read more

How To Download Multiple Files Sequentially using NSURLSession downloadTask in Swift

Your code won’t work because URLSessionDownloadTask runs asynchronously. Thus the BlockOperation completes before the download is done and therefore while the operations fire off sequentially, the download tasks will continue asynchronously and in parallel. While there are work-arounds one can contemplate (e.g., recursive patterns initiating one request after the prior one finishes, non-zero semaphore pattern … Read more

How can I get the Data from NSURLSession.sharedSession().dataTaskWithRequest

You can’t return data directly from an asynchronous task. The solution with Swift 2 is to make a completion handler like this: class PostFOrData { // the completion closure signature is (NSString) -> () func forData(completion: (NSString) -> ()) { if let url = NSURL(string: “http://210.61.209.194:8088/SmarttvWebServiceTopmsoApi/GetReadlist”) { let request = NSMutableURLRequest( URL: url) request.HTTPMethod = … Read more

The resource could not be loaded because the App Transport Security policy requires the use of a secure connection

I have solved it with adding some key in info.plist. The steps I followed are: Opened my Project target’s info.plist file Added a Key called NSAppTransportSecurity as a Dictionary. Added a Subkey called NSAllowsArbitraryLoads as Boolean and set its value to YES as like following image. Clean the Project and Now Everything is Running fine … Read more

NSURLSession/NSURLConnection HTTP load failed on iOS 9

Found solution: In iOS9, ATS enforces best practices during network calls, including the use of HTTPS. From Apple documentation: ATS prevents accidental disclosure, provides secure default behavior, and is easy to adopt. You should adopt ATS as soon as possible, regardless of whether you’re creating a new app or updating an existing one. If you’re … Read more