Posted By

chrisaiv on 02/10/16


Tagged

ios swift swiftlant


Versions (?)

Simple GET Request


 / Published in: Objective C
 

A simple GET request using Swift

  1. //: Playground - noun: a place where people can play
  2.  
  3. import UIKit
  4.  
  5. class Test {
  6.  
  7. init(path:String){
  8. getRequest(path)
  9. }
  10.  
  11. func getRequest(path:String){
  12. let operationQueue:NSOperationQueue = {
  13. let operationQueue = NSOperationQueue()
  14. operationQueue.name = "com.chrisjmendez.queue"
  15. operationQueue.maxConcurrentOperationCount = 1
  16. return operationQueue
  17. }()
  18.  
  19. //A. Craft a GET Request
  20. let url = NSURL(string: path)
  21. let urlRequest = NSMutableURLRequest(URL: url!)
  22. urlRequest.HTTPMethod = "GET"
  23. //B. Send a GET Reqest
  24. NSURLConnection.sendAsynchronousRequest(urlRequest, queue: operationQueue) { (response, responseData, error) -> Void in
  25. print("!", response)
  26. //C. Convert JSON to NSArray
  27. if error != nil {
  28. print("error", error?.localizedDescription)
  29. }
  30. if let data = responseData{
  31. print("data", data)
  32. }
  33. }
  34. }
  35. func parseResponse(json:NSArray){
  36. print(json)
  37. }
  38. }
  39.  
  40. let test = Test(path: "http://geni.us/youcouldbemine")
  41.  
  42.  
  43. extension String {
  44. /// Percent escape value to be added to a URL query value as specified in RFC 3986
  45. /// - returns: Return precent escaped string.
  46. func stringByReplacingSpaceWithPlusEncodingForQueryValue() -> String? {
  47. let term = self.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil)
  48.  
  49. // Anything which is not URL-friendly is escaped
  50. let escapedTerm = term.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
  51. return escapedTerm
  52. }
  53. }
  54.  
  55. extension Double {
  56. func toStringWithDecimalPlaces(numberOfDecimalPlaces:Int) -> String {
  57. return String(format:"%."+numberOfDecimalPlaces.description+"f", self)
  58. }
  59. }

Report this snippet  

You need to login to post a comment.