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://www.jb51.cc/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请求数据
需要: import 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装载网络图片
需要: 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 欢迎您的加入.

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...