Swift 3和Swift 4中的WebService API方法? [英] WebService API Method in Swift 3 and Swift 4?
问题描述
我是iOS Swift
的新手,我想在单独的类中创建单独的方法(例如 NSObject
) Web服务,以便我可以在任何ViewController中使用它,并使用 NSURLSession
和<$解析任何类型的 JSON
响应c $ c> Alamofire 。
I am new to Swift
iOS and i want to create a separate method in separate class(like NSObject
) of web services so that i can use it in any ViewController and parse any type of JSON
response using NSURLSession
and Alamofire
. Could someone help me.
推荐答案
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()
}
}
您需要将参数作为字符串传递
You need to pass parameter as string
var params = "user_id=" + "12"
params += "&course_id=" + "1"
WebRequester.shared.request(urlStr: urlStr, parameter: params) { (result, error) in
DispatchQueue.main.async {
print(result)
}
}
您也可以将参数作为字典传递,但需要使用以下字典
扩展
you can also pass parameter as dictionary but need to convert in string using following Dictionary
extension
request.httpBody = parameter.stringFromHttpParameters()。data(使用:
String.Encoding.utf8)
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响应更改响应结构
You need to change response structure as per your api response
您需要设置授权和api根据您的api键
you need to set authorisation and api key as per your api
这篇关于Swift 3和Swift 4中的WebService API方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!