LoginSignup
36
36

More than 5 years have passed since last update.

HTTP Request in Swift 2.0

Last updated at Posted at 2015-09-22

HTTP Request in Swift 2.0

APIを利用するiOSアプリを実装しようとしたところ,HTTP Requestの方法がよく分からず調査し,HTTP Requestを行うクラス(Request.js)を実装してみた.

Request.swift

Request.swift
import Foundation

class Request {
    let session: NSURLSession = NSURLSession.sharedSession()

    // GET METHOD
    func get(url: NSURL, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) {
        let request: NSMutableURLRequest = NSMutableURLRequest(URL: url)

        request.HTTPMethod = "GET"
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        session.dataTaskWithRequest(request, completionHandler: completionHandler).resume()
    }

    // PUT METHOD
    func post(url: NSURL, body: NSMutableDictionary, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) {
        let request: NSMutableURLRequest = NSMutableURLRequest(URL: url)

        request.HTTPMethod = "POST"
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        do {
            request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(body, options: NSJSONWritingOptions.init(rawValue: 2))
        } catch {
            // Error Handling
            print("NSJSONSerialization Error")
            return
        }
        session.dataTaskWithRequest(request, completionHandler: completionHandler).resume()
    }

    // POST METHOD
    func put(url: NSURL, body: NSMutableDictionary, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) {
        let request: NSMutableURLRequest = NSMutableURLRequest(URL: url)

        request.HTTPMethod = "PUT"
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        do {
            request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(body, options: NSJSONWritingOptions.init(rawValue: 2))
        } catch {
            // Error Handling
            print("NSJSONSerialization Error")
            return
        }
        session.dataTaskWithRequest(request, completionHandler: completionHandler).resume()
    }

    // DELETE METHOD
    func delete(url: NSURL, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) {
        let request: NSMutableURLRequest = NSMutableURLRequest(URL: url)

        request.HTTPMethod = "DELETE"
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        session.dataTaskWithRequest(request, completionHandler: completionHandler).resume()
    }
}

使用例

sample.swift

let request: Request = Request()

let url: NSURL = NSURL(string: "https://api.example.com/path/to/resource")!
let body: NSMutableDictionary = NSMutableDictionary()
body.setValue("value", forKey: "key")

request.post(url, body: body, completionHandler: { data, response, error in
    // code
})

疑問

NSJSONSerialization.dataWithNSObject() の箇所を綺麗にエラーハンドリングできないのか.

do {
    request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(body, options: NSJSONWritingOptions.init(rawValue: 2))
} catch {
    // Error Handling
    print("NSJSONSerialization Error")
    return
}
36
36
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
36
36