Skip to content

Instantly share code, notes, and snippets.

@gazolla
Last active September 20, 2016 15:51
Show Gist options
  • Save gazolla/1d8f5802fa3503be2ba4e4a9601ff787 to your computer and use it in GitHub Desktop.
Save gazolla/1d8f5802fa3503be2ba4e4a9601ff787 to your computer and use it in GitHub Desktop.
HTTP encapsulation
//
// HTTP.swift
// TableTest2
//
// Created by Gazolla on 22/05/16.
// Copyright © 2016 Gazolla. All rights reserved.
//
import Foundation
import UIKit
public class HTTP{
static func GET(urlString:String, completion:(error:NSError?, data:NSData?)->Void){
if let request = NSMutableURLRequest(urlString: urlString, method: .GET) {
connectToServer(request, completion: completion)
} else {
let er = NSError(domain: "com.gazapps", code: 400, userInfo: [NSLocalizedDescriptionKey: NSHTTPURLResponse.localizedStringForStatusCode(400)])
completion(error: er, data: nil)
}
}
static func connectToServer(request:NSMutableURLRequest, completion:(error:NSError?, data:NSData?)->Void){
startNetworkActivityIndicator()
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let task = session.dataTaskWithRequest(request) { (data, response, error) in
stopNetworkActivityIndicator()
if error != nil {
completion(error: error, data: nil)
} else if let httpResponse = response as? NSHTTPURLResponse {
if 200...299 ~= httpResponse.statusCode {
completion(error: nil, data: data)
} else {
let er = NSError(domain: "com.gazapps", code: httpResponse.statusCode, userInfo: [NSLocalizedDescriptionKey: NSHTTPURLResponse.localizedStringForStatusCode(httpResponse.statusCode)])
completion(error: er, data: nil)
}
}
}
task.resume()
}
static func startNetworkActivityIndicator(){
dispatch_async(dispatch_get_main_queue()) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
}
}
static func stopNetworkActivityIndicator(){
dispatch_async(dispatch_get_main_queue()) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
}
}
extension NSMutableURLRequest {
public convenience init?(urlString:String, method:HTTPVerb, body:NSData?=nil){
if let url = NSURL(string:urlString) {
self.init(URL:url)
self.addValue("application/json", forHTTPHeaderField: "Content-Type")
self.addValue("application/json", forHTTPHeaderField: "Accept")
self.HTTPMethod = method.rawValue
self.HTTPBody = body
} else {
return nil
}
}
}
public enum HTTPVerb:String {
case GET
case PUT
case POST
case DELETE
}
var items:[String]=[]
HTTP.GET("https://api.github.com/users/gazolla/repos") { (error, data) in
if error != nil {
print(error)
}
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: [])
for item in json as! [AnyObject]{
self.items.append(item["full_name"] as! String)
}
} catch {
print(error)
}
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment