How do I make an HTTP request in Swift?

前端 未结 20 1067
不知归路
不知归路 2020-11-22 05:10

I read The Programming Language Swift by Apple in iBooks, but cannot figure out how to make an HTTP request (something like cURL) in Swift. Do I need to import Obj-C classes

相关标签:
20条回答
  • 2020-11-22 06:04

    I have done HTTP Request Both methods GET & POST with JSON Parsing this way:

    on viewDidLoad():

    override func viewDidLoad() {
    super.viewDidLoad()
    
        makeGetRequest()
        makePostRequest()
    
    }
    
    func makePostRequest(){
    
        let urlPath: String = "http://www.swiftdeveloperblog.com/http-post-example-script/"
        var url: NSURL = NSURL(string: urlPath)!
        var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
    
        request.HTTPMethod = "POST"
        var stringPost="firstName=James&lastName=Bond" // Key and Value
    
        let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)
    
        request.timeoutInterval = 60
        request.HTTPBody=data
        request.HTTPShouldHandleCookies=false
    
        let queue:NSOperationQueue = NSOperationQueue()
    
        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in
            var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
            let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary
    
             if (jsonResult != nil) {
                // Success
               println(jsonResult)
    
               let message = jsonResult["Message"] as! NSString
    
               println(message)
             }else {
                // Failed
                println("Failed")
            }
    
        })
    
    }
    
    func makeGetRequest(){
        var url : String = "http://api.androidhive.info/contacts/"
        var request : NSMutableURLRequest = NSMutableURLRequest()
        request.URL = NSURL(string: url)
        request.HTTPMethod = "GET"
        request.timeoutInterval = 60
    
        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in
            var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
            let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary
    
            if (jsonResult != nil) {
                // Success
                println(jsonResult)
    
                let dataArray = jsonResult["contacts"] as! NSArray;
    
                for item in dataArray { // loop through data items
    
                    let obj = item as! NSDictionary
    
                    for (key, value) in obj {
    
                        println("Key: \(key) - Value: \(value)")
    
                        let phone = obj["phone"] as! NSDictionary;
    
                        let mobile = phone["mobile"] as! NSString
                        println(mobile)
                        let home = phone["home"] as! NSString
                        println(home)
                        let office = phone["office"] as! NSString
                        println(office)
                    }
                }
    
            } else {
                // Failed
                println("Failed")
            }
    
        })
    }
    

    Done

    0 讨论(0)
  • 2020-11-22 06:06

    Basic Swift 3+ Solution

    guard let url = URL(string: "http://www.stackoverflow.com") else { return }
    
    let task = URLSession.shared.dataTask(with: url) { data, response, error in
    
      guard let data = data, error == nil else { return }
    
      print(NSString(data: data, encoding: String.Encoding.utf8.rawValue))
    }
    
    task.resume()
    
    0 讨论(0)
提交回复
热议问题