Dimuth
Dimuth

Reputation: 752

Use Post request response string in another method Swift

I am trying to use response of the post request in prepareForSegue function. i want to assign response value to destination viewController property. i can not do that because when i assign it in side closure brackets, does not assign before view the new window. because inside the closure code read, after view the new window.

as well as i try to assign saveInvoice function assign to a variable and use within prepareForSegue function. but that variable is NSUrlSessionDataTask type, so i could not use it further.

bellow i have mentioned my code segment

calling function

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    let previewVC :PreviewViewController = segue.destinationViewController as! PreviewViewController

    previewVC.invoiceSummary = "test hash key"

    let invoiceSave = saveInvoice({ hash_key in
        print(hash_key)
        let test = hash_key
        if test != ""
        {
            print("Success")
        }
        previewVC.sendersName = "sender view controller name"
        })

    print(invoiceSave)
}

This is the function which handdle the post request

func saveInvoice(completionHandler: (NSString) -> Void) -> NSURLSessionDataTask
{
    let invoiceSummary = "Sample invoice summary"
    let invoiceDate = "2015-11-20"
    let invoiceConnectionID = "647193"

    //let json = ["summary": invoiceSummary, "date": invoiceDate, "business_id": invoiceConnectionID]
    let json = NSMutableDictionary()

    json.setValue(invoiceSummary, forKey: "summary")
    json.setValue(invoiceDate, forKey: "2015-11-20")
    json.setValue(invoiceConnectionID, forKey: "business_id")

    let data = try? NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions(rawValue: 0));

    let request = NSMutableURLRequest(URL: NSURL(string: "https://livetest.somedomain.com/api/invs?auth_token=jmkm6ijijejf23kmkdd")!)

    request.HTTPMethod = "POST"
    request.addValue("application/json",forHTTPHeaderField: "Content-Type")
    request.addValue("application/json",forHTTPHeaderField: "Accept")
    request.HTTPBody = data

    var outer = ""
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
        data, response, error in

        let responceJSon = JSON(data: data!)

        //let text = self.passJson(responceJSon)

        let invoice = responceJSon["invoice"]

        let hash_key = invoice["hash_key"].stringValue
        let statement_number = invoice["statement_no"].stringValue
        let statement_summary = invoice["summary"].stringValue
        let statement_date = invoice["date"].stringValue

        let obj = ["hash_key": hash_key, "statement_no": statement_number, "summary": statement_summary, "date": statement_date]
        self.invObject.append(obj)


        //self.invObject.append(text as! [String : String])
        outer = self.invObject[0]["statement_no"]!
        print(outer)

        if let hash_key = invoice["hash_key"].string{

            completionHandler(hash_key)
            return
        }


    }
    task.resume()
    return task
}

Upvotes: 1

Views: 160

Answers (1)

Moriya
Moriya

Reputation: 7906

First of all the saveInvoice executes asynchronously so you won't have the value when the next controller loads but a while after.

To save the variable you need to do that inside the completion block. I guess it's the hash_key that is of interest here?

so you would instead do something like this

saveInvoice({ hash_key in
    previewVC.hash_key = hash_key
    previewVC.sendersName = "sender view controller name"
})

However, as mentioned above this executes asynchronously so I rather think it would be better to start the save and then execute the segue programatically when the completion handler is called from within saveInvoice

saveInvoice({ hash_key in
    savedHashKey = hash_key
    self.performSegueWithIdentifier(segueName, sender: self)
})

and then in prepareForSegue

let savedHashKey:String? = nil

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    let previewVC :PreviewViewController = segue.destinationViewController as! PreviewViewController

    previewVC.invoiceSummary = savedHashKey
    savedHashKey = nil
}

Upvotes: 1

Related Questions