Http request on iOS app starting - ios

I want to send http request on every myapp-starting.
How to do this? I try:
class MainViewController: UITableViewController {
func my_request(){
let url = NSURL(string: "http://www.stackoverflow.com")
let request = NSURLRequest(URL: url)
let connection = NSURLConnection(request: request, delegate:nil, startImmediately: true)
println(connection)
}
let lol = my_request()
}
But I have an error: Missing argument for parameter #1 in call
How to fix that?
Thanks!

my_request() returns nothing, if you just want to call the function, use only
my_request()
I would suggest to put this in the ViewDidLoad function (on your Main ViewController of your App)

Related

How to check resume capability of current URLSessionDownloadTask?

Currently i'm working on downloading a file from server, and this is working good.
my question is how would i know that url has resume capability or not before actual download started?
bellow is some code snippet,
class Downloader:NSObject,URLSessionDownloadDelegate {
/*
SOME PROPERTIES & DECLARATIONS
*/
override init() {
super.init()
let backgroundSessionConfiguration = URLSessionConfiguration.background(withIdentifier: url.absoluteString)
backgroundSessionConfiguration.networkServiceType = .default
self.defaultSession = URLSession(configuration: backgroundSessionConfiguration, delegate: self, delegateQueue: OperationQueue.main)
}
func start(_ block:DownloaderCompletionHandler?) {
guard self.input == nil else { return }
guard self.output == nil else { return }
if let data = self.resumableData {
self.downloadTask = self.defaultSession.downloadTask(withResumeData: data)
}else {
let request = URLRequest(url: self.input!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 0.60)
self.downloadTask = self.defaultSession.downloadTask(with: request)
}
self.downloadTask.resume()
}
func pause() {
self.downloadTask.cancel { (data) in
self.resumableData = data
}
}
}
please , guid me on this situation.
THANKS IN ADVANCE
A download can be resumed only if the following conditions are met:
The resource has not changed since you first requested it
The task is an HTTP or HTTPS GET request
The server provides either the ETag or Last-Modified header (or both) in its response
The server supports byte-range requests
The temporary file hasn’t been deleted by the system in response to disk space pressure
→ Source: https://developer.apple.com/documentation/foundation/urlsessiondownloadtask/1411634-cancel
if you send a request with Range in HttpHeaders and receive a 206 status code in response , then you can resume the download. otherwise download can not be resumed.
read more about it here

swift 3+, URLsession, in the background fails apparently at random

I am fairly new to swift(1 week) and iOS programming, and my problem is that I seem to miss some basic understanding. Below you see a function that is triggered by a background notification. I can and have verified that I receive the background notification reliably and the app comes active (printout of the raw data values on the console) As long as the app is in the foreground everything is working just as expected, it gets fired, and sends a single https request. The background triggers come on a timer every minute.
Now the whole thing changes when the app enters into the background. In this case I am still getting the triggers through the notification (console printout) and I can see in the debugger the same function that works like a charm in the foreground stumbles. It still works, it still gets fired, but a data packet is sent only so often, randomly as it seems between 2 and 30 minutes.
let config = URLSessionConfiguration.background(withIdentifier: "org.x.Reporter")
class queryService {
let defaultSession = URLSession(configuration: config)
var dataTask: URLSessionDataTask?
var errorMessage = ""
func getSearchResults(baseURL: String, searchTerm: String) {
dataTask?.cancel()
config.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData;
config.timeoutIntervalForRequest = 10
if var urlComponents = URLComponents(string: "https://host.com/reportPosition.php") {
urlComponents.query = "\(searchTerm)"
guard let url = urlComponents.url else { return }
dataTask = defaultSession.dataTask(with: url)
}
// 7
dataTask?.resume()
}
}
Try using dataTaskWithCompletion so you can see what's going wrong in the error.
URLSession.shared.dataTask(with: URL.init(string: "")!) { (data, response, error) in
if error != nil {
// Error
}
}.resume()
https://developer.apple.com/documentation/foundation/urlsession/1410330-datatask
EDIT
What you want to do is for background you get completions via delegate call backs so when you init ur URLSession do so using the following func
URLSession.init(configuration: URLSessionConfiguration.init(), delegate: self, delegateQueue: OperationQueue.init())
https://developer.apple.com/documentation/foundation/urlsession/1411597-init
Then conform ur class to the URLSessionDelegate like so
class queryService, URLSessionDelegate {
then implement the delegate methods listed here for call backs
https://developer.apple.com/documentation/foundation/urlsessiondelegate
EDIT2
Here is good tutorial about it
https://www.raywenderlich.com/158106/urlsession-tutorial-getting-started

Downloading files in iOS [duplicate]

This question already has answers here:
How to download file in swift?
(16 answers)
Closed 6 years ago.
I'm trying to download a file using Swift. This is the downloader class in my code:
class Downloader {
class func load(URL: URL) {
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
let request = NSMutableURLRequest(url: URL)
request.httpMethod = "GET"
let task = session.dataTask(with: URL)
task.resume()
}
}
I call the function like this:
if let URL = URL(string: "https://web4host.net/5MB.zip") {
Downloader.load(URL: URL)
}
but this error message pops up:
2017-02-16 04:27:37.154780 WiFi Testing[78708:7989639] [] __nw_connection_get_connected_socket_block_invoke 2 Connection has no connected handler
2017-02-16 04:27:37.167092 WiFi Testing[78708:7989639] [] __nw_connection_get_connected_socket_block_invoke 3 Connection has no connected handler
2017-02-16 04:27:37.169050 WiFi Testing[78708:7989627] PAC stream failed with
2017-02-16 04:27:37.170688 WiFi Testing[78708:7989639] [] nw_proxy_resolver_create_parsed_array PAC evaluation error: kCFErrorDomainCFNetwork: 2
Could someone tell me what I'm doing wrong and how I could fix it? Thanks!
The code to receive the data is missing.
Either use delegate methods of URLSession or implement the dataTask method with the completion handler.
Further for a GET request you don't need an URLRequest – never use NSMutableURLRequest in Swift 3 anyway – , just pass the URL and don't use URL as a variable name, it's a struct in Swift 3
class Downloader {
class func load(url: URL) { // better func load(from url: URL)
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
let task = session.dataTask(with: url) { (data, response, error) in
// handle the error
// process the data
}
task.resume()
}
}

My UIWebView is being called though I've not performed any segue

I have a UIWebView which when intercepts a particular URL makes a transition to a UIViewController.
When a button is clicked this viewController presents another UIViewController modally.
What's weird is that when a unwind segue is performed to the first UIViewController, it appears for a split second only to show the webView and I am fairly certain that this is the same webView as the first one as this webView "continues" from the URL it left previously and also all the variables initiated in the webView have the values they held prior to the segue.
func makeHTTPGetRequest(path: String, onCompletion: ServiceResponse) {
let request = NSMutableURLRequest(URL: NSURL(string: path)!)
let session = NSURLSession.sharedSession()
if (NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies as? [NSHTTPCookie] != nil) || ((NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies as? [NSHTTPCookie])! != []){
ToolBox.cookieJar = (NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies as? [NSHTTPCookie])!
// ToolBox.maxIndex++
}
println(NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies as? [NSHTTPCookie])
var cookies = ToolBox.cookieJar
var headers : NSDictionary = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies)
var storage : NSHTTPCookieStorage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
for cookie in storage.cookies as! [NSHTTPCookie]{
storage.deleteCookie(cookie)
}
NSUserDefaults.standardUserDefaults()
request.allHTTPHeaderFields = (headers as [NSObject : AnyObject])
request.HTTPShouldHandleCookies = true
request.HTTPMethod = "POST"
var bodyData = "frontend=android"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
let json:JSON = JSON(data: data)
onCompletion(json,error)
})
task.resume()
}
I set debug points in all the suspicious places, just before the viewController moves to the webView, task.resume() is called.
The webView shows up now, but the code in the viewController class is getting executed.
I am trying to understand what might have been the reason this is happening for the past couple of hours with no luck. I am pretty sure that I am not calling the webView at all, in fact it is the initial view controller and no other class calls it, so the only possible reason is that the webView is getting called implicitly by some function I am using, but I am unable tot figure it out, I am reading docs for every function but I found nothing to solve this bug.
If someone knows the reason for the bug, please share it with me.
EDIT: One more thing I think is important to mention is that from the animation of the transition from the viewController to webView , it seems as if the viewController is unwinding to webView, which is odd since the segue from webView to viewController is a show segue.
Update: I commented all the code in my viewWillAppear() and viewDidAppear() and ran the app. The webView popped up just after viewDidAppear() function got called the viewWillAppear() of webView is getting called.
Update2: Thanks for everyone who tried to solve this problem. The bug turned out to be a very stupid one.
#IBAction func unwindToList(segue : UIStoryboardSegue){
if !segue.sourceViewController.isBeingDismissed() {
segue.sourceViewController.dismissViewControllerAnimated(true, completion: nil)
}
}
I was dismissing the souceViewController which was the very reason it went back to the webView. Sorry for posting such stupid question

Failure to return to calling function from NSURLSession delegate without killing the task

I'm using Swift in Xcode 6.2 (beta) but had the same problem on the 6.1 release version. I'm trying to use NSURLSession and believe I have it set up correctly (see code below). The problem is that I have a delegate setup to deal with a redirect happening through the code. I actually need to capture the cookies prior to the final redirection and I'm doing this through the delegate:
func URLSession(_:NSURLSession, task:NSURLSessionTask, willPerformHTTPRedirection:NSHTTPURLResponse, newRequest:NSURLRequest, completionHandler:(NSURLRequest!) -> Void )
This works and I'm able to execute code successfully and capture the cookies I need. The problem is that I need to add task.cancel() at the end of the function or else it never seems to complete and return to the delegator (parent?) function. Because of this I lose the results from the redirect URL (although in my current project it is inconsequential). The strange thing is that this was working for a while and seemingly stopped. I don't believe I entered any code that changed it, but something had to happen. Below is the relevant code.
NSURLSession Function:
func callURL (a: String, b: String) -> Void {
// Define the URL
var url = NSURL(string: "https://mycorrecturl.com");
// Define the request object (via string)
var request = NSMutableURLRequest(URL: url!)
// Use default configuration
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
// Create the NSURLSession object with default configuration, and self as a delegate (so calls delegate method)
let session = NSURLSession(configuration: config, delegate: self, delegateQueue: nil)
// Change from default GET to POST (needed to call URL properly)
request.HTTPMethod = "POST"
// Construct my parameters to send in with the URL
var params = ["a":a, "b":b] as Dictionary<String, String>
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
// Do some other stuff after delegate has returned...
})
task.resume()
return
}
The delegate code:
func URLSession(_:NSURLSession, task:NSURLSessionTask, willPerformHTTPRedirection:NSHTTPURLResponse, newRequest:NSURLRequest, completionHandler:(NSURLRequest!) -> Void ) {
// Check Cookies
let url = NSURL(string: "https://mycorrecturl.com")
var all = NSHTTPCookie.cookiesWithResponseHeaderFields(willPerformHTTPRedirection.allHeaderFields, forURL: url!)
// Get the correct cookie
for cookie:NSHTTPCookie in all as [NSHTTPCookie] {
if cookie.name as String == "important_cookie" {
NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookie(cookie)
}
}
task.cancel()
}
It used to return to the calling function without calling task.cancel(). Is there anything that looks wrong with the code that would cause it to just hang in the delegate function if task.cancel() isn't called?
Edit: What code would I add to fix this.
If you are not canceling the request, your willPerformHTTPRedirection should call the completionHandler. As the documentation says, this completionHandler parameter is:
A block that your handler should call with either the value of the request parameter, a modified URL request object, or NULL to refuse the redirect and return the body of the redirect response.

Resources