import Alamofire
import SwiftyJSON
//网络请求数据
func request(){
Alamofire.request(.GET, "http://fanyi.youdao.com/openapi.do", parameters: ["keyfrom": "bhzjbxjhb","key":"**********","type":"data","doctype":"json","version":"1.1","q":txtDanCi.text!])
.responseJSON { response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
switch response.result {
case .Success:
print("数据获取成功!")
if let j = response.result.value {
//SwiftyJSON解析数据
let JSOnDictory = JSON(j)
let translation = JSOnDictory["translation"]
let uk = JSOnDictory["basic"]["uk-phonetic"]
let us = JSOnDictory["basic"]["us-phonetic"]
self.lblXianshi.text! = String(translation)
self.英式发音.text! = String(uk)
self.美式发音.text! = String(us)
print(translation)
}
case .Failure(let error):
print(error)
}
}}
//异步请求数据
//请求地址
var url = "http://apis.baidu.com/apistore/mobilephoneservice/mobilephone"
//请求地址
var httpArg = "tel="
//网络请求数据的方法
func request(httpUrl: String, httpArg: String) {
let req = NSMutableURLRequest(URL: NSURL(string: httpUrl + "?" + httpArg + txtPhone.text!)!)
//请求时长
req.timeoutInterval = 6
//请求方式
req.HTTPMethod = "GET"
//请求添加的header
req.addValue("***************", forHTTPHeaderField: "apikey")
//异步请求数据
NSURLConnection.sendAsynchronousRequest(req, queue: NSOperationQueue.mainQueue()) {
(response, data, error) -> Void in
//返回参数,200表示成功
let res = response as! NSHTTPURLResponse
print(res.statusCode)
//错误信息处理
if error != nil{
print("请求失败")
}
if let d = data {
//json文本
let content = NSString(data: d, encoding: NSUTF8StringEncoding)
print(content)
//SwiftyJSON解析数据
let JSOnDictory = JSON(data:d)
let telString = JSOnDictory["retData"]["telString"]
let province = JSOnDictory["retData"]["province"]
let city = JSOnDictory["retData"]["city"]
let carrier = JSOnDictory["retData"]["carrier"]
//显示到界面中
self.lblPhoneNum.text = String(telString)
self.lblProvince.text = String(province)
self.lblCity.text = String(city)
self.lblSupply.text = String(carrier)
print(telString)
print(province)
print(city)
print(carrier)
}
}
}