Skip to content

Instantly share code, notes, and snippets.

@seyhunak
Last active February 4, 2020 06:14
Show Gist options
  • Save seyhunak/40686ae8fbc565877e7d to your computer and use it in GitHub Desktop.
Save seyhunak/40686ae8fbc565877e7d to your computer and use it in GitHub Desktop.
NSURLRequest in Swift
import Foundation
class Request : NSObject {
var url : NSURL? = nil
var request : NSMutableURLRequest? = nil
var response : NSHTTPURLResponse? = nil
var data: NSMutableData? = nil
var done: (NSError?, NSData, NSString?) -> () = { (_, _, _) -> () in }
init (method: String, url: String, done: (NSError?, NSData, NSString?) -> ()) {
let _url = NSURL(string: url)
self.request = NSMutableURLRequest(URL: _url)
self.request!.HTTPMethod = method;
self.done = done
self.data = NSMutableData()
}
func start () {
let connection = NSURLConnection(request: self.request, delegate: self, startImmediately: true)
}
class func get(url: String, done: (NSError?, NSData, NSString?) -> ()) -> Void {
return Request(method: "GET", url: url, done: done).start();
}
class func post(url: String, done: (NSError?, NSData, NSString?) -> ()) -> Void {
return Request(method: "POST", url: url, done: done).start();
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
self.data!.appendData(data)
}
func connection(connection: NSURLConnection!, didReceiveResponse response: NSHTTPURLResponse!) {
self.response = response
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
let text = NSString(data: self.data, encoding: NSUTF8StringEncoding)
self.done(nil, self.data!, text)
}
func connection(connection: NSURLConnection!, didFailWithError error: NSError!) {
self.done(error, nil!, nil)
}
}
func delayFor(inout delay: Bool) {
while (delay) {
NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode,
beforeDate: NSDate(timeIntervalSinceNow: 0.1))
}
}
// Usage
var delay: Bool = true
Request.get("http://google.com", { (error: NSError?, data: NSData, text: NSString?) -> () in
println(text)
})
delayFor(&delay)
@mayooresan
Copy link

Isn't update with Swift 3 😭

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment