Last active
February 4, 2020 06:14
-
-
Save seyhunak/40686ae8fbc565877e7d to your computer and use it in GitHub Desktop.
NSURLRequest in 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
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Isn't update with Swift 3 😭