Swift之网络编程

在不适用第三方框架的情况下,使用Swift提供的API进行网络操作

1、NSURLConnection

    /**
    通过NSURLConnection对象发送同步请求
    使用同步操作,该方法不支持,废弃
    */
    func sendSynchronousRequest() {
        // 1、创建请求路径
        let url = NSURL(string: uri)!;
        // 2、创建请求对象。NSURLRequest方法默认为GET请求
        // let request = NSURLRequest(URL: url);
        // 2、创建可变的NSURLRequest对象
        let request = NSMutableURLRequest(URL: url);
        // 设置超时时间
        request.timeoutInterval = 3;
        // 3、通过NSURLConnection对象发送请求(同步请求)
        let data = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil)!;
    }

    /**
    通过NSURLConnection对象发送异步请求
    */
    func sendAsynchronousRequest() {
        // 1、创建请求路径
        let url = NSURL(string: uri)!;
        // 2、创建请求对象
        let request = NSURLRequest(URL: url);
        // 3、通过NSURLConnection对象发送请求(异步请求)
        // Queue的值对应着闭包中的代码在主线程或子线程中执行,一般使用主线程
        let queue = NSOperationQueue.mainQueue();
//        let queue = NSOperationQueue();
        NSURLConnection.sendAsynchronousRequest(request, queue: queue) { (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
            if response != nil {
                let resultResponse = response as NSHTTPURLResponse;
                if resultResponse.statusCode == 200 {
                    let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: nil) as NSDictionary;
                    let dict = json["weatherinfo"] as NSDictionary;
                }
            }
        }
    }

    /**
    通过NSURLConnection对象发送请求,使用代理的方式实现
    */
    func sendRequestWithDelegate() {
        // 1、创建请求路径
        let url = NSURL(string: uri)!;
        // 2、创建请求对象
        let request = NSURLRequest(URL: url);
        // 3、创建NSURLConnection对象,并设置代理
        NSURLConnection(request: request, delegate: self);
    }

extension ViewController: NSURLConnectionDataDelegate {

    /**
    请求错误/失败时调用
    */
    func connection(connection: NSURLConnection, didFailWithError error: NSError) {
        println("didFailWithError");
    }

    /**
    开始接收到服务器响应
    */
    func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse) {
        responseData = NSMutableData();
        println("didReceiveResponse");
    }

    /**
    接收到服务器数据
    */
    func connection(connection: NSURLConnection, didReceiveData data: NSData) {
        responseData.appendData(data);
        println("didReceiveData");
    }

    /**
    当服务器的数据接收完毕
    */
    func connectionDidFinishLoading(connection: NSURLConnection) {
        let json = NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.AllowFragments, error: nil) as NSDictionary;
        let dict = json["weatherinfo"] as NSDictionary;
        println("connectionDidFinishLoading: \(dict)");
    }
}

请求的路径也就直接使用网络上提供的开放API,如此也无需自己搭建请求服务器。

可以使移动开发更加专注于自己的领域

    let uri = "http://m.weather.com.cn/data/101010100.html";
    var responseData: NSMutableData!;


你可能感兴趣的:(swift,网络编程)