Created
June 6, 2014 22:42
-
-
Save frozzare/cfb79749e56b5abb00c7 to your computer and use it in GitHub Desktop.
Example of a web request class 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(); | |
} | |
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 waitFor (inout wait: Bool) { | |
while (wait) { | |
NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, | |
beforeDate: NSDate(timeIntervalSinceNow: 0.1)) | |
} | |
} | |
var wait: Bool = true | |
Request.get("http://svt.se", { (error: NSError?, data: NSData, text: NSString?) -> () in | |
println(text) | |
wait = false | |
}) | |
waitFor(&wait) |
A little bit confuse about line10 :
var done: (NSError?, NSData, NSString?) -> () = { (_, _, _) -> () in }
could you plz explain it?
Thank you!
I got this error:
Type NSData does not confirm to protocol NilLiteralConvertible
On line 42
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can you make an example of a post request with a parameter?