FAQ Database Discussion Community


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

ios,afnetworking-2,nsurlsession,background-task
I've built an app around AFNetworking 2.0's AFHTTPSessionManager and its nice HTTP convenience methods. I now need to ensure that all of this networking functionality can run in the background, and I'm rather concerned. Reading Apple's documentation, I can see that data tasks are not supported for background sessions. After...

iOS and Go - Keep-Alive using NSURLSession

ios,web-services,http,go,nsurlsession
In my iOS app, I have a search feature that fetches results from a server. The search updates live as the user updates their query, so this results in several requests being made in succession. So my question is, how can I ensure that TCP keep-alive is being used on...

NSURL returning nil for certain cases

objective-c,nsurl,nsurlsession
I'm creating an NSURL to send as a request to a PHP rest API that I've got setup. Here's my code below: NSMutableString *url = [NSMutableString stringWithFormat:@"http://www.private.com/recievedata.php?item=%@&contact=%@&discovery=%@&summary=%@",__item,__contactDetails,__lostFound,__explain]; //The " ' " in PHP is a special character, so we have to escape it in the URL //The two slashes are...

NSURLSessionDataTask when running in background remote notification with content_available =1

ios,background,notifications,push-notification,nsurlsession
My app is sending notifications (like a chat app) that inform the other app that it needs to fetch the message from the server even when it's not in the foreground. I plan an APN to send notification with Content_available=1 and then have the app to call the server to...

Return value from asynchronous thread

swift,asynchronous,nsurlsession
In a playground file, I have a function which is supposed to return a array where Lesson is a custom data type. In the playground at the right hand of my screen it does display a array with the values that where supposed to be in the array though if...

NSURLSession in a loop

iphone,swift,for-loop,nsurlsession,nsdocumentdirectory
I was hoping to run this code to fetch multiple images from URLs but although the loop runs through every object in my array, the only object that is saved is the final one. Is there a better way to do this? EDIT: It seems that all the images saved...

Setting NSURLRequestCachePolicy and NSURLSession

ios,nsurlsession,nsurlcache
I'm creating an NSURLSession with a sessionConfiguration where I have explicitly set the requestCachePolicy and URLCache. sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration]; sessionConfiguration.requestCachePolicy = NSURLRequestReturnCacheDataElseLoad; sessionConfiguration.URLCache = [NSURLCache sharedURLCache]; A request is created and passed as an argument in NSURLSession dataTaskWithRequest:CompletionHandler: method. The request is constructed like this: request = [NSMutableURLRequest requestWithURL:url...

Getting data from NSURLSessionTaskDelegate

ios,swift,nsurlsession
I'm trying to use NSURLSession with a DataTask and a Delegate but I can't find a way to convert the data obtained by the didReceiveData method into a string. This is the code that I'm using, the problem that I'm experiencing is that I get some data but when I...

Swift dataTaskWithRequest completion block not executed

swift,http-post,nsurlsession
I have a function which posts a dictionary back to the server and return the status code or error content when there's an error. It works fine sometimes, while the rest of the time the completion section is skipped. func postData(url: String, query: NSDictionary) ->NSObject? { var error: NSError? var...

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

ios,uitableview,swift,nsurlsession
I have a tableview with some cells and each cell will get data from internet. my function for my tableviewcell like this: override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("placeCell", forIndexPath: indexPath) as! WeatherTableViewCell ...... //Create Url here... ...... let downloadTask: NSURLSessionDownloadTask = sharedSession.downloadTaskWithURL(url!,...

JSON url response null

ios,objective-c,iphone,json,nsurlsession
I write an application for iphone in objective-c and wanna get data from json. but I get null from url, but url is correct and when I pass url to browser I see the json data. this is my IBAction method: - (IBAction)checkMobileNumber:(id)sender { NSString *prefix = self.prefixTextField.text; NSString *number...

Using NSURLSession from a Swift command line program

osx,swift,nsurlsession,nsrunloop
I'm trying to test a little proof-of-concept command line app prior to integrating it into a larger app. What I'm trying to do is download some data using NSURLSession using this example. However it appears that if I use the examples given in a simple OS X command line app...

How do I get the NSURLResponse before the downloadTaskWithURL finishes?

ios,swift,nsurl,nsurlsession
This is my code for download : let url = NSURL(string:"http://www.zastavki.com/pictures/originals/2013/Photoshop_Image_of_the_horse_053857_.jpg")! let documentsDirectoryURL = NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first as! NSURL NSURLSession.sharedSession().downloadTaskWithURL(url, completionHandler: { (location, response, error) -> Void in if let error = error { println(error.description) } else { println("Finished downloading \"\(response.suggestedFilename)\".") println(location.path!)...

Delay inside Background Fetch EXEC_BAD_ACCESS

ios,objective-c,nsurlsession,background-fetch
I am creating an application that works in background mode (minimized), and every 90 seconds it performs a certain method that checks some information on a server. The code is this: AppDelegate.m - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { ... [[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum]; ... } -(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void...

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

ios,swift,nsurl,nsurlsession
I'm using an API that gives me data in a neat format - How do I get this as a String? I can print it, but saving it as a string doesn't seem to work. I specifically want to update a UI element using the data from the NSURLSession task....

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
Supposing I have a class with class methods only and within a method I have two NSURLSessionDataTask / NSURLSessionUploadTask instances which have a completion handler like this: ^(NSData *responseData, NSURLResponse *response, NSError *error){ //here parsing the response etc. } which are 100% identical for both tasks. What's the best way...

Get Website Data Using Swift

ios,swift,web-scraping,nsurlsession
I am trying to use a NSURLSession to pull some data from espn, but I can't seem to get it to work. It prints only nil. I've tested this method with another page on their website and it worked, but I can't get it to work with the one in...

Swift - session.dataTaskWithURL completionHandler never called

swift,nsurl,nsurlsession
I have the following code : let urlPath:String = apiURL + apiVersion + url + "?api_key=" + apiKey let url = NSURL(string: urlPath) let session = NSURLSession.sharedSession() println(url!) let task = session.dataTaskWithURL(url!, completionHandler: {(data, reponse, error) in println("Task completed") // rest of the function... }) The completionHandler function is never...

Response Headers and URL in AFNetworking

ios,objective-c,cocoa-touch,afnetworking-2,nsurlsession
I am using AFNetworking to upload video and Image to a server. NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:urlString parameters:dictParams constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { [formData appendPartWithFileData:imgData name:@"photo" fileName:@"photo.jpg" mimeType:@"image/jpeg"]; [formData appendPartWithFileData:[NSData dataWithContentsOfFile:pathVideo] name:@"video" fileName:@"video.mp4" mimeType:@"video/mp4"]; } error:nil];...

Send NSString as body of post method using NSURLSession

ios,objective-c,nsstring,nsdictionary,nsurlsession
I am trying to post a string to a server using the next example: // 1 NSURL *url = [NSURL URLWithString:@"YOUR_WEBSERVICE_URL"]; NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; NSURLSession *session = [NSURLSession sessionWithConfiguration:config]; // 2 NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url]; request.HTTPMethod = @"POST"; // 3 NSDictionary *dictionary = @{@"key1": @"value1"}; NSError...

How do I check if dataTaskWithRequest is complete?

ios,swift,closures,nsurlsession
I'm new to iOS programming and trying to create my first app. I am fetching some data from a server using var task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in I understand that all code in the completionHandler closure is executed when the task is completed. From...

How to make sure NSUrlSession does not fetch cached pages?

ios,nsurlsession
I'm using NSUrlSession to download the contents of an HTML page (so I can parse it, against my will). My problem is that iOS seems to be caching the page with my app, so that even if I update this page on the server, my app keeps seeing the old...

Accessing the bytes from NSURLSessionDownloadTask as they are downloaded

ios,objective-c,nsurlsession,nsurlsessiondownloadtask
In my app I'm currently using an NSURLSessionDownloadTask to fetch a file via HTTP. This class provides a useful delegate interface to monitor its progress and getting the bytes once the download completes via NSURLSessionDownloadDelegate, however I have not been able to find any way to access the bytes as...

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

ios,objective-c,delegates,nsurlsession,nsurlsessionuploadtask
The app interacts with php scripts on my server. A user can create a booking, and details are written to a database. Subsequently, they can cancel that booking. Within the app, a booking is an object, responsible for gathering its own details from the server. A booking can also cancel...

Does NSURLSession Take place in a separate thread?

ios,objective-c,grand-central-dispatch,nsurlsession
I was designing an app that uses NSURLSession and thinking about putting it in a different thread with Grand Central Dispatch, but if NSURLSession automatically does that in the background, I wouldn't have to use GCD then, correct? So in other words, does NSURLSession automatically use Grand Central Dispatch in...

Why is NSURLSession slower than cURL when downloading many files?

ios,nsurlsession
I've been using cURL to download about 1700+ files -- which total to about ~290MB -- in my iOS app. It takes about 5-7 minutes on my Internet connection to download all of them using cURL. But since not everyone has fast internet connection (especially when on the go), I...

Basic NSURLSession usage with particular website

ios,swift,post,nsurlsession
I'm nearly embarrassed to ask, but I'm trying to build a little app for myself and I'm stumbling with the intricacies of web technologies. It's not the Swift I need help with, more so the methodology... I'm trying to sign in here programatically https://account.tfl.gov.uk/oyster It's just UK website that lets...

Cancel NSURLSession if user taps twice in swift iOS

ios,swift,nsurlsession
Im using NSURLSession which is preferred according to this thread. How to make an HTTP request in Swift? let url = NSURL(string: "http://www.stackoverflow.com") let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in println(NSString(data: data, encoding: NSUTF8StringEncoding)) } task.resume() My only problem is when user taps twice and I want to cancel...

Multiple NSURLSessions Causing UITableView Problems

ios,objective-c,uitableview,nsurlsession
I'm running into a bit of a strange problem here. One of my NSURLSessions is in charge of getting information for restaurant information that I have stored (restaurant name, restaurant's logo URL, etc), and then the second NSURLSession is in charge of using the restaurant's logo URL to retrieve the...

Attempting to get authentication from server using Json token in Swift

json,swift,token,nsurlsession
I'm adding a Login process in my Swift app and have added the following code to handle the Json token authentication class func getValidationFromServer(success: ((svrData: NSData!) -> Void)) { var usrName = ViewController.gVariables.gUser var pwd = ViewController.gVariables.gPwd var postData = NSMutableData(data: "username=\(usrName)".dataUsingEncoding(NSUTF8StringEncoding)!) postData.appendData("&password=\(pwd)".dataUsingEncoding(NSUTF8StringEncoding)!)...

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

ios,swift,nsurlsession,completion-block
OK, here's the deal: I have a URL call I'm making in a Swift app, sort of like so: /*! @brief Tests a given Root Server URL for validity @discussion What we do here, is append "/client_interface/serverInfo.xml" to the given URI, and test that for validity. @param inURIAsAString This contains...

Using NSURLSession to play remote audio, code critique

ios,avaudioplayer,nsurlsession
First, to avoid posting a great deal of code on here, I have created a very basic example of what I am after - https://github.com/opheliadesign/AudioTest. I am brand new to iOS development and I'm having a little trouble understanding the best way to load and play a static MP3 file...

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

ios,swift,grand-central-dispatch,nsurlsession
I am creating an iOS app using swift. I would like to achieve some GET or POST HTTP request. I know that Alamofire exists but i want to create my own functions. What I have done : import Foundation class DatabaseRequest:NSObject{ class func GET(urlAsString:String, completion : (response:NSURLResponse, result:AnyObject?, error:String?)-> Void){...

Saving URL data to a variable

ios,swift,nsurlsession,dispatch-async
So I am trying to get a simple string of data back from a RESTful API. Here is what a response looks like: Hello It is not formatted in XML or JSON or anything just a simple string because only one word is being passed back at a time. So...

POST request in swift

api,swift,post,nsurlsession,mashape
Okay I have looked high and low and can not find the answer. So I am just trying to make a simple POST request to a mashape api from an iPhone app. Here is what I have so far: var headers: NSDictionary = ["X-Mashape-Key": "Hm5NokCvUamshPFfnQCRJKne3UuCp1C******************", "Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json"] var...

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

swift,nsurlsession,nsurlprotocol
I have a NSURLSession that runs in a background queue. I'm adding my NSURLProtocol subclass to the NSURLsessionConfiguration.protocolClases but the override class func canInitWithRequest(request: NSURLRequest) -> Bool never gets called. This is how I'm adding my NSURLProtocol let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() configuration.protocolClasses!.append(MockNetwork) urlSession = NSURLSession(configuration: configuration, delegate: self, delegateQueue: operationQueue)...