Categories
swift

Loading image from URL with SWIFT

Found this snippet provided by a stackoverflow user helpful. It loads a remote image async. Helps with performance when loading several images over the network to populate your table cells . This snippet extends the UIImageView Class with an added method imageFromURL(urlString:String) extension UIImageView { public func imageFromUrl(urlString: String) { if let url = NSURL(string: […]

Categories
ios swift

Making an HTTP POST Request in Swift

In this example I will be uploading an image to a node.js server. func makePostRequest(){ // create a instantiate a session let session = NSURLSession.sharedSession() // set url to POST to var url = NSURL(string: “http://yourdomain.com/post”) // create the request object var request = NSMutableURLRequest(URL: url!) request.HTTPMethod = “POST” request.HTTPBody = YOUR_REQUEST_BODY // set up the […]

Categories
ios swift

Creating a POST request body in Swift

// createRequestBody() func createRequestBody(photo:NSData){ var boundary:String = “——WebKitFormBoundaryasdas543wfsdfs5453533d3sdfsf3” var contentType = “multipart/form-data; boundary=\(boundary)” request.HTTPMethod = “POST” request.addValue(contentType, forHTTPHeaderField: “Content-Type”) var body = NSMutableData() body.appendData(NSString(format: “\r\n–%@\r\n”, boundary).dataUsingEncoding(NSUTF8StringEncoding)!) body.appendData(NSString(format: “Content-Disposition: form-data; name=\”photo\”; filename=\”photo.jpeg\”\r\n”).dataUsingEncoding(NSUTF8StringEncoding)!) body.appendData(NSString(format:”Content-Type: image/jpeg\r\n\r\n”).dataUsingEncoding(NSUTF8StringEncoding)!) body.appendData(photo) body.appendData(NSString(format: “\r\n–%@\r\n”, boundary).dataUsingEncoding(NSUTF8StringEncoding)!) println(body) // This will be the request body to post to your api/service }  Example of request body […]