Swift-->Http网络请求(NSURLSession, Alamofire)

网络请求用的比较多的是Get和Post请求,最为学习记录,先介绍Get请求.后续更新Post请求.
本文介绍,在IOS开发中,苹果原生的NSURLSession框架和第三方开源的Alamofire

这里写图片描述


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://blog.csdn.net/angcyo/article/details/52280819

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请求数据
需要: import Alamofire

@IBAction func openWidthAlamofire() {
    // 1:
    Alamofire.request(.GET, url)
        .validate()
        .response { request, response, 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装载网络图片
需要: import 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

注意:
如果你选择的IOS版本>=9.0, 那么在网络请求的时候,可能会出现这个错误:

The resource could not be loaded because the App Transport Security policy require

你只需要在项目中的plist文件中添加:

在Info.plist中添加NSAppTransportSecurity类型Dictionary。
在NSAppTransportSecurity下添加NSAllowsArbitraryLoads类型Boolean,值设为YES

这里写图片描述

源码: https://github.com/angcyo/HttpDemo

后续补充更多…


至此: 文章就结束了,如有疑问: QQ群 Android:274306954 Swift:399799363 欢迎您的加入.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值