17.Swift 原生网络通信

17.Swift 原生网络通信

  • Swift 原生网络通信
    • sendSynchronousRequest
    • sendAsynchronousRequest
    • NSURLSession

IOS9.0后,就打算废弃NSURLConnection,主推NSURLSession

sendSynchronousRequest

同步Request
NSURLConnection.sendSynchronousRequest(request: NSURLRequest, returningResponse response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>) throws -> NSData

    func usingSendSynchronousRequest(){
        do{
            var response:NSURLResponse?
            // 发同步请求
            let data:NSData = try NSURLConnection.sendSynchronousRequest(NSURLRequest(URL: NSURL(string: "http://www.baidu.com")!), returningResponse: &response)

            if let d:NSData = data {
                NSLog("\(NSString(data: d, encoding: NSUTF8StringEncoding))")
            }

            if let r:NSURLResponse = response{
                NSLog("\(r)")
            }

        }catch let error as NSError{
            NSLog("\(error.localizedDescription)")
        }
    }

sendAsynchronousRequest

异步Request
NSURLConnection.sendAsynchronousRequest(request: NSURLRequest, queue: NSOperationQueue, completionHandler handler: (NSURLResponse?, NSData?, NSError?) -> Void)

    func usingSendAsynchronousRequest(){
        // 异步请求
        NSURLConnection.sendAsynchronousRequest(NSURLRequest(URL: NSURL(string: "http://www.baidu.com")!), queue: NSOperationQueue()) { (resp:NSURLResponse?, data:NSData?, error:NSError?) -> Void in
            if let e:NSError = error{
                NSLog("\(e.localizedDescription)")
            }else{
                NSLog("\(NSString(data: data!, encoding: NSUTF8StringEncoding))")
            }
        }
    }

NSURLSession

NSURLSession实例化一个网络请求task
NSURLSession.dataTaskWithRequest(request: NSURLRequest, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) -> NSURLSessionDataTask

    func usingNSURLSession(){
        let session = NSURLSession.sharedSession()
        let request = NSURLRequest(URL: NSURL(string: "http://baidu.com")!)
        let task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in let string = NSString(data: data!, encoding: NSUTF8StringEncoding) NSLog("\(string)") }) task.resume() }

你可能感兴趣的:(ios,网络,通信,swift)