我正在使用Swift和alamofire
。
如何进行代码优化?这是我对不同api的post和put请求:
func getPDataFromURL(_ onCompletion:@escaping (Dictionary<String, Any>)-> Void)
{
let token = UserDefaults.standard.string(forKey: "UserLoginToken")
let Usertype = UserDefaults.standard.string(forKey: "Usertype")
let Userbranchid = UserDefaults.standard.string(forKey: "Userbranchid")
let UrlStraing = FETCH_Parent_Profile_URL
print(UrlStraing)
let url = URL(string: UrlStraing)!
var urlRequest = URLRequest(url:url)
urlRequest.httpMethod = "GET"
urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")
let userToken = "Token token=" + token! as String
urlRequest.addValue(userToken, forHTTPHeaderField: "Authorization")
Alamofire.request(urlRequest).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
if response.result.value != nil{
print(response.result.value!)
onCompletion(response.result.value! as! Dictionary<String, Any>)
}
break
case .failure(_):
print(response.result.error!)
onCompletion(response.result.error as! Dictionary<String, Any>)
break
}
}
}
这是我对另一个api的第二个post请求:
func getSDataFromURL(_ onCompletion:@escaping (Dictionary<String, Any>)-> Void) {
let token = UserDefaults.standard.string(forKey: "UserLoginToken")
let Usertype = UserDefaults.standard.string(forKey: "Usertype")
let Userbranchid = UserDefaults.standard.string(forKey: "Userbranchid")
let UrlStraing = FETCH_School_Info_URL + "branch_id=" + Userbranchid! + "&student_id=86&user_type=" + Usertype!
print(UrlStraing)
let url = URL(string: UrlStraing)!
var urlRequest = URLRequest(url:url)
urlRequest.httpMethod = "GET"
urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")
let userToken = "Token token=" + token! as String
urlRequest.addValue(userToken, forHTTPHeaderField: "Authorization")
Alamofire.request(urlRequest).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
if response.result.value != nil{
print(response.result.value!)
onCompletion(response.result.value! as! Dictionary<String, Any>)
}
break
case .failure(_):
print(response.result.error!)
onCompletion(response.result.error as! Dictionary<String, Any>)
break
}
}
}
在viewcontroller中调用函数如下:
func SetUpSchoolUIProfiledata() {
Common.sharedInstance.StartActivity(view: self.view)
DispatchQueue.main.async {
APIManager.sharedInstance.getSchoolProfileDataFromURL(){(userJson)->
Void in
self.stop()
let swiftyJsonVar = JSON(userJson)
print("userJson userJson userJson userJson",userJson)
print("swiftyJsonVar",swiftyJsonVar)
let message = swiftyJsonVar["message"].rawString()
let info = swiftyJsonVar["info"].rawString()!
let jsonData = info.data(using: .utf8)!
let dictionary = try? JSONSerialization.jsonObject(with: jsonData, options: []) as! Dictionary<String, Any>
self.schoolName_lbl.text = dictionary?["name"] as? String
self.add1_lbl.text = dictionary?["add_line1"] as? String
print("imgURLstring is ",self.imgURLstring)
self.SetUpProfileImage()
}
}
}
如何创建单功能多post和get请求?
最佳答案
你可以这样创建单例类
当您要调用web服务时,请使用以下方法
class DataProvider: NSObject {
class var sharedInstance:DataProvider {
struct Singleton {
static let instance = DataProvider()
}
return Singleton.instance
}
let baseUrl:String = "http://192.168.1.25:3004/api3/v3/"
func putData( parameter:[String:String], url:String, _ successBlock:@escaping ( _ response: JSON )->Void , errorBlock: @escaping (_ error: NSError) -> Void ){
let path = baseUrl + url
print(path)
print(parameter)
let headers = ["authorization": AppData().token]
Alamofire.request(path, method: .put, parameters: parameter, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
switch response.result {
case .success:
if let value = response.result.value {
let json = JSON(value)
successBlock(json)
}
case .failure(let error):
errorBlock(error as NSError)
}
}
}
像这样打电话
DataProvider.sharedInstance.putData(parameter: parameter, url: "users/account/update", { (response) in
print(response)
if response["status"].stringValue == "200" {
Utility.showMessageDialog(onController: self, withTitle: "", withMessage: response["message"].stringValue)
}
}) { (error) in
print(error)
}