1

I am trying to do 2 HTTP requests in the first request i will get a var that will be used in the second request. My problem is when I do it using the code below it just runs the second request without running the first.

    let url = NSURL(string:"https://loginurl")
    let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
    let request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 2.0)
    request.HTTPMethod = "POST"

    let contentType = " application/x-www-form-urlencoded"
    NSURLProtocol.setProperty(contentType, forKey: "Content-Type", inRequest: request)

    var dataString = "user details"
    var requestBodyData = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
    request.HTTPBody = requestBodyData

    NSURLProtocol.setProperty(requestBodyData!.length, forKey: "Content-Length", inRequest: request)

    var response: NSURLResponse?
    let session = NSURLSession.sharedSession()


    var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in

 //code for getting the session id to be used in the second request

    })
    task.resume()

    let url2 = NSURL(string:"http://url2?sessionid")
    let request2 = NSMutableURLRequest(URL: url2!, cachePolicy: cachePolicy, timeoutInterval: 2.0)
    request2.HTTPMethod = "GET"
     dataString=""
     requestBodyData = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
    request2.HTTPBody = requestBodyData
    NSURLProtocol.setProperty(contentType, forKey: "Content-Type", inRequest: request2)

      task = session.dataTaskWithRequest(request2, completionHandler: {data, response, error -> Void in


     })

    task.resume()

Can anybody explain what can be wrong with this code

Problem 2:

 let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in

        if let httpRes = response as? NSHTTPURLResponse {
            let html = NSString(data:data!, encoding:NSUTF8StringEncoding)


            if let match = html?.rangeOfString("(?<=sessionid=')[^\';]+", options: .RegularExpressionSearch)  {
                portalid = (html?.substringWithRange(match))!


            }

        }

When I run in simulator it works without issues but when I debug it on iPhone it crashes showing this error "Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFString substringWithRange:]: Range {9223372036854775807, 0} out of bounds; string length 52427'" Thanks

Seif Hatem
  • 1,433
  • 2
  • 12
  • 20

1 Answers1

1

Here is code sample which makes two requests:

//: Playground - noun: a place where people can play

import UIKit
import XCPlayground

XCPlaygroundPage.currentPage.needsIndefiniteExecution = true

let session = NSURLSession.sharedSession()

session.dataTaskWithURL(NSURL(string: "http://www.google.com")!, completionHandler: { (data :NSData?, response :NSURLResponse?, error :NSError?) -> Void in

        let res = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print(res!)

        // make a new request here
        let innerSession = NSURLSession.sharedSession()

    innerSession.dataTaskWithURL(NSURL(string: "http://www.google.com")!, completionHandler: { (data :NSData?, response :NSURLResponse?, error :NSError?) -> Void in

        let res = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print(res!)


    }).resume()


    }).resume()
azamsharp
  • 19,710
  • 36
  • 144
  • 222