快速的最小GET / POST请求代码

复制并粘贴这些代码,即可开始制作应用!

获取代码

 让url = URL(string:“ https://httpbin.org/get”)! 
URLSession.shared.dataTask(with:url){(data,response,error)in
如果让错误=错误{
打印(“错误:\(错误)”)
}其他{
如果让response = response as? HTTPURLResponse {
print(“ statusCode:\(response.statusCode)”)
}
如果让数据=数据,则让dataString =字符串(数据:数据,编码:.utf8){
print(“ data:\(dataString)”)
}
}
}。恢复()

邮递区号

 让url = URL(string:“ https://httpbin.org/post”)! 
var request = URLRequest(url:url)
request.httpMethod =“ POST”
URLSession.shared.dataTask(with:url){(data,response,error)in
如果让错误=错误{
打印(“错误:\(错误)”)
}其他{
如果让response = response as? HTTPURLResponse {
print(“ statusCode:\(response.statusCode)”)
}
如果让数据=数据,则让dataString =字符串(数据:数据,编码:.utf8){
print(“ data:\(dataString)”)
}
}
}。恢复()

迅捷版

  Apple Swift版本4.2(swiftlang-1000.11.37.1 clang-1000.11.45.1) 
目标:x86_64-apple-darwin18.2.0