Swift_网络请求

swift网络请求,不是第三方库,直接用代码写的,直接代码:

class fun requestDataOfGet(url: String, parameters: String?, _ callback( __ @escaping  result: ant) -> ()){

let urlstr = "http://***********"//链接自己添加吧 

let url =  URL.init(string: urlstr) //需要把String的URL转换成URL

var request = URLRequset.init(url: url!)

request.httpMethod = "GET"  

request.httpBody = ""  //请求数据一些其他的数据,需要吧parameters转换成Data,我这里就不写了

let session = URLSession.shared  

let dataTesk = session.dataTask(with: request) { (data, response, error) -> Void in

if error != nil{

   print(error)  

 }else{

 //base64 解密   对于没有加密的数据可以直接跳过

  let dataStr = String.init(data: data!, encoding: String.Encoding(eawValue: String.Encoding.utf8.rawValue))

  let decodedData = Data.init(base64Encoded: str!, options: Data.Base64DecodingOptions.init(rawValue: 0))

  //json解析

  let json =  try? JSONSerialization.jsonObject(with: decodedData !, options: [])

  if (json != nil) {

     print(json)

  }else{

     print("解析失败")

  }

}

//执行方法

dataTesk.resume()

}

调用,parameters为空,若要添加,需要传入String,

ClassName.requestDataOfGet(url: url, parameters: nil){ (response) in

print(response)

//Any转换成Dictionary

guard let dataDic = response as? [String: Any] else{ return}

}

end

你可能感兴趣的:(Swift_网络请求)