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 欢迎您的加入.

在Swift 4中发出HTTP POST请求

01-09
<div class="post-text" itemprop="text"> <p>I´m trying to send data to a PHP file on my server using <code>URLSession</code>. This seems to fail though, since no data is received on the server. While running the app, I get this console print:</p> <pre><code>2018-01-09 20:56:10.942359+0100 EinsatzPush[12182:8624757] [BoringSSL] Function boringssl_session_errorlog: line 2871 [boringssl_session_read] SSL_ERROR_ZERO_RETURN(6): operation failed because the connection was cleanly shut down with a close_notify alert 2018-01-09 20:56:10.942857+0100 EinsatzPush[12182:8624757] [BoringSSL] Function boringssl_session_errorlog: line 2871 [boringssl_session_read] SSL_ERROR_ZERO_RETURN(6): operation failed because the connection was cleanly shut down with a close_notify alert 2018-01-09 20:56:10.943028+0100 EinsatzPush[12182:8624757] TIC Read Status [1:0x1c0173680]: 1:57 2018-01-09 20:56:10.943187+0100 EinsatzPush[12182:8624757] TIC Read Status [1:0x1c0173680]: 1:57 2018-01-09 20:56:10.943278+0100 EinsatzPush[12182:8624757] TIC Read Status [1:0x1c0173680]: 1:57 2018-01-09 20:56:10.943923+0100 EinsatzPush[12182:8624757] [BoringSSL] Function boringssl_session_errorlog: line 2871 [boringssl_session_read] SSL_ERROR_ZERO_RETURN(6): operation failed because the connection was cleanly shut down with a close_notify alert </code></pre> <p>This is the code I´m using:</p> <pre><code>let url = URL(string: "https://my-server.com/update.php") let session = URLSession.shared let request = NSMutableURLRequest(url: url as! URL) request.httpMethod = "POST" let paramString = "username=user&token=token" request.httpBody = paramString.data(using: String.Encoding.utf8) let task = session.dataTask(with: request as URLRequest) { ( data, response, error) in guard let _:NSData = data as NSData?, let _:URLResponse = response, error == nil else { print("error") return } if let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) { print(dataString) } } task.resume() </code></pre> <p>I´d be very happy if anyone here could help me get this fixed. Thanks!</p> </div>
©️2020 CSDN 皮肤主题: 猿与汪的秘密 设计师: 上身试试 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值