-3
  func data_request(){
  let url:NSURL = NSURL(string: url_to_request)!
  let session = URLSession.shared
  let request = NSMutableURLRequest(url: url as URL)
//request.addValue("application/json", forHTTPHeaderField: "Content-Type")
//request.addValue("application/json", forHTTPHeaderField: "Accept")
request.httpMethod = "POST"
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
//let paramString = "data=Hello"
let paramStrings = paramString
request.httpBody = paramStrings.data(using: String.Encoding.utf8)
  let task = session.dataTask(with: request as URLRequest) { ( data,   response, error) in
    guard let :NSData = data as NSData?, let :URLResponse = response , error   == nil else {
        // print("error") //
        return //
    }
    let dataString = NSString(data: data!, encoding:          String.Encoding.utf8.rawValue)
    print(dataString)


};

  task.resume()

}

how do i get the return value datastring in another view ?? how do i pass this value..iam a beginner in ios..plshelp ....thanks in advance

sdpkm
  • 1
  • 2

1 Answers1

0

Using block you can do this

For Swift. Use AnyObject for id objc type.

func callWebservice (serviceName: String, withMethod method: String, andParams params: NSDictionary, showLoader loader: Bool, completionBlockSuccess aBlock: ((AnyObject) -> Void), andFailureBlock failBlock: ((AnyObject) -> Void)) {
    if loader {
        // Show loader
    }

    performRequestWithServiceName(serviceName, method: method, andParams: params, success: aBlock, failure: failBlock)
}

func performRequestWithServiceName(serviceName: String, method methodName: String, andParams params: NSDictionary, success successBlock: ((AnyObject) -> Void), failure failureBlock: ((AnyObject) -> Void)) {
    if callSuceess {
        successBlock("Success")
    }else {
        successBlock(nil)
    }
}

An example when you want call web service. See code below

callWebservice("your-service-name", withMethod: "your-method", andParams: ["your-dic-key": "your dict value"], showLoader: true/*or false*/, completionBlockSuccess: { (success) -> Void in
    // your successful handle
}) { (failure) -> Void in
    // your failure handle
}

from :https://stackoverflow.com/a/31491077/3901620

Community
  • 1
  • 1
KKRocks
  • 8,222
  • 1
  • 18
  • 84
  • it is the same here http://stackoverflow.com/questions/34017897/show-json-data-in-a-tableview-with-swift/34018245#34018245 – Nguyen Hoan Oct 24 '16 at 11:09
  • thanks KKRocks...but i actually want the return value in another view controller...iam able to print it in the same function...how do i pass the value ?? – sdpkm Oct 25 '16 at 05:14
  • you can call this method any class you want . – KKRocks Oct 25 '16 at 05:25