Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @IBOutlet var nameLabel : UILabel!
- var finalString: String = "test"
- override func viewDidLoad() {
- super.viewDidLoad()
- // Do any additional setup after loading the view, typically from a nib.
- }
- override func didReceiveMemoryWarning() {
- super.didReceiveMemoryWarning()
- // Dispose of any resources that can be recreated.
- }
- @IBAction func helloWorldAction(nameTextField: UITextField) {
- //fetch data from server
- let request = NSMutableURLRequest(URL: NSURL(string: "http://192.168.1.11")!)
- request.HTTPMethod = "POST"
- let postString = "user=test&pass=test3"
- request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
- let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
- data, response, error in
- //error handeling
- if error != nil {
- println("error=(error)")
- return
- }
- let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
- self.finalString = String(responseString!)
- println("(self.finalString)");
- }
- task.resume()
- //print finalString
- println("finalString = (finalString)")
- }
- }
- import UIKit
- class ViewController: UIViewController {
- @IBOutlet weak var nameLabel: UITextField!
- // you have to add a completion block to your asyncronous request
- func fireRequest(link:String,completion: ((data: NSData?) -> Void)) {
- if let requestUrl = NSURL(string: link){
- let request = NSMutableURLRequest(URL: requestUrl)
- request.HTTPMethod = "POST"
- let postString = "user=test&pass=test3"
- request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
- NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in
- completion(data: NSData(data: data))
- if let error = error {
- println("error=(error)")
- return
- }
- }.resume()
- }
- }
- override func viewDidLoad() {
- super.viewDidLoad()
- println("Fired request" + NSDate().description )
- fireRequest("http://192.168.1.11") { data in
- dispatch_async(dispatch_get_main_queue()) {
- println("Finished request")
- if let data = data { // unwrap your data (!= nil)
- let myResponseStr = NSString(data: data, encoding: NSUTF8StringEncoding) as String
- self.nameLabel.text = myResponseStr
- println("response:"+myResponseStr)
- }
- }
- }
- }
- override func didReceiveMemoryWarning() {
- super.didReceiveMemoryWarning()
- }
- }
Add Comment
Please, Sign In to add comment