Menu
  • HOME
  • TAGS

Multiple NSURLSessions Causing UITableView Problems

ios,objective-c,uitableview,nsurlsession

Besides assuming that your network requests aren't erroring (you should at least log if there are network errors), there are threading issues. Your NSURLSession callback probably runs on a background thread. This makes it unsafe to call UIKit (aka - [_tableView reloadData]). UIKit isn't thread safe. This means invoking any...

Return object for a method inside completion block

swift,ios8,nsurlsession,completion-block,swift-closures

If you want the MakeGetRequest method to return data obtained via dataTaskWithURL, you can't. That method performs an asynchronous call, which is most likely completed after the MakeGetRequest has already returned - but more generally it cannot be know in a deterministic way. Usually asynchronous operations are handled via closures...

NSURLSessionDataTask when running in background remote notification with content_available =1

ios,background,notifications,push-notification,nsurlsession

A background push will never be delivered if the user has explicitly terminated the app. Apart from that, background pushes were reliable (though not 100% guaranteed) up until 8.1. With iOS 8.1 onwards background pushes are only delivered to the app immediately after being sent if the device is being...

Download large number of files in background in iOS

ios,objective-c,nsurlsession,nsurlsessiondownloadtask

One NSURLSession - because you only want to handle session based things just once (auth for example). One NSOperationQueue - with multiple operations running at the same time. (See property operationCount). It might be a little tricky implementing a NSOperation for the first time, but I'm sure this would be...

NSURLErrorDomain Code=-1001 error when a http post request is sent

ios,swift,nsurlsession,nsurlerrordomain

Apparently my post request was getting a timeout error since I was sending an image that the server would find too large. I scaled down the images in order to make my images acceptable by the server. As this post suggests, NSURLErrorDomain Code=-1001 error might be caused by many things...

How do I get the data from an NSURLSession as a string?

ios,swift,nsurl,nsurlsession

If your problem is that it is empty outside of the task, that is because it is going out of scope after the completion block ends. You need to save it somewhere that has a wider scope. let url = NSURL(string: apiCall) var dataString:String = "" let task = NSURLSession.sharedSession().dataTaskWithURL(url!)...

Setting NSURLRequestCachePolicy and NSURLSession

ios,nsurlsession,nsurlcache

Problem 1: I think my understanding of the NSURLRequestReturnCacheDataElseLoad was incorrect. In this case the response is not cached. Problem 2: From Apple header for NSURLSession in the NSURLSessionAsynchronousConvenience category: data task convenience methods...create tasks that bypass the normal delegate calls for response and data delivery, and provide a simple...

Should we consider transitioning from AFNetworking to NSUrlSession? [closed]

ios,objective-c,afnetworking,nsurlsession

NSURLSession does not reproduce all of the richness of AFNetworking (notably, the construction of complex HTTP requests and the simplified parsing of the responses). So if you're leveraging these features of AFNetworking, then you might want to stay with AFNetworking. For the programmer who is currently using NSURLConnection, though, NSURLSession...

Design simple ios application using NSURLSession

ios,objective-c,ios7.1,nsurlsession

You can use AFNetworking for the API calls.Tutorial explaining in details how to use it the right way.Also you can use NSNotificationCenter to notify the view controller when the call is successful/fail

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

ios,swift,delegates,nsurlsession

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...

NSURLSession dataTaskWithRequest not being called

swift,nsurlsession

Looks like it is firing, I just wasn't waiting long enough. The function returned back to the calling function with no data, but thats because the NSURLSession wasn't finished yet. I guess I'm still getting the hang of the asynchronous nature of NSURLSession.

Basic NSURLSession usage with particular website

ios,swift,post,nsurlsession

Looking at the HTML for the login page, a couple of observations: You might want to confirm the capitalization of the username and password field names. Sometimes web services are case sensitive. If you look at the form in the HTML, there are other fields on the form. You will...

Does NSURLSession Take place in a separate thread?

ios,objective-c,grand-central-dispatch,nsurlsession

Yes, NSURLSession does it's work in a background thread. The download ALWAYS takes place on a background thread. You can control whether it's completion methods are executed on a background thread or not by the queue you pass in in the delegateQueue parameter to the init method. If you pass...

Does NSURLSessionTask keep taskIdentifier after session reconnection?

ios,nsurlsession,nsurlsessiontask

From the results of my own experiments, I can confirm that NSURLSessionTask keeps taskIdentifier after session reconnection.

Accessing the bytes from NSURLSessionDownloadTask as they are downloaded

ios,objective-c,nsurlsession,nsurlsessiondownloadtask

If you want access to the bytes as they're downloaded, you should use data task, not download task. And if you then implement the NSURLSessionDataDelegate methods (specifically, didReceiveData), you can access the bytes, as they're downloaded.

How to get data from website

ios,swift,nsurlsession,foundation

This is simple way 1) Get the html content from the url: you can use - NSURLSession NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:nil delegateQueue:nil]; [[session dataTaskWithURL:[NSURL URLWithString:urlString] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { - NSURLConnection: NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self]; dataWithContentsOfURL: NSData * htmlData = [NSData dataWithContentsOfURL:[NSURL...

AFNetworking 2.0 + UIProgressView how to correctly display progress for an upload session

ios,afnetworking-2,uiprogressview,nsurlsession

Googleing, githubbing, I've found the answer, essentially this is a "feature" of NSURLSession, when you create a session with uploadstream the task takes over on your setted header. Since in a stream there is not a really content size, if we set something the task will rewrite it. Fortunately NSURLSession...

NSURLSession in a loop

iphone,swift,for-loop,nsurlsession,nsdocumentdirectory

The problem is that they are all capturing/sharing the same imageFile variable, as it is declared outside the scope of the for. So first you go over the loop n times, overwriting the imageFile variable with the next filename as you go and firing off an asynchronous download. Then, later,...

Many download tasks

ios,objective-c,xcode,nsurlsession

I do it in this way: #define __ASYNC_BLOCK(code) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), code) #define __UI_THREAD_TASK(code) dispatch_async(dispatch_get_main_queue(), code); and then somewhere in your code you can use like this: ... __ASYNC_BLOCK(^{ // do download... __UI_THREAD_TASK(^{ // update ui }) }); ... EDIT: Look at Tracking Progress section Background Transfer Service in iOS 7...

Inheritance, AFNetworking, Good Practices?

ios,inheritance,nsurl,afnetworking-2,nsurlsession

AFNetworking is a very good library for networking. If you need something more advanced than basic stuff and you don't want to reimplement them by yourself, it is a good (best?) choice. Note that AF 2.0 is not compatible with older versions of OSX and iOS, so pay attention to...

NSURLSession and HTTPS

https,nsurlsession

So I went ahead and installed a self signed certificate on my web server, and then simply changed the HTTP to HTTPS in NSURLRequest and all seems to be working just fine!

AFHTTPSessionManager convenience methods (GET, POST, PUT, etc) and background transfers

ios,afnetworking-2,nsurlsession,background-task

AFNetworking allows you to perform background requests (though be careful to not use any of the task-specific completion blocks and make sure you implement the appropriate app delegate methods; see AFNetworking 2.0 and background transfers). You probably also can use requestWithMethod of AFHTTPRequestSerializer to simplify the process of building the...

Response Headers and URL in AFNetworking

ios,objective-c,cocoa-touch,afnetworking-2,nsurlsession

You are logging the header with the real response : NSLog(@"%@ %@", response, responseObject); You desired response is just the responseObject apparently a dictionary. NSLog(@"%@", responseObject); For example, you can access the "message" doing : NSLog(@"%@", responseObject[@"message"]); Should log : "Test Button"...

Cancel NSURLSession if user taps twice in swift iOS

ios,swift,nsurlsession

This is how I solved the problem. When task.cancel() is performed, the print statement wont be executed. Seems a little hacky to check against a string so if anyone has a better solution I will accept that one. let url = NSURL(string: "http://www.stackoverflow.com") let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error)...

Sending post data nsurlsession

json,swift,post,nsurlsession

As Francisco said, you can create a NSMutableURLRequest and set the HTTPBody. But you should also percent escape the values for username and, more importantly, for password. So, imagine your request being created like so: let config = NSURLSessionConfiguration.defaultSessionConfiguration() config.HTTPAdditionalHeaders = ["Accept" : "application/json", "X-Application" : "<AppKey>", "Content-Type" : "application/x-www-form-urlencoded"]...

NSURLSession not retained when using a category

iphone,objective-c,nsurlsession

The compiler translates self.currentRegion = region; into [self setCurrentRegion:region]; which means that you have an infinite recursion in your setter method - (void)setCurrentRegion:(CLRegion *)region { self.currentRegion = region; } And the same problem occurs in your getter method: - (CLRegion *)currentRegion { return self.currentRegion; } The program then crashes because...

Having issue with multiple file downloads

ios,nsurlsession,nsurlsessiondownloadtask,nsurlsessionconfiguration

When using background sessions, old download requests can persist from session to session. Have you tried checking for old, outstanding background tasks with getTasksWithCompletionHandler? I had a bear of a time until I realized that when my app starts, it can get backlogged behind old background requests. And if you...

How do I convert this curl command to Objective-C?

objective-c,json,curl,nsurlsession,nsurlsessiondatatask

A curl header of 'Authorization: Token token="replace-with-token"' would translate into: [config setHTTPAdditionalHeaders:@{@"Authorization":@"token=\"4959a0bc00a15e335fb6\""}]; ...

How to check if connection has been switched to 3G while app is in background in iOS?

ios,networking,background-process,reachability,nsurlsession

If you just want to make sure downloads only happen on WiFi, then you should set the allowsCellularAccess property of the NSURLSession's NSURLSessionConfiguration to NO. No monitoring, cancelling or other tricks needed: that'll make sure the download never goes over the cellular connection....

Pause,Resume,Cancel Upload Task Using NSURLSession UploadTask

ios,objective-c,ios7,nsurlsession,nsurlsessionuploadtask

I have studied alot but could find nothing .After i tried this on my code assuming this as a download task ,I came to know that we can "pause , resume" upload tasks as well using NSURLSession just we do in downloading tasks. To pause a task simply call [yourUploadTask...

How to download multiple images using same session and different download tasks

ios,xcode,nsurlsession

The code is good as it is the problem was that in my actual code I was making a mistake, on the second resume I was calling the first task.

Set cookies with NSURLSession

ios,session-cookies,nsurlsession

You can probably get away with just using the sharedHTTPCookieStorage for NSHTTPCookieStorage, and then use setCookies:forURL:mainDocumentURL: or the single setCookie: - the latter might be better for your needs. If this doesn't work you might need to setup the NSURLSessionConfiguration and set the NSHTTPCookieStorage The docs don't state it, but...

Does NSURLCache really require initialization as this article indicates?

ios,objective-c,cocoa-touch,nsurlsession,nsurlcache

No. The [NSURLCache sharedURLCache] is set up by iOS. I just ran through the debugger and found that the initial memoryCapacity is 512,000 bytes and the initial diskCapacity is 10,000,000 bytes (for iOS 7.1). The NSHipster article you referenced does seem to imply that you must first initialize the shared...

How to set cookieAcceptPolicy for ephemeral NSURLSession

cookies,nsurlsession,cookiestore

It looks like ephemeral sessions don't store cookies ever. eskimo1 says on the devforums: ISTR that ephemeral session configurations don't work the way that folks expect based on the documentation. I never got around to looking at this in detail but it seems like you have. You should file a...

Swift NSURLSession App crashes on cellular data

ios,xcode,swift,nsurl,nsurlsession

What you're doing is web scraping which is inherently unstable, particularly the way you're doing it. There is no guarantee that the content returned from that url will match up with the precise text you're using to break up the html. You've already found that you get different responses depending...

POST request in swift

api,swift,post,nsurlsession,mashape

Okay incase anyone has the same problem I am going to post the solution. So as @findall pointed out I the correct encoding was not JSON and it was just supposed to be a url encode. But after I changed it to url encode it still was not working. So...

How to use NSURLSession and NSURLRequest to fetch users feeds and update in a tableview for a social networking iOS app?

ios,nsurlrequest,nsurlsession

Your request needs to ask for a specific page or offset of the feed, and your server should handle this. For the first feed, you'd ask for page 0. The server gives you items 1 - 30. At the app end, you keep track of the page you last requested....

Function does not wait until the data is downloaded

swift,nsurlsession

The other answer is not a good replacement for the code you already had. A better way would be to continue using NSURLSession's data tasks to keep the download operation asynchronous and adding your own callback block to the method. You need to understand that the contents of the download...

How do I store one completion handler in a class so that all methods could use it?

objective-c,objective-c-blocks,grand-central-dispatch,nsurlsession

Simply add a Class method that returns this completion handler, this way both other methods can call this one.

Using boundaries to HTTP Post multiple data

ios,swift,http-post,nsurlsession

Two issues You're terminating the body too soon. The --boundary-- syntax is for the end of the body. You are not properly encoding the Category value. So, it should probably look something like: // add category body.appendString("--\(boundary)\r\n") body.appendString("Content-Disposition: form-data; name=\"Category\"\r\n\r\n") body.appendString("\(self.categoryAbbreviations[self.tag])\r\n") // now all done body.appendString("--\(boundary)--\r\n") Frankly, one might consider...

Download images asynchronously and identify which image has downloaded?

ios,core-data,asynchronous,nsurlconnection,nsurlsession

You could get the NSURL from the request in the given connection. From the url you should be able to figure out which image it is.

NSURLCache not working with NSURLSession

ios,swift,nsurlsession,nsurlcache

NSURLCache and NSURLSession currently appear to be buggy at best, and possibly broken. I don't need background downloads or anything like that, so I opted to use Cash: https://github.com/nnoble/Cash . It works perfectly for my needs.

how to pass a dictionary using NSURLSession in post method?

ios,nsurlsession

I solve the problem by using this method, NSError *error; NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil]; NSURL * url = [NSURL URLWithString:[ NSString stringWithFormat:@"http://holla.com/login/save_contact"]];; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; [request...

IOS, Swift, No way to access main thread in NSURLSession

ios,swift,grand-central-dispatch,nsurlsession

What you're trying here seems a bit odd to me. You're dispatching asynchronously from the main thread to the main thread. Usually you dispatch async to perform something concurrently on another thread than the current one so the current thread can go about doing its thing without having to wait...

returning a value from asynchronous call using semaphores

ios,objective-c,asynchronous,nsurlsession,nsurlsessiondatatask

I would suggest cutting the Gordian knot: You should not use semaphores to make an asynchronous method behave synchronously. Adopt asynchronous patterns, e.g. use a completion handler: - (void)loginWithEmail:(NSString *)email password:(NSString*)password completionHandler:(void (^ __nonnull)(NSDictionary *userDictionary, NSError *error))completionHandler { NSString *post = ...; // build your `post` here, making sure to...

How can I reload data in UItableviewCell after I download data for each cell from internet?

ios,uitableview,swift,nsurlsession

You have to update your UI in the main thread. replace this: cell.label.text = "\(self.dataText)" With this: dispatch_async(dispatch_get_main_queue()) { cell.label.text = "\(self.dataText)" } ...

Swift can't send URLRequest at all?

ios,swift,nsurlrequest,nsurlsession

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. See stackoverflow.com/a/25126900/1187415 for an example. You should take the habit to print out everything you get from a request, to...

Converting NSURLSessionDataTask into a Download task with Background support

ios,session,download,nsurlsession

This question is kind of difficult to give a clear answer, seams to me, that all 3 major URLLoading factors (sessionType, taskType, FG/BG creation) are restricted by your designs. Since session keeps a deep-copy on the configuration (which determines default/BackGround/Ephemeral session-nature-type), after initiating your session (in our case: your default-type-Session)...

How to delay method until NSData finishes loading in NSUrlSession?

ios,asynchronous,nsurlsession

So blocks by default are skipped over in execution and queued up (sometimes on other threads). This means when you're returning a variable that you had just set in a block, you should assume the block has not been executed and any variables you set inside it will not be...

Attempting to get authentication from server using Json token in Swift

json,swift,token,nsurlsession

I think here you need a Asynchonous POST Request code below let urlPath: String = "http://api.mip.local/oauth/token" var url: NSURL = NSURL(string: urlPath)! var postData = NSMutableData(data: "username=\(usrName)".dataUsingEncoding(NSUTF8StringEncoding)!) postData.appendData("&password=\(pwd)".dataUsingEncoding(NSUTF8StringEncoding)!) postData.appendData("&grant_type=password".dataUsingEncoding(NSUTF8StringEncoding)!) var request1: NSMutableURLRequest = NSMutableURLRequest(URL: url) request1.HTTPMethod = "POST"...

Getting data from NSURLSessionTaskDelegate

ios,swift,nsurlsession

Most probably the received string data is not UTF8 encoded. Try NSASCIIStringEncoding.

How do I check if dataTaskWithRequest is complete?

ios,swift,closures,nsurlsession

The view controller doesn't need to know when completionHandler is called. All you do is you have completionHandler actually dispatch a tableView.reload() back to the main queue (which then triggers the calling of the UITableViewDataSource methods). It's the completionHandler that initiates the UI update, not the other way around: let...

NSURLSessionTask authentication challenge completionHandler and NSURLAuthenticationChallenge client

ios,nsurlsession,nsurlprotocol,nsurlsessiondatatask

To answer my own question, the answer is no. Moreover, Apple's provided challenge sender does not implement the entire NSURLAuthenticationChallengeSender protocol, thus crashing when client attempts to respond to challenge: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFURLSessionConnection performDefaultHandlingForAuthenticationChallenge:]: unrecognized selector sent to instance 0x7ff06d958410' My solution was...

Delay inside Background Fetch EXEC_BAD_ACCESS

ios,objective-c,nsurlsession,background-fetch

You can't run forever in the background, iOS just doesn't offer you that ability. The crash currently is because you're calling the completion handler multiple times and after it has been invalidated. Basically, you should change your approach, and perhaps your requirement, and use the background processing as prescribed by...

Using NSURLSession from a Swift command line program

osx,swift,nsurlsession,nsrunloop

You can use a semaphore to block the current thread and wait for your URL session to finish. Create the semaphore, kick off your URL session, then wait on the semaphore. From your URL session completion callback, signal the semaphore. You could use a global flag (declare a volatile boolean...

IOS - My Data Usage keeps returning data

ios,objective-c,nsurlsession

As you say, sending a request uses data, even if no results come back. Asking for data every two seconds seems excessive. Maybe just reduce the frequency of checking? Or perhaps you could switch it around so new data is pushed to the client rather than polling like this? Or...

BackGround Downloading speed in ios7

ios7,nsurlsession,nsurldownload

Yes, there may be a speed difference with background transfers. It's difficult to know what that speed difference will be. Once your app is in the background, the NSURLSession background daemon will manage the download to maximise efficiency, depending on several factors, including other data transfers, the network state (Wi-Fi...

Handling sequential downloads with NSURLSession

ios,nsurlsession

Yes, you can just make the additional calls within the completionBlock. But the requests should not be "blocking", but rather you'd just initiate additional asynchronous requests for the additional data. You want them to operate concurrently with respect to each other, if your model supports that. You pay a significant...

Background fetch and background transfers in iOS to download data (JSON) on bakcground

ios,cocoa-touch,ios7,nsurlsession

NSUrlSession supports background fetching of Files only. That is an important consideration in your design. 1) Yes, you need to create a session configuration for background downloads. 2) Not unless you download the data to a file then read the file 3) Background fetch can also be done incrementally in...

How to programmatically add a proxy to an NSURLSession

ios,proxy,nsurlsession,nsurlsessionconfiguration

It turns out, the dictionary keys you want are the Stream variants, they are the ones that resolve down to "HTTPProxy" and such: NSString* proxyHost = @"myProxyHost.com"; NSNumber* proxyPort = [NSNumber numberWithInt: 12345]; // Create an NSURLSessionConfiguration that uses the proxy NSDictionary *proxyDict = @{ @"HTTPEnable" : [NSNumber numberWithInt:1], (NSString...

Is There A Neat Way to Attach a Completion Block to an NSURLSessionDataDelegate Callback in Swift?

ios,swift,nsurlsession,completion-block

What I've done in the past is to create some sort of transaction object. I set up a download manager (as a singleton) to create an array of transaction objects. I make the transaction object the delegate of the URL session (Actually this predates NSURLSession - I did it with...

Swift - session.dataTaskWithURL completionHandler never called

swift,nsurl,nsurlsession

The task never completes because it never gets started. You have to manually start the data task using its resume() method. let urlPath:String = apiURL + apiVersion + url + "?api_key=" + apiKey let url = NSURL(string: urlPath) let session = NSURLSession.sharedSession() let task = session.dataTaskWithURL(url!, completionHandler: {(data, reponse, error)...

NSURLSession label not changing text swift xcode 6

ios,xcode,swift,nsurlsession

Make sure your statusLabel is correctly connected in Interface Builder. If you log the value of the status label, you will likely find nil.

Is there a way to use NSURLProtocol in a NSURLSession with custom config?

swift,nsurlsession,nsurlprotocol

After spending some more hours trying to find out why this wasn't working I found the way of doing it. Instead of: configuration.protocolClasses!.append(MockNetwork) Do: var protocolClasses = [AnyObject]() protocolClasses.append(MockNetwork) let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() configuration.protocolClasses = protocolClasses After that change everything worked and not necessary to NSURLProtocol.registerClass(MockNetwork)...

JSON url response null

ios,objective-c,iphone,json,nsurlsession

Do not convert the JSON to a string: NSString* rawJSON = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; convert it is an object, in this case a NSDictionary NSError = *error; NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; if (dict) { NSLog(@"dict: %@", dict); } else { NSLog(@"error: %@", error); } The JSON...

Swift NSURLSession access delegate within closure

ios,swift,delegates,nsurlsession

Your delegate is not defined. You declare a delegate var of type Optional<APIClientDelegate> but you never sets its value. If you want it to work, you delegate var needs to point to a class that fullfills the requirements set in the protocol for APIClientDelegate....

Return value from asynchronous thread

swift,asynchronous,nsurlsession

That's correct: Your HTTP request is asynchronous, which means that the request runs on a background thread while allowing user interface actions and whatever else to continue running unimpeded on the main thread. In order to get your resulting data you can pass a anonymous callback function as a parameter...

ios table view rows not showing up

ios,nsurlsession

That's an async operation. That means it'll likely occur on a background thread, and UI can't be updated via background threads. Just add a dispatch to the main thread in your success block. self.objects.append(AppModel(id:1, name: "candy crush"])) dispatch_async(dispatch_get_main_queue(), { () -> Void in self.insertRows() }) ...

Image(or video) posting to server in Swift

ios,swift,http-post,nsurlconnection,nsurlsession

If you want to upload image in json body you need to encode it. Suppose you have a UIImage instance image let data = UIImageJPEGRepresentation(image, 0.5) let encodedImage = data.base64EncodedStringWithOptions(.allZeros) Now it is encoded as base64 string. We can use it in json body. let parameters = ["image": encodedImage, "otherParam":...

Swift dataTaskWithRequest completion block not executed

swift,http-post,nsurlsession

Your method is async method,you can not get return from this. You can pass in a block to handle your action with return func postData(url: String, query: NSDictionary,finished:(NSObject)->()) { var error: NSError? var result: NSObject? = nil let dest = NSURL("http://myUrl.com") let request = NSMutableURLRequest(URL: dest!) request.HTTPMethod = "POST" request.HTTPBody...

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

swift,nsurlsession

You can't return data directly from an asynchronous task. The solution is to make a completion handler like this: class PostFOrData { let url = NSURL( string: "http://210.61.209.194:8088/SmarttvWebServiceTopmsoApi/GetReadlist") var picUrl = NSURL(string : "http://210.61.209.194:8088/SmarttvMedia/img/epi00001.png") var responseString : NSString = "" func forData(completion: (NSString) -> ()) { let request = NSMutableURLRequest(...

NSURLSession performSegueWithIdentifier not running

ios,segue,nsurlsession

If you create the NSURLSession object the way you are, it creates a new serial operation queue that is not the main queue. The completion handler of the dataTaskWithURL: method is run on the session's queue, so it's not working because you're trying to do a UI task on a...

Go to another view when NSURLSession finishes its job

swift,viewcontroller,nsurlsession,nsurlsessiondatatask

The problem is that the completion handler code of the dataTaskWithURL method runs in a background secondary thread, not in the main thread (where view controller transition can happen). Wrap the call to pushViewController in a main thread queue closure: ... dispatch_async(dispatch_get_main_queue(), { let navigationVC = self.navigationController navigationVC?.pushViewController(weatherView, animated: false)...

How do I unit test HTTP request and response using NSURLSession in iOS 7.1?

ios,objective-c,nsurlsession,xctest,nsurlsessiontask

Xcode 6 now handles asynchronous tests withXCTestExpectation. When testing an asynchronous process, you establish the "expectation" that this process will complete asynchronously, after issuing the asynchronous process, you then wait for the expectation to be satisfied for a fixed amount of time, and when the query finishes, you will asynchronously...

Set configuration of NSURLSession sharedSession

ios,nsurlsession

Thats because you cannot modify the sharedSession. Imagine as if the sharedSession is the iOS device sharedSession and is used by all other Apps and frameworks. Makes sense for it to be non-configurable right? The documentation about it states: The shared session uses the currently set global NSURLCache, NSHTTPCookieStorage, and...

UI Slow to Update *ONLY* If Called In Response To Change Occurring in NSURLSessionUploadTask Completion Block

ios,objective-c,delegates,nsurlsession,nsurlsessionuploadtask

Use main queue to update the UI. Use following code: - (void)priceDidUpdate:(NSString *)updatedPrice { dispatch_async(dispatch_get_main_queue(), ^() { //Add method, task you want perform on mainQueue //Control UIView, IBOutlet all here NSLog(@"priceDidUpdate delegate notification - updatedPrice is: %@", updatedPrice); [self.deliveryLabel setText:@"N/A"]; [self.priceLabel setText:updatedPrice]; }); } ...

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

json,asynchronous,swift,nsurlsession

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:...

NSURLErrorFailingURLPeerTrustErrorKey in Swift playground

xcode,swift,https,nsurlsession,swift-playground

HTTP Requests are not supported in "normal" iOS Playground: From Xcode release notes: iOS Playgrounds now support displaying animated views with the XCPShowView() XCPlayground API. This capability is disabled by default; it can be enabled by checking the "Run in Full Simulator" setting in the Playground Settings inspector. When the...

NSURL returning nil for certain cases

objective-c,nsurl,nsurlsession

You said: I had to add "\" in front of the apostrophes as is evident from my code because PHP needs to have the " ' " escaped in its URLs. But by doing so, it seems like I've violated some requirement set out for NSURL. What do you guys...

How to make sure NSUrlSession does not fetch cached pages?

ios,nsurlsession

Try to set your NSURLSessionConfiguration's requestCachePolicy to NSURLRequestReloadIgnoringLocalCacheData. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData; NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration]; ...

Function/Code Design with Concurrency in Swift

multithreading,swift,concurrency,nsurlsession

The typical pattern when calling an asynchronous method that has a completionHandler parameter is to use the completionHandler closure pattern, yourself. So the methods don't return anything, but rather call a closure with the returned information as a parameter: func getNames(completionHandler:(NSArray!)->()) { .... let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {data, response, error...

Send NSString as body of post method using NSURLSession

ios,objective-c,nsstring,nsdictionary,nsurlsession

I ended up using the first example that I found here is my implementation: NSURL *url = [NSURL URLWithString:@"MY_LINK/smtg"]; //Create thhe session with custom configuration NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration]; sessionConfiguration.HTTPAdditionalHeaders = @{ @"Authorization" : [NSString stringWithFormat:@"BEARER %@",finalToken], @"Content-Type" : @"application/json" }; NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration]; // 2...

Get Website Data Using Swift

ios,swift,web-scraping,nsurlsession

Here's the full example that works var url = NSURL(string: "http://espn.go.com/golf/leaderboard?tournamentId=2271") if url != nil { let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in print(data) if error == nil { var urlContent = NSString(data: data, encoding: NSASCIIStringEncoding) as NSString! print(urlContent) } }) task.resume() } Looks like...

NSURLRequest lost HTTP header “Authorization” while redirecting the request

objective-c,redirect,http-headers,nsurlrequest,nsurlsession

'Authorization' header is one from the 'special' headers that are advised not to be modified. This is from Apple's documentation (LINK): The NSURLConnection class and NSURLSession classes are designed to handle various aspects >of the HTTP protocol for you. As a result, you should not modify the following headers: Authorization...

swift transition between two views take very long time

swift,view,nsurlsession,transitions,presentviewcontroller

Resolved Yes ! after a long night i have find why my view take too much time to appear after the wiewdidload was executed. it's about thread and NSUrlSession, with NSUrlSession the callback is on the background thread , and like I handle rootview inside, the view is not handled...

If an iOS user is actively adding data to a view, what is the best way to retrieve this from the server?

ios,nsurlsession,nsurlsessiontask

Do two things simultaneously. Send the POST request to make the new item. Add the item to the UITableView Such as: self.listings addObject:myObject]; [self.tableView reloadData]; The best thing to do is to assume that the data was sent successfully, and show the listing in the UITableView as soon as possible....

iOS app: Authentication with server timing out after 20 minutes. Is this normal, and how can I handle it?

ios,iphone,ipad,authentication,nsurlsession

In my situation, what would you do? Fix the damn server, that's what. Or find the person who can fix it and make them fix it. You have a variety of workarounds, but they're all dancing around a problem that could be fixed once and for all. Find out...

Does NSURLSession persist?

ios,objective-c,nsurlsession

NSURLSession was created to make it easier to apply the same settings to http connections. Chances are good that you can just use [NSURLSession sharedSession] without modification. (Modifications might include an ephemeral session so that no data is cached, or a session that adds the same header data to every...

Saving URL data to a variable

ios,swift,nsurlsession,dispatch-async

As is clear in the code you've added under the "More Details" section of your answer, i.e. let task: Void = session.dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in // ... self.spellCorrection = withNewLine.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNew lineCharacterSet()) println(spellCorrection) }).resume() println(self.spellCorrection) by printing self.spellCorrection directly outside of the block, you're attempting to...

iOS and Go - Keep-Alive using NSURLSession

ios,web-services,http,go,nsurlsession

I believe you're confusing TCP keep-alive with HTTP keep-alive (persistent connections). These are unrelated concepts. From your question, you probably mean HTTP persistent connections. In HTTP/1.1, persistent connections are the default and are used by NSURLSession and nearly every HTTP/1.1 client. You have to ask to turn them off. You...

error back when using nsurlsession to access a webservice several times in a for loop

ios,nsurlsession

I put request into for loop, it works. The first thought of rob about NSMutableRequest and NSURLSession seems right, I'm trying to catch the whole idea. Thanks for rob's answer. Anyway, this is code. for (ImageInformation *temp in self.images.imageInfos) { // compose request dynamically NSURL *url = [NSURL URLWithString:@"http://121.199.35.173:8080/xihuan22dcloud/services/Shibietupianservice/serviceGetthetupian"]; NSMutableURLRequest...

Replacing NSURLConnection with NSURLSession

ios,nsurlsession

The answer depends upon whether you need the richness of the various NSURLSession delegate methods or not. If you're ok using the completion block renditions (i.e. no progress callbacks, no streaming, no sophisticated handling of authentication challenges and redirects, etc.), the conversion from NSURLConnection to NSURLSession is pretty trivial. Just...

How do I get the NSURLResponse before the downloadTaskWithURL finishes?

ios,swift,nsurl,nsurlsession

Do not use Shared session Keep a session property,use this function to init. init(configuration configuration: NSURLSessionConfiguration?, delegate delegate: NSURLSessionDelegate?, delegateQueue queue: NSOperationQueue?) -> NSURLSession Then use dataTask to download image In this delegate method you can get Response optional func URLSession(_ session: NSURLSession, dataTask dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler...