Swift-->Http网络请求(NSURLSession, Alamofire)
网络请求用的比较多的是Get和Post请求,最为学习记录,先介绍Get请求.后续更新Post请求. 1:调用系统浏览器打开网页 let baidu = "http://www.baidu.com"
//MARK:构建一个NSURL,使用String
var bdUrl: NSURL {
return NSURL(string: baidu)!
}
//MARK: 获取UIApplication对象
var application: UIApplication {
return UIApplication.sharedApplication()
}
@IBAction func openBaidu() {
//检查是否可以打开这个URL
let can = application.canOpenURL(bdUrl)
if can {
//记住:一定要在子线程中调用,否则会阻塞主线程.
NSOperationQueue().addOperationWithBlock {
//返回结果,表示是否请求成功
let result = self.application.openURL(self.bdUrl)//打开URL
}
}
}
关于多线程: http://www.52php.cn/article/p-gytwawso-mt.html 2:使用NSURLSession获取NSURL对应的数据 @IBAction func openWidthSession() {
NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: url)!) { data,response,error in
print("(String(data: data!,encoding:NSUTF8StringEncoding))")//数据
print("(response)")
print("(error)")
}.resume() //调用resume,执行任务.
}
关于NSURLSession: http://www.cnblogs.com/biosli/p/iOS_Network_URL_Session.html 3:使用Alamofire请求数据 @IBAction func openWidthAlamofire() {
// 1:
Alamofire.request(.GET,url)
.validate()
.response { request,data,error in
print("(request?.URLString)")
print("(response)")
print("(String(data: data!,encoding: NSUTF8StringEncoding))")//数据
print("(error)")
}
// 2:
Alamofire.request(.GET,bdUrl).responseString { response in
print("(response.result.value)")//数据
}
}
Alamofire的用法: https://github.com/Alamofire/Alamofire#usage 4:使用AlamofireImage装载网络图片 @IBAction func pngImage() {
let url = "https://httpbin.org/image/png"
// 1:
Alamofire.request(.GET,url)
.responseImage { response in
print(response.request)
print(response.response)
if let image = response.result.value {
print("image downloaded: (image)")
self.imageView.image = image //图片
}
}
// 2:
imageView.af_setImageWithURL(NSURL(string: url)!)//更简单的方式
}
AlamofireImage的用法: https://github.com/Alamofire/AlamofireImage#usage 注意:
你只需要在项目中的plist文件中添加:
源码: https://github.com/angcyo/HttpDemo 后续补充更多… 至此: 文章就结束了,如有疑问: QQ群 Android:274306954 Swift:399799363 欢迎您的加入. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |