Difference between revisions of "Swift code snippets"

From Hawk Wiki
Jump to: navigation, search
(Making Network Request)
Line 1: Line 1:
 
==Making Network Request==
 
==Making Network Request==
<pre>
+
<pre class="brush:swift">
 
var clientId = "Put your client id here"
 
var clientId = "Put your client id here"
 
   
 
   
Line 13: Line 13:
 
}
 
}
 
</pre>
 
</pre>
 +
 
==Use setImageWithURL==
 
==Use setImageWithURL==
 
Create the bridging file: create a new Objective-C file, name it anything, and when you save it, Xcode will prompt you generate a bridging file. <br>
 
Create the bridging file: create a new Objective-C file, name it anything, and when you save it, Xcode will prompt you generate a bridging file. <br>

Revision as of 00:02, 20 February 2015

Making Network Request

var clientId = "Put your client id here"
 
var url = NSURL(string: "https://api.instagram.com/v1/media/popular?client_id=\(clientId)")!
var request = NSURLRequest(URL: url)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
    var responseDictionary = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as NSDictionary
    self.photos = responseDictionary["data"] as NSArray
    self.tableView.reloadData()
    
    println("response: \(self.photos)")
}

Use setImageWithURL

Create the bridging file: create a new Objective-C file, name it anything, and when you save it, Xcode will prompt you generate a bridging file.
In an Objective-C bridging file:

#import <AFNetworking/UIImageView+AFNetworking.h>

In the swift view file, to set a imageView using URL:

setImageWithURL(NSURL(string: thumbnail))

Adding UIRefreshControl

//refreshControl is automatically defined in UITableViewController
override func viewDidLoad() {
    super.viewDidLoad()
    
    refreshControl = UIRefreshControl()
    refreshControl.addTarget(self, action: "onRefresh", forControlEvents: UIControlEvents.ValueChanged)
    scrollView.insertSubview(refreshControl, atIndex: 0)
}

//to stop refresh, call
self.refreshControl.endRefreshing()

Example of fetching messages from Parse

https://gist.github.com/sandofsky/7134b1ff90d235901254