Alamofire
print(Alamofire.request("https://www.baidu.com"))
Alamofire.request("https://httpbin.org/get", parameters: ["foo": "bar"])
Alamofire.request("https://httpbin.org/get", parameters: ["foo": "bar"])
.response { (response) in
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)")
}
}
.responseJSON { response in //使用responseJSON 方法的话,JSON数据会被自动转化为 Dictionary或Array
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
print(response.result.isSuccess)
debugPrint(response.result.isSuccess)
if let JSON = response.result.value {
print("JSON: \(JSON)") //具体如何解析json内容可看下方“响应处理”部分
}
}
/*
除了上面样例使用的responseJSON(处理json类型的返回结果)外,Alamofire还提供了许多其他类型的响应处理方法:
response()
responseData()
responseString(encoding: NSStringEncoding)
responseJSON(options: NSJSONReadingOptions)
responsePropertyList(options: NSPropertyListReadOptions)
*/
http://www.hangge.com/blog/cache/detail_970.html
SwiftyJSON
//SwiftyJSON
let jsonStr = "[{\"name\": \"hangge\", \"age\": 100, \"phones\": [{\"name\": \"公司\",\"number\": \"123456\"}, {\"name\": \"家庭\",\"number\": \"001\"}]}, {\"name\": \"big boss\",\"age\": 1,\"phones\": [{ \"name\": \"公司\",\"number\": \"111111\"}]}]"
let jsonData = jsonStr.data(using: String.Encoding.utf8, allowLossyConversion: false)
//print("jsonData======\(jsonData)")
let data11 = JSON(parseJSON: jsonData)
print("data11======\(data11)")
let json = try! JSON(data: jsonData!)
print(json)
if let number = json[0]["phones"][0]["number"].string {
// 找到电话号码
print("第一个联系人的第一个电话号码:",number)
}
// MARK: 字典转字符串
func dictionaryToString(dict:[String:AnyObject]) -> String{
var result:String = ""
do {
let jsonData = try JSONSerialization.data(withJSONObject: dict, options: JSONSerialization.WritingOptions.init(rawValue: 0))
if let JSONString = String(data: jsonData, encoding: String.Encoding.utf8){
result = JSONString
}
}catch{
result = ""
}
return result
}
SwiftyJSON+Alamofire
//SwiftyJSON+Alamofire
let url = URL(string: "http://www.hangge.com/getJsonData.php")
Alamofire.request(url!).validate().responseJSON { (response) in
switch response.result.isSuccess{
case true :
if let value = response.result.value{
let json = JSON(value)
if let number = json[0]["phones"][0]["number"].string {
// 找到电话号码
print("第一个联系人的第一个电话号码:",number)
}
}
case false :
print(response.result.error)
}