Web View Not Displaying Content in Swift 2.0 - ios

I was following a tutorial to display content from a web view within my application. In swift 2.0, when I run the emulator I am getting no response on the emulator screen.
My code:
import UIKit
class ViewController: UIViewController {
#IBOutlet var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let url = NSURL(string: "http://www.stackoverflow.com")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {
(data, response, error) in
if error == nil {
var urlContent = NSString(data: data!, encoding: NSUTF8StringEncoding)
print(urlContent)
dispatch_async(dispatch_get_main_queue()) {
self.webView.loadHTMLString(urlContent! as String, baseURL: nil)
}
}
}
task.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

I'm pretty sure you should try to retain your data task.
Just declare stored property:
var task: NSURLSessionDataTask?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let url = NSURL(string: "http://www.stackoverflow.com")
task = NSURLSession.sharedSession().dataTaskWithURL(url!) {
(data, response, error) in
if error == nil {
var urlContent = NSString(data: data!, encoding: NSUTF8StringEncoding)
print(urlContent)
dispatch_async(dispatch_get_main_queue()) {
self.webView.loadHTMLString(urlContent! as String, baseURL: nil)
self.task = nil
}
}
}
task.resume()

Related

How to display YouTube search API response in UI text view?

I am creating a project where I have to display the YouTube search API response in a UI Text View when a button is clicked. Now I am getting the response in console.
1) How to display it as a JSON response.
2) How to display it in UI text view.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var resultTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func goButton(_ sender: Any) {
guard let url = URL(string: "https://www.youtube.com/watch?v=6Zf79Ns8_oY")else {
return
}
let session = URLSession.shared
let task = session.dataTask(with: url) {(data, response, error) in
if let response = response {
print(response)
}
if let jsondata = data {
print(jsondata)
}
}
task.resume()
}
}
I think you are looking for that:
Parse Response using JSONSerialization and set required value to textview text.
guard let url = URL(string: "https://www.youtube.com/watch?v=6Zf79Ns8_oY")else {
return
}
let session = URLSession.shared
let task = session.dataTask(with: url) {(data, response, error) in
guard let data = data, error == nil else { return }
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
let text = json["KEY"] as? String
DispatchQueue.main.async{
self.YOURTEXTVIEW.text = text
}
} catch let error as NSError {
print(error)
}
}
task.resume()
maybe it is helpful.

Invalid value around character 0 swift

I hope you are having a great day. I encountered an error that I did some research about. The error I think means that my JSON object is not a proper one to be serialized by the JSONSerialization class on swift 3.0. I verified that my json object is not valid by using the method .isValidJSONObject of the JSONSerialization class.
I checked that my json object is valid. The error occure at the line where "JSONSerialization.jsonObject" method execute. I would love if you can help me figure out how to solve this problem. Feel free to ask for more code parts or project settings. Thanks in advance.
Here is the code used:
import UIKit
class ViewController: UIViewController, NSURLConnectionDataDelegate {
lazy var receivedData = NSMutableData()
override func viewDidLoad() {
super.viewDidLoad()
var url = NSURL(string:"http://localhost:8080/OurServer/webresources/server")!
var request = NSURLRequest(url: url as URL)
var connection = NSURLConnection(request: request as URLRequest, delegate: self, startImmediately: false)!
connection.start()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func connection(_ connection: NSURLConnection, didReceive data: Data)
{
receivedData.append(data)
var temp1 = receivedData as NSMutableData
do
{
var temp3 = JSONSerialization.isValidJSONObject(receivedData)
var jsonResult = try JSONSerialization.jsonObject(with: receivedData as Data, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
print("\n")
print(jsonResult)
}
catch let error as NSError
{
print("\n" + "\(error)")
}
}
}
As mentioned in the comment NSURLConnection is outdated.
This is a modern, Swift 3 compliant version of your code using URLSession
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string:"http://localhost:8080/OurServer/webresources/server")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error!)
return
}
do {
let jsonResult = try JSONSerialization.jsonObject(with: data!) as! [String:Any]
print("\n", jsonResult)
} catch {
print("\n", error)
}
}
task.resume()
}
}
After checking, it appears i made a not very smart mistake. The mistake was with my url. excuse me for that guys.

Why do I need to use dispatch_async I think I am on the same thread

I have a login page in IOS using swift. When I click the SignIn button I start the login process that calls a function with delegate call backs on completion. This works fine, and my activity indicator starts spinning. The issue is, that when I get my delegate callbacks and I call the stopanimating() on the indicator it does not stop until about 6 seconds later. If I add the dispatch_async, it will stop animating right away. This makes me believe that I am not running on the same thread, but I do not see where this is happening.
EDIT: It looks like when I am calling in my Rest Function session.dataTaskWithRequest() that the block of code that is returned is not on the main thread, so when I call the delegates and return to the main code, it is not on the main thread? Is this correct? I can't find documentation that would explain that.
class Login_ViewController: UIViewController, RestServiceDelegate {
#IBOutlet weak var txtEmail: UITextField!
#IBOutlet weak var txtPassword: UITextField!
#IBOutlet weak var signInActivity: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func signInClick(sender: UIButton) {
signInActivity.startAnimating()
var restReq = RestRequest()
restReq.delegate = self
var restParams = ["userEmail":"\(txtEmail.text)", "password":"\(txtPassword.text)"] as Dictionary<String, String>
restReq.callRestAction(restParams, restAction: "AuthenticateUser")
}
func stopActivity()
{
println("Stopping the Activity Indiciator")
// WHY DOES THIS LINE TAKE FOREVER TO STOP ANIMATING?
self.signInActivity.stopAnimating()
// IF I UNCOMMENT THIS NEXT LINE IT WILL STOP THE ANIMATION!
//dispatch_async(dispatch_get_main_queue() , {self.signInActivity.stopAnimating()})
}
// MARK: - RestServiceDelegate
func restServiceEndedWithError(message : String, calledRestAction : String) {
stopActivity()
println("Error with Rest Request: \(message) for Action: \(calledRestAction)")
}
func restServiceResponse(jsonResponse : NSDictionary, calledRestAction : String) {
println("Response from Rest Request \(calledRestAction) with data \(jsonResponse)")
if let userAuth : AnyObject = jsonResponse["AuthenticateUserResult"] {
if userAuth as! Bool == true
{
println("User Authenticated: \(userAuth).")
}
else
{
println("Not Authenticated")
}
} else {
println("Not Authenticated")
}
stopActivity()
}
}
Here is the code when calling the Rest Action:
protocol RestServiceDelegate
{
func restServiceResponse(jsonResponse : NSDictionary , calledRestAction : String)
func restServiceEndedWithError(message : String, calledRestAction : String)
}
class RestRequest
{
let appToken : String = "blah blah blah"
let restURL : String = "http://blah blah blah"
var delegate : RestServiceDelegate?
func callRestAction(params : Dictionary<String,String>, restAction : String )
{
var url : String = restURL + restAction
println("CALLING REST URL: \(url)")
var request : NSMutableURLRequest = NSMutableURLRequest()
request.URL = NSURL(string: url)
request.HTTPMethod = "POST"
var session = NSURLSession.sharedSession()
var newParams = params
newParams.updateValue(appToken, forKey: "appToken")
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(newParams, options: nil, error: &err)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
println("Response: \(response)")
var strData : String = (NSString(data: data, encoding: NSUTF8StringEncoding) as? String)!
println("Returned Result (BODY): \(strData)")
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary
if(err != nil)
{
self.delegate!.restServiceEndedWithError(err!.localizedDescription, calledRestAction: restAction)
}
else
{
self.delegate!.restServiceResponse(json!, calledRestAction: restAction)
}
})
task.resume()
}
}

Can't use variable outside of scope method in Swift (dataTaskWithRequest)

#IBOutlet var nameLabel : UILabel!
var finalString: String = "test"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func helloWorldAction(nameTextField: UITextField) {
//fetch data from server
let request = NSMutableURLRequest(URL: NSURL(string: "http://192.168.1.11")!)
request.HTTPMethod = "POST"
let postString = "user=test&pass=test3"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
//error handeling
if error != nil {
println("error=\(error)")
return
}
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
self.finalString = String(responseString!)
println("\(self.finalString)");
}
task.resume()
//print finalString
println("finalString = \(finalString)")
}
}
I am trying to do two things, and I will tell you what isn't working with both.
First, not seen in this code, I was trying to assign a UILabel.text a value, that didn't work at all. I couldn't do it within the function and neither could I do it outside. This brings me to problem number two. When finalString is printed inside the function it outputs the proper value.
However, when its printed outside the function it prints the value it was first assigned. Please tell me how to assign the UILabel.text a value properly and how to use the output outside of the scope of the questions.
Thanks in advance.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var nameLabel: UITextField!
// you have to add a completion block to your asyncronous request
func fireRequest(link:String,completion: ((data: NSData?) -> Void)) {
if let requestUrl = NSURL(string: link){
let request = NSMutableURLRequest(URL: requestUrl)
request.HTTPMethod = "POST"
let postString = "user=test&pass=test3"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in
completion(data: NSData(data: data))
if let error = error {
println("error=\(error)")
return
}
}.resume()
}
}
override func viewDidLoad() {
super.viewDidLoad()
println("Fired request" + NSDate().description )
fireRequest("http://192.168.1.11") { data in
dispatch_async(dispatch_get_main_queue()) {
println("Finished request")
if let data = data { // unwrap your data (!= nil)
let myResponseStr = NSString(data: data, encoding: NSUTF8StringEncoding) as String
self.nameLabel.text = myResponseStr
println("response:"+myResponseStr)
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}

SwiftyJSON Problems

I am trying to extract some data out of a JSON object I am pulling in from Reddit, and am having issues when using the SwiftyJSON library (you can find this here: https://github.com/SwiftyJSON/SwiftyJSON).
I am calling Reddit's API at the following URL, "http://www.reddit.com/r/aww/hot.json" I am trying to extract a few key value pairs out of the json response, starting with the author of a listing.
My code is below:
import UIKit
class ViewController: UIViewController, NSURLConnectionDelegate {
var data = NSMutableData()
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.connectReddit()
}
func connectReddit() {
let urlPath: String = "http://www.reddit.com/r/aww/hot.json"
var url = NSURL(string: urlPath)!
var request = NSURLRequest(URL: url)
var connection = NSURLConnection(request: request, delegate: self, startImmediately: false)!
connection.start()
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
self.data.appendData(data)
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
var err: NSError?
// throwing an error on the line below (can't figure out where the error message is)
let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
println(jsonResult)
let json = JSON(data: data)
let authorName = json["data"]["children"]["author"].stringValue
println(authorName)
}
}
You can see the code calling the SwifyJSON class, trying to parse it for data is the following, I am getting nil as a response when I clearly see data there.
let json = JSON(data: data)
let authorName = json["data"]["children"]["author"].stringValue
println(authorName)
I am not sure what I am doing wrong here.
Thanks for the help!
you should try this ;
let authorName = json["data"]["children"][0]["data"]["author"].stringValue
For Swift 3.0.1:
let authorName = json["data"]["children"][0]["data"]["author"].string

Resources