func makeLogon() {
// 构建URL let url:URL = URL(string: "https://xxx/xxx/API?xxx")! // 发送HTTP请求的的session对象 let session = URLSession.shared // 构建请求request var request = URLRequest(url: url) request.httpMethod = "GET" // 发一个get请求 let task:URLSessionDataTask = session.dataTask(with: request as URLRequest) {
( data, response, error) in guard let data = data, let _:URLResponse = response, error == nil else {
print("error") return } let dataString = String(data: data, encoding: String.Encoding.utf8) let dict = self.getDictionaryFromJSONString(jsonString: dataString!) print(dict) } task.resume() } func getDictionaryFromJSONString(jsonString:String) ->NSDictionary{
let jsonData:Data = jsonString.data(using: .utf8)! let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) if dict != nil {
return dict as! NSDictionary } return NSDictionary() }
func sendLocation(latitude:String,longitude:String){
let dict:Dictionary = ["latitude":latitude,"longitude":longitude] let data = try? JSONSerialization.data(withJSONObject: dict, options: []) var request = URLRequest(url: URL(string: "http://cloud.bmob.cn/sendLocation")!) request.httpMethod = "POST" request.httpBody = data //记得要设置Content-Type为application/json,不然可能发生错误 request.setValue("application/json", forHTTPHeaderField: "Content-Type") let task = URLSession.shared.dataTask(with: request) {
(data, response, error) in if error != nil {
print(error.debugDescription) }else{
print(String(data:data!, encoding: String.Encoding.utf8)) if let any = try?JSONSerialization.jsonObject(with: data!, options: .allowFragments){
let dict : Dictionary = any as! Dictionary<String, Any> print(dict) } } } task.resume() }
像上面在两个地方传参数,用iOS原生的网络请求接口测试是成功的,用alamofire测试时不成功
Swift 原生网络请求
github仓库:Moya/Moya
简书博客:moya的使用
主要参考博客:Moya基本用法
import Alamofire //修改密码 func afModifyPassword(oldPassword:String,newPassword:String,complete:@escaping Completion){
let parameters:Dictionary = ["password1":oldPassword.md5(),"password2":newPassword.md5()] request(baseURL + "/member/modifyPassword",method:.post,parameters: parameters,headers: baseHeaders).responseJSON {
(response) in switch response.result {
case .success(let responseSus): let dict:NSDictionary = responseSus as! NSDictionary printXY(dict, obj: self, line: #line) let model = SSCommonModel.deserialize(from: dict) complete(model!) case .failure(let error): let errorModel = SSCommonModel(error: error.localizedDescription) complete(errorModel) } } }
简书博客:
Alamofire(swift版的AFN)
github仓库:
Alamofire/Alamofire
写一个自己的网络中间层,里面一部分用到moye,一部分用到Alamofire,一部分用苹果原生的网络接口