Swift 3 和 Swift 4 中的 WebService API 方法?

WebService API Method in Swift 3 and Swift 4?

我是 Swift iOS 的新手,我想在单独的 class(如 NSObject)网络服务中创建一个单独的方法,以便我可以使用它在任何 ViewController 中并使用 NSURLSessionAlamofire 解析任何类型的 JSON 响应。谁能帮帮我。

class WebRequester: NSObject {

    static let shared = WebRequester()

    let session = URLSession.shared

    func request(urlStr:String, parameter:String, token:String? = nil, callback:@escaping (_ result:NSDictionary?, error:Error?) -> Void) {

        let url = URL(string: BaseURL + urlStr)

        debugPrint("=====================")
        debugPrint(url ?? "")
        debugPrint(parameter)
        debugPrint("=====================")

        var request = URLRequest(url: url!)
        request.httpMethod = "POST"
        request.httpBody = parameter.data(using: String.Encoding.utf8)


        print("Token :", (token ?? ""))
        request.setValue(token, forHTTPHeaderField: "Authorization")


        let task = session.dataTask(with: request) { (data, response, error) in
            DispatchQueue.main.async {
                if error == nil {
                   do {
                         let jsonObj = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments)
                         if let dic = jsonObj as? NSDictionary {
                             callback(dic, error)
                         }
                   }
                   catch {
                      callback(nil, error)
                   }
                }
                else {
                   callback(nil, error)
                }

            }
        }
        task.resume()
    }

}

您需要将参数作为字符串传递

var params = "user_id=" + "12"
params += "&course_id=" + "1"

WebRequester.shared.request(urlStr: urlStr, parameter: params) { (result, error) in
    DispatchQueue.main.async {
         print(result)
    }
}

您也可以将参数作为字典传递,但需要使用以下 Dictionary 扩展名

转换为字符串

request.httpBody = parameter.stringFromHttpParameters().data(using: String.Encoding.utf8)

extension Dictionary {
    func stringFromHttpParameters() -> String {
        let parameterArray = self.map { (key, value) -> String in
            let percentEscapedKey = (key as! String).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
            let percentEscapedValue = (value as AnyObject).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
            return "\(percentEscapedKey)=\(percentEscapedValue)"
        }

        return parameterArray.joined(separator: "&")
    }
}

WebRequester

  • HTTP 请求
  • 带有单张图片的多部分
  • 具有多个图像的多部分

您需要根据您的 api 回复

更改回复结构

您需要根据您的 api

设置授权和 api 密钥

WebRequester

这是 Alamofire 的工作代码 (swift 4)

在你的项目中添加这个class

import Foundation
import UIKit
import Alamofire
import SystemConfiguration

class APPWebService: NSObject {

    class open func callPostApi(api:String, parameters:[String:AnyObject]?, complition:@escaping (AnyObject)->Void)
    {

        if self.IsInternetAvailable() == false {
            self.showAlert(title: "Whoops :(", message: "No internet connection.")
            return
        }

        let parameters = parameters

        // Encode Data
        let base64EncodedString = toBase64EncodedString(toJsonString(parameters: parameters!))

        Alamofire.request(api, method: .post, parameters: ["jsondata":base64EncodedString])
        .response { response in

            do {

                if response.error != nil{
                    print(response.error as Any, terminator: "")
                }

                if let jsonDict = try JSONSerialization.jsonObject(with: (response.data as Data?)!, options: []) as? [String: AnyObject]{

                    print(jsonDict as Any, terminator: "")
                    complition(jsonDict as AnyObject)

                }else{
                    self.showAlert(title: "Whoops", message: "Something went wrong. Please, try after sometime.")
                    return
                }

            } catch _ {
                print("Exception!")
            }
      }
  }

// For check Internet Connection
class open func IsInternetAvailable () -> Bool {

    var zeroAddress = sockaddr_in()
    zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
    zeroAddress.sin_family = sa_family_t(AF_INET)

    let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
        [=10=].withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
            SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
        }
    }

    var flags = SCNetworkReachabilityFlags()
    if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
        return false
    }
    let isReachable = flags.contains(.reachable)
    let needsConnection = flags.contains(.connectionRequired)
    return (isReachable && !needsConnection)

}

// Display Alert
class open func showAlert(title:String,message:String){

    let alert = UIAlertView(title:title,message: "\n" + message,delegate: nil ,cancelButtonTitle: "Ok")
    alert.show()
}

// For Convert to JSON String
class open func toJsonString(parameters:[String:AnyObject]) -> String
{
    var jsonData: NSData?
    do {
        jsonData = try JSONSerialization.data(withJSONObject: parameters, options:JSONSerialization.WritingOptions(rawValue: 0)) as NSData?
    } catch{
        print(error.localizedDescription)
        jsonData = nil
    }

    let jsonString = NSString(data: jsonData! as Data, encoding: String.Encoding.utf8.rawValue)! as String
    return jsonString
}

// For Convert to Base64Encoded String
class open func toBase64EncodedString(_ jsonString : String) -> String
{
    let utf8str = jsonString.data(using: .utf8)
    let base64Encoded = utf8str?.base64EncodedString(options: [])
    return base64Encoded!
}
}

像这样使用

func ServiceCall()
{
    // Create parameter list
    let parameters = [
        "name":"Abc",
        "address":"Xyz",
        "contact":"1234567890"
        ]

    // set webservice Url
    let ReqURL = "your webservice url here"

    APPWebService.callPostApi(api: ReqURL, parameters: parameters as [String : AnyObject]?) { (dict) -> Void in

        print(dict) // Your response is here.
    }
}