How do I make an HTTP request in Swift?

前端 未结 20 1072
不知归路
不知归路 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 05:50

    Details

    • Xcode 9.2, Swift 4
    • Xcode 10.2.1 (10E1001), Swift 5

    Info.plist

    NSAppTransportSecurity

    Add to the info plist:

    NSAppTransportSecurity
    
        NSAllowsArbitraryLoads
        
    
    

    Alamofire Sample

    Alamofire

    import Alamofire
    
    class AlamofireDataManager {
        fileprivate let queue: DispatchQueue
        init(queue: DispatchQueue) { self.queue = queue }
    
        private func createError(message: String, code: Int) -> Error {
            return NSError(domain: "dataManager", code: code, userInfo: ["message": message ])
        }
    
        private func make(session: URLSession = URLSession.shared, request: URLRequest, closure: ((Result<[String: Any]>) -> Void)?) {
            Alamofire.request(request).responseJSON { response in
                let complete: (Result<[String: Any]>) ->() = { result in DispatchQueue.main.async { closure?(result) } }
                switch response.result {
                    case .success(let value): complete(.success(value as! [String: Any]))
                    case .failure(let error): complete(.failure(error))
                }
            }
        }
    
        func searchRequest(term: String, closure: ((Result<[String: Any]>) -> Void)?) {
            guard let url = URL(string: "https://itunes.apple.com/search?term=\(term.replacingOccurrences(of: " ", with: "+"))") else { return }
            let request = URLRequest(url: url)
            make(request: request) { response in closure?(response) }
        }
    }
    

    Usage of Alamofire sample

    private lazy var alamofireDataManager = AlamofireDataManager(queue: DispatchQueue(label: "DataManager.queue", qos: .utility))
    //.........
    
    alamofireDataManager.searchRequest(term: "jack johnson") { result in
          print(result.value ?? "no data")
          print(result.error ?? "no error")
    }
    

    URLSession Sample

    import Foundation
    
    class DataManager {
    
        fileprivate let queue: DispatchQueue
            init(queue: DispatchQueue) { self.queue = queue }
    
        private func createError(message: String, code: Int) -> Error {
            return NSError(domain: "dataManager", code: code, userInfo: ["message": message ])
        }
    
        private func make(session: URLSession = URLSession.shared, request: URLRequest, closure: ((_ json: [String: Any]?, _ error: Error?)->Void)?) {
            let task = session.dataTask(with: request) { [weak self] data, response, error in
                self?.queue.async {
                    let complete: (_ json: [String: Any]?, _ error: Error?) ->() = { json, error in DispatchQueue.main.async { closure?(json, error) } }
    
                    guard let self = self, error == nil else { complete(nil, error); return }
                    guard let data = data else { complete(nil, self.createError(message: "No data", code: 999)); return }
    
                    do {
                        if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                            complete(json, nil)
                        }
                    } catch let error { complete(nil, error); return }
                }
            }
    
            task.resume()
        }
    
        func searchRequest(term: String, closure: ((_ json: [String: Any]?, _ error: Error?)->Void)?) {
            let url = URL(string: "https://itunes.apple.com/search?term=\(term.replacingOccurrences(of: " ", with: "+"))")
            let request = URLRequest(url: url!)
            make(request: request) { json, error in closure?(json, error) }
        }
    }
    

    Usage of URLSession sample

    private lazy var dataManager = DataManager(queue: DispatchQueue(label: "DataManager.queue", qos: .utility))
    // .......
    dataManager.searchRequest(term: "jack johnson") { json, error  in
          print(error ?? "nil")
          print(json ?? "nil")
          print("Update views")
    }
    

    Results

提交回复
热议问题