1

This might be a stupid question, but I have some issues changing my code to avoid some deprecated code in iOS9.

I have created an app that logs in to a webpage. The webpage uses a username and a password which forwards to a page where a token has to be entered.

I have been able to login to that webpage by using three urls that have been loaded synchronously in a for-loop. Here is a quick example of the process:

let urls = ["www.testpage.com", "www.testpage.com/username=erik&password=123", "www.testpage.com/token=123456"]

for (index, url) in urls.enumerate() {

     self.urlRequest = NSMutableURLRequest(URL: urlObject.baseUrl, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 30.0)

     NSURLConnection.sendSynchronousRequest(self.urlRequest, returningResponse: &response)

     if index == 2 {
          print("Login successful")
     }
}

This has worked just fine as the synchronous request has triggered on url at a time in correct sequence.

I am now having trouble achieving the same thing with dataTaskWithRequest as the last url sometimes triggeres before the first one has finished.

Do you have any recommendations of how to do this correctly?

Appreciate any help!

Regards, Erik

fisher
  • 1,286
  • 16
  • 29
  • See my answer here: http://stackoverflow.com/a/33205098/341994 – matt Feb 04 '16 at 12:08
  • Thanks @matt! I'll take a look at it! – fisher Feb 04 '16 at 12:10
  • @fisher did you get a 1:1 drop in solution without blocks, async_dispatchs etc, just a function which does a http-get , blocks the current thread and then returns ? – Leo Sep 02 '16 at 16:02

1 Answers1

-1

Don't do that. Instead, do something like this:

let index: UInt = 0

self.beginRequest(index, urls);

and then write a Swift version of this:

- (void) beginRequestAtIndex: (NSUInteger) index inArray:(NSArray *)URLs {
    NSURL *URL = URLs[index];
    NSURLRequest *req = [NSURLRequest requestWithURL:URL];
    // Configure request here.

    NSURLSession *session = self.myURLSession;

    NSURLSessionDataTask *task = [session dataTaskWithRequest:req
                                            completionHandler:^(NSData *data,
                                                    NSURLResponse *response,
                                                    NSError *error))completionHandler {

        if (++index >= [URLs count]) {
          print("Login successful")
        } else {
          dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)),
                         dispatch_get_main_queue(), ^{
              [self beginRequestAtIndex:index inArray: URLs];
          });

          print("Login successful")
        }
    }];

}

In other words, when one request completes (in the completion handler block), begin the next one. Repeat until done. But do this using method calls from the callback block, not loops and synchronous requests.

dgatwood
  • 10,129
  • 1
  • 28
  • 49