[ios] 如何在Swift中创建HTTP请求?



5 Answers

您可以像在Objective-C中通常那样使用URLURLRequestURLSessionNSURLConnection 。 请注意,对于iOS 7.0及更高版本,首选URLSession

使用URLSession

URLSession初始化URL对象和URLSession 。 然后用resume()运行任务。

let url = URL(string: "http://www.stackoverflow.com")

let task = URLSession.shared.dataTask(with: url!) {(data, response, error) in
    print(NSString(data: data!, encoding: String.Encoding.utf8))
}

task.resume()

使用NSURLConnection

首先,初始化一个URL和一个URLRequest

let url = URL(string: "http://www.stackoverflow.com")
let request = URLRequest(URL: url!)
request.HTTPMethod = "POST" 

然后,您可以通过以下方式异步加载请求:

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
    print(NSString(data: data!, encoding: NSUTF8StringEncoding))
}

或者你可以初始化一个NSURLConnection

let connection = NSURLConnection(request: request, delegate:nil, startImmediately: true)

只要确保将您的代理设置为nil并使用委托方法来处理收到的响应和数据。

有关更多详细信息,请查看NSURLConnectionDataDelegate协议文档

在Xcode操场上测试

如果您想在Xcode操场上试用此代码,请将import XCPlayground添加到您的操场,以及以下呼叫:

XCPSetExecutionShouldContinueIndefinitely()

这将允许您在游戏场中使用异步代码。

Question

我在iBooks上看过Apple编程语言Swift,但无法弄清楚如何在Swift中创建一个http请求(类似CURL)。 我需要导入Obj-C类吗?还是只需要导入默认库? 还是不可能基于本机swift代码创建HTTP请求?




 var post:NSString = "api=myposts&userid=\(uid)&page_no=0&limit_no=10"

    NSLog("PostData: %@",post);

    var url1:NSURL = NSURL(string: url)!

    var postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!

    var postLength:NSString = String( postData.length )

    var request:NSMutableURLRequest = NSMutableURLRequest(URL: url1)
    request.HTTPMethod = "POST"
    request.HTTPBody = postData
    request.setValue(postLength, forHTTPHeaderField: "Content-Length")
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.setValue("application/json", forHTTPHeaderField: "Accept")

    var reponseError: NSError?
    var response: NSURLResponse?

    var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)

    if ( urlData != nil ) {
        let res = response as NSHTTPURLResponse!;

        NSLog("Response code: %ld", res.statusCode);

        if (res.statusCode >= 200 && res.statusCode < 300)
        {
            var responseData:NSString  = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!

            NSLog("Response ==> %@", responseData);

            var error: NSError?

            let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary

            let success:NSInteger = jsonData.valueForKey("error") as NSInteger

            //[jsonData[@"success"] integerValue];

            NSLog("Success: %ld", success);

            if(success == 0)
            {
                NSLog("Login SUCCESS");

                self.dataArr = jsonData.valueForKey("data") as NSMutableArray
                self.table.reloadData()

            } else {

                NSLog("Login failed1");
                ZAActivityBar.showErrorWithStatus("error", forAction: "Action2")
            }

        } else {

            NSLog("Login failed2");
            ZAActivityBar.showErrorWithStatus("error", forAction: "Action2")

        }
    } else {

        NSLog("Login failed3");
        ZAActivityBar.showErrorWithStatus("error", forAction: "Action2")
}

它肯定会对你有所帮助




细节

Xcode 9.2,Swift 4

import Foundation

class Data {

    static fileprivate let queue = DispatchQueue(label: "requests.queue", qos: .utility)
    static fileprivate let mainQueue = DispatchQueue.main

    fileprivate class func make(session: URLSession = URLSession.shared, request: URLRequest, closure: @escaping (_ json: [String: Any]?, _ error: Error?)->()) {
            let task = session.dataTask(with: request) { data, response, error in
                queue.async {
                    guard error == nil else {
                        return
                    }
                    guard let data = data else {
                        return
                    }

                    do {
                        if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                            mainQueue.async {
                                closure(json, nil)
                            }
                        }
                    } catch let error {
                        print(error.localizedDescription)
                        mainQueue.async {
                            closure(nil, error)
                        }
                    }
                }
            }

            task.resume()
    }

    class func searchRequest(term: String, closure: @escaping (_ json: [String: Any]?, _ error: Error?)->()) {
        let url = URL(string: "https://itunes.apple.com/search?term=\(term.replacingOccurrences(of: " ", with: "+"))")
        let request = URLRequest(url: url!)
        Data.make(request: request) { json, error in
            closure(json, error)
        }
    }
}

用法

Data.searchRequest(term: "jack johnson") { json, error  in
      print(error ?? "nil")
      print(json ?? "nil")
      print("Update views")
}

结果




基本的Swift 3解决方案

let url = URL(string: "http://www..com")

let task = URLSession.shared.dataTask(with: url! as URL) { data, response, error in

  guard let data = data, error == nil else { return }

  print(NSString(data: data, encoding: String.Encoding.utf8.rawValue))
}

task.resume()



您可以使用Just ,一个python-requests样式的HTTP库。

使用Just发送HTTP请求的一些示例:

// synchronous GET request with URL query a=1
let r = Just.get("https://httpbin.org/get", params:["a":1])

// asynchronous POST request with form value and file uploads
Just.post(
    "http://justiceleauge.org/member/register",
    data: ["username": "barryallen", "password":"ReverseF1ashSucks"],
    files: ["profile_photo": .URL(fileURLWithPath:"flash.jpeg", nil)]
) { (r)
    if (r.ok) { /* success! */ }
}

在这两种情况下,请求r的结果都可以通过类似于python-request方式访问:

r.ok            // is the response successful?
r.statusCode    // status code of response
r.content       // response body as NSData?
r.text          // response body as text?
r.json          // response body parsed by NSJSONSerielization

你可以在这个playground找到更多的例子

在操场上以同步模式使用这个库是最接近Swift可以获得的卷曲的。




Swift 3数据请求使用URLSession API

   //create the url with NSURL
   let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")! //change the url

   //create the session object
   let session = URLSession.shared

   //now create the URLRequest object using the url object
   let request = URLRequest(url: url)

   //create dataTask using the session object to send data to the server
   let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in

       guard error == nil else {
           return
       }

       guard let data = data else {
           return
       }

      do {
         //create json object from data
         if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
            print(json)
         }
      } catch let error {
        print(error.localizedDescription)
      }
   })

   task.resume()





Related