Swift - UILabel from URL

490 views Asked by At

I wanted to know if it's possible to load the text in a label from a URL.

I was going to try and use NSURL to pull in a .txt file stored online.

Would anyone know how to implement this with swift?

Thanks

2

There are 2 answers

2
Woodstock On BEST ANSWER

If you don't want to use sessions, you can also use the simpler NSURLConnection Class, something like this:

let url = NSURL(string: "https://wordpress.org/plugins/about/readme.txt")

let request = NSURLRequest(URL: url!)

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
    println(NSString(data: data, encoding: NSUTF8StringEncoding))




    dispatch_async(dispatch_get_main_queue()) {

        // Do stuff on the UI thread
        self.textField.text = NSString(data: data, encoding: NSUTF8StringEncoding)! as String
        return
    }

}
1
Duncan C On

Yes it's possible. Yes, I know how to do it. However, you haven't exerted any effort whatsoever to solve your problem yourself.

Search on NSURLConnection. Unless you need https or login, you could use the class method sendAsynchronousRequest:queue:completionHandler:, which is very easy to use. You should be able to find examples of using it on the net.

You could also use a library like Alamofire. That makes it even easier.