Created
February 6, 2016 03:33
-
-
Save aoriani/7fa2b55e73ddfd185651 to your computer and use it in GitHub Desktop.
Implementing get Requests with swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// REST.swift | |
// CoconutTests | |
// | |
// Created by Andre Oriani on 2/5/16. | |
// Copyright © 2016 Walmartlabs. All rights reserved. | |
// | |
import Foundation | |
class RestManager { | |
private let session = NSURLSession( | |
configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), | |
delegate:nil, | |
delegateQueue:NSOperationQueue.mainQueue() | |
) | |
private func performRequest<ResponseType: Decodable>(request:NSURLRequest, | |
success: (ResponseType) ->Void = {_ in }, | |
failure: () -> Void = {}) -> NSURLSessionDataTask { | |
let task : NSURLSessionDataTask = session.dataTaskWithRequest(request, | |
completionHandler: { (data, response, error) in | |
guard let response = response as? NSHTTPURLResponse else {failure(); return} | |
if (error == nil) && (200..<300 ~= response.statusCode) { | |
guard let data = data else {failure(); return} | |
do { | |
let json = JSON(data: data) | |
let model = try ResponseType.decode(json) | |
success(model) | |
} catch { | |
failure() | |
} | |
} else { | |
failure() | |
} | |
}) | |
task.resume() | |
return task | |
} | |
func getPopular(success: (Payload)-> Void) -> NSURLSessionDataTask { | |
let clientId = "e05c462ebd86446ea48a5af73769b602" | |
let url = NSURL(string:"https://api.instagram.com/v1/media/popular?client_id=\(clientId)") | |
let request = NSURLRequest(URL: url!) | |
return performRequest(request, success: success) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment