Guest User

Untitled

a guest
Sep 27th, 2018
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.68 KB | None | 0 0
  1. @IBOutlet var nameLabel : UILabel!
  2. var finalString: String = "test"
  3.  
  4. override func viewDidLoad() {
  5. super.viewDidLoad()
  6. // Do any additional setup after loading the view, typically from a nib.
  7. }
  8.  
  9. override func didReceiveMemoryWarning() {
  10. super.didReceiveMemoryWarning()
  11. // Dispose of any resources that can be recreated.
  12. }
  13.  
  14. @IBAction func helloWorldAction(nameTextField: UITextField) {
  15.  
  16.  
  17. //fetch data from server
  18. let request = NSMutableURLRequest(URL: NSURL(string: "http://192.168.1.11")!)
  19. request.HTTPMethod = "POST"
  20. let postString = "user=test&pass=test3"
  21. request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
  22. let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
  23. data, response, error in
  24.  
  25. //error handeling
  26. if error != nil {
  27. println("error=(error)")
  28. return
  29. }
  30.  
  31. let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
  32. self.finalString = String(responseString!)
  33. println("(self.finalString)");
  34. }
  35. task.resume()
  36.  
  37. //print finalString
  38. println("finalString = (finalString)")
  39.  
  40. }
  41.  
  42. }
  43.  
  44. import UIKit
  45.  
  46. class ViewController: UIViewController {
  47. @IBOutlet weak var nameLabel: UITextField!
  48.  
  49. // you have to add a completion block to your asyncronous request
  50. func fireRequest(link:String,completion: ((data: NSData?) -> Void)) {
  51. if let requestUrl = NSURL(string: link){
  52. let request = NSMutableURLRequest(URL: requestUrl)
  53. request.HTTPMethod = "POST"
  54. let postString = "user=test&pass=test3"
  55. request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
  56. NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in
  57. completion(data: NSData(data: data))
  58. if let error = error {
  59. println("error=(error)")
  60. return
  61. }
  62.  
  63. }.resume()
  64. }
  65. }
  66. override func viewDidLoad() {
  67. super.viewDidLoad()
  68. println("Fired request" + NSDate().description )
  69. fireRequest("http://192.168.1.11") { data in
  70. dispatch_async(dispatch_get_main_queue()) {
  71. println("Finished request")
  72. if let data = data { // unwrap your data (!= nil)
  73. let myResponseStr = NSString(data: data, encoding: NSUTF8StringEncoding) as String
  74. self.nameLabel.text = myResponseStr
  75. println("response:"+myResponseStr)
  76. }
  77. }
  78. }
  79. }
  80. override func didReceiveMemoryWarning() {
  81. super.didReceiveMemoryWarning()
  82. }
  83. }
Add Comment
Please, Sign In to add comment