---
title: "#78: NSURLSession Basics 🔗"
url: https://littlebitesofcocoa.com/78-nsurlsession-basics
author: Jake Marsh
published: 2015-09-09
topics: ["Foundation","Networking"]
description: "NSURLSession is the heart of networking in Foundation. Let's take a look at a few ways to use it. The basic idea is we'll create a new NSURLSession, and..."
---

# #78: NSURLSession Basics 🔗

By Jake Marsh, September 9, 2015. HTML: https://littlebitesofcocoa.com/78-nsurlsession-basics

_NSURLSession_ is the heart of networking in **Foundation**. Let's take a look at a few ways to use it.

The basic idea is we'll create a new _NSURLSession_, and then use it to create **NSURLSessionTasks** that will make the actual HTTP **requests**. We'll start by creating a new **session**:

``` swift
let session = NSURLSession(
  configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
  delegate: self,
  delegateQueue: nil
)
```

Now we'll use the **session** to create different **tasks** to do our bidding:

## Call HTTP API

``` swift
let url = NSURL(string: "http://api.apple.com/releaseSchedule")!
let task = session.dataTaskWithURL(url)
task.resume()
```

## Download Data

We'll can use a **data task** like above, then use this **function** to grab the downloaded **data**. This will be called multiple times, so we'll need to keep an **NSMutableData** reference around to append to.

``` swift
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData)
```

## Upload Data

Here we're uploading an **NSData**. There's also another form of `uploadTaskWithRequest` that accepts a **file URL** to upload from.

``` swift
let request = NSMutableURLRequest(
  URL: NSURL(string: "http://api.someservice.com/upload")!
)

request.HTTPMethod = "POST"

let task = session.uploadTaskWithRequest(request, 
  fromData: dataToUpload)

task.resume()
```
