NSURLSession

var imageView = UIImageView(frame: CGRectMake(40, 40, 200, 200))
var curTime = NSDateFormatter()

override func viewDidLoad() {
    super.viewDidLoad()

    curTime.dateFormat = "HH:mm:ss"
    print(curTime.stringFromDate(NSDate()))
    
    imageView.contentMode = UIViewContentMode.ScaleAspectFit
    self.view.addSubview(imageView)
    
    let url = "http://pic1.nipic.com/2008-12-29/2008122993940613_2.jpg"
    let imageURL = NSURL(string: url)
    let urlRequest = NSURLRequest(URL: imageURL!)
   
    // let session = NSURLSession.sharedSession() // # 1
    let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration()) // # 2
    let task = session.dataTaskWithRequest(urlRequest, completionHandler: {(data, response, error) -> Void in
        let imgData = NSData(data: data!)
        self.imageView.image = UIImage(data: imgData)
    })
    task.resume()
    
    print(curTime.stringFromDate(NSDate()))
}

IOS9需要设置如下:

clipboard.png

Alamofire

Alamofire

Alamofire是个第三方的Swift语言的HTTP网络开发工具包,基于NSURLSession,但是更娇便于使用。

import Alamofire

// # 1
Alamofire.request(.GET, "https://httpbin.org/get").responseJSON { (response) -> Void in
    print(response.result)
    print(response.result.value)
}

// # 2
Alamofire.request(.GET, "https://www.baidu.com").responseJSON { (response) -> Void in
    print(response.result.value)
}

// # 3
let url = "http://pic1.nipic.com/2008-12-29/2008122993940613_2.jpg"
    
Alamofire.request(.GET, url).responseData { (response) -> Void in
    self.imageView.image = UIImage(data: NSData(data: response.result.value!))
}

和SwiftyJSON一起用:

Alamofire.request(.GET, url).validate().responseJSON { response in
    switch response.result {
    case .Success:
        if let value = response.result.value {
          let json = JSON(value)
          print("JSON: \(json)")
        }
    case .Failure(let error):
        print(error)
    }
}

RichardXG
337 声望19 粉丝