Setting which Text view to use to open Url - ios

Hello am making an app where the user presses an butten and a random link opens! But i have problems with making the textview were the user presses to recognize that it is a Url to open
import UIKit
import StoreKit
class ViewController: UIViewController, UITextViewDelegate,
NSObjectProtocol {
#IBOutlet weak var randomButton: UIButton!
#IBOutlet weak var firsttext: UITextView!
let links =
["http://www.google.com","http://www.yahoo.com",
"http://www.discovery.com"]
var currentLinkIndex : Int = 0
override func viewDidLoad() {
super.viewDidLoad()
firsttext.delegate = self
}
func textview(textview: UITextView!, shouldInteractWithURL URL: NSURL,
inRange characterRange: NSRange) -> Bool {
let url = NSURL(string:links[currentLinkIndex])
UIApplication.sharedApplication().openURL(url!)
return false
}
#IBAction func randomButtonaction(sender: UIButton) {
let random : Int = Int(arc4random()) % 3
firsttext.text = links[random]
currentLinkIndex = random
}
}
Do i have to inside "func textview...ShouldinteractWithUrl..." name that i want the firsttext to be the one thats should be enable to interact with url and then open? How do i set it to do so?

Related

Delegate and DataSource not woking in MessageKit Swift IOS

I'm using the MessageKit for chating when I calling the its delegate and datasource it saying (Cannot find 'messagesCollectionView' in scope) please see the code and guide me thanks.
import UIKit
import FirebaseAuth
import MessageKit
struct Message: MessageType{
var sender: SenderType
var messageId: String
var sentDate: Date
var kind: MessageKind
}
struct sender: SenderType{
var photo: String
var senderId: String
var displayName: String
}
class ChatDashboard: UIViewController {
#IBOutlet weak var lblUser: UILabel!
var userActive: String? = nil
override func viewDidLoad() {
super.viewDidLoad()
messagesCollectionView.messagesDataSource = self
messagesCollectionView.messagesLayoutDelegate = self
messagesCollectionView.messagesDisplayDelegate = self //not working delegate and datasource
if let userData = userActive{
self.lblUser.text = userData
}
}
override func viewDidAppear(_ animated: Bool) {
}
}
Have a look at their example project usage.
Should clear out lots of confusion.
Link: https://github.com/MessageKit/MessageKit/tree/master/Example
As for your query,
Can't find messagesCollectionView because MessagesViewControllerneeds to be extended to access that.

Trying to do a conversion of Bin to hex onto swift language

Could someone see with wrong with this when i submit doesn't seem to show the answer as the label. If anyone could show me how to fix it!
import UIKit
class ViewTwo: UIViewController {
#IBOutlet weak var num: UITextField!
#IBOutlet weak var hex: UILabel!
#IBAction func binToHex(_ sender: Any) {
}
func binToHex(bin : String) -> String {
let num = bin.withCString { strtoul($0, nil, 2) }
let hex = String(num, radix: 16, uppercase: true)
return hex
}
}
Your hex conversion seems to work, but you are not setting the hex result to label in your button target. Set that like this
#IBAction func binToHex(_ sender: Any) {
self.hex.text = binToHex(bin: "1010")
}

iOS Swift - Properties not updating after preparing for segue

I am trying to pass a news ID of type string to the second VC and load the object based on it from Realm. When I debugged, I found that the prepare for segue is correctly setting the detailNewsVC.newsID to the primary key of my news item but the second VC is not receiving it. Any help on this?
Checks I have made:
Made sure that the detail VC identifier is correct
detailNewsVC.newsID in VC 1 is correctly setting the news ID .. This is to make sure that realm is correctly sending the newsID and it is working fine.
Changed the viewDidLoad in VC 2 to viewWillLoad..Just to make sure that second vc is not loaded before for any reason but no luck on that.
Restarted xcode
Replaced newsID in VC 2 with an actual news primary key and it's correctly pulling the related news. I think the culprit is that the VC2 property: newsID is not updating when prepare for segue is called.
First VC code for prep for segue:
extension HomeVC: UICollectionViewDelegate {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == SegueIdentifier.gotodetail.rawValue, let sendNewsID = sender as? String {
let navVC = segue.destination as? UINavigationController
let detailNewsVC = navVC?.viewControllers.first as! DetailNewsVC
detailNewsVC.newsID = sendNewsID
print("Detail News ID = \(detailNewsVC.newsID)")
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let newsID = newsArray[indexPath.row].newsId
performSegue(withIdentifier: SegueIdentifier.gotodetail.rawValue, sender: newsID)
}
}
Second VC Code:
class DetailNewsVC: UIViewController {
#IBOutlet private weak var scrollView: UIScrollView!
#IBOutlet private weak var newsTitle: UILabel!
#IBOutlet private weak var newsImage: UIImageView!
#IBOutlet private weak var newsDescription: UILabel!
var newsID = ""
override func viewDidLoad() {
super.viewDidLoad()
let realm = try! Realm()
print("News ID: \(newsID)")
guard let news = realm.object(ofType: News.self, forPrimaryKey: newsID as AnyObject) else {
print("Cannot load news")
return
}
print(news)
newsTitle.text = news.newsTitle
if let url = URL(string: news.urlToImage), let data = try? Data.init(contentsOf: url) {
newsImage.image = UIImage(data: data)
}
newsDescription.text = news.newsDescription
}
}
Move your prepare function out of the extension and put it in HomeVC. According to Apple's Swift Guide extensions cannot override existing functionality.
Extensions can add new functionality to a type, but they cannot override existing functionality.
Apple Developer Guide
It's hard to tell in which order UIKit calls the UIViewController methods, but it might be possible that viewDidLoad is getting called before you get the chance to set the value of newsID.
The following might be overkill, but it'll guarantee the views will be updated during viewDidLoad, or otherwise if newsID is set after the fact:
class DetailNewsVC: UIViewController {
#IBOutlet private weak var scrollView: UIScrollView!
#IBOutlet private weak var newsTitle: UILabel!
#IBOutlet private weak var newsImage: UIImageView!
#IBOutlet private weak var newsDescription: UILabel!
public var newsID = "" {
didSet {
updateUIForNews()
}
}
override func viewDidLoad() {
super.viewDidLoad()
updateUIForNews()
}
private func updateUIForNews() {
guard !newsID.isEmpty else {
return
}
let realm = try! Realm()
print("News ID: \(newsID)")
guard let news = realm.object(ofType: News.self, forPrimaryKey: newsID as AnyObject) else {
print("Cannot load news")
return
}
print(news)
newsTitle.text = news.newsTitle
if let url = URL(string: news.urlToImage), let data = try? Data.init(contentsOf: url) {
newsImage.image = UIImage(data: data)
}
newsDescription.text = news.newsDescription
}
}

Make UIButton Click Display UIWebview

I'm trying to load a specific URL after clicking a button. I have the webView code inside of a UIButton action, but I'm not sure how to pull that into the display/viewDidLoad method it will work. But I need to be able to change the URL with different buttons.
import UIKit
class ViewController: UIViewController {
var radioURL = "http://www.ladiescanwetalk.org/category/podcasts/"
#IBOutlet weak var mainWebView: UIWebView!
#IBAction func loadRadioView(sender: UIButton) {
let getCurrentURL = NSURL (string: radioURL)
let requestCurrentURL = NSURLRequest(URL: getCurrentURL!)
self.mainWebView?.loadRequest(requestCurrentURL)
}
override func viewDidLoad() {
super.viewDidLoad()
}
In my opinion the best to achieve what you're asking is to set a different tag value for each value (you can do this either using Storyboard or directly via code).
Your code will be something like this:
#IBAction func loadRadioView(sender: UIButton) {
if sender.tag == 1 {
radioURL = "http://anotherUrl"
} else if sender.tag == 2 {
radioURL = "http://yetanotherurl"
} else if sender.tag == 3 {
radioURL = "http://....."
}
let getCurrentURL = NSURL (string: radioURL)
let requestCurrentURL = NSURLRequest(URL: getCurrentURL!)
self.mainWebView?.loadRequest(requestCurrentURL)
}

how change a piece of Url with Textbox & Button?(Swift 2)

this is my code but its give me nil in output.
import AVFoundation
import AVKit
import UIKit
var userName :String?
class ViewController: UIViewController {
var movieUrl:NSURL? = NSURL(string: "http://streamapp.ir:1935/lahzenegar/\(userName)/playlist.m3u8")
#IBOutlet var inpt: UITextField!
#IBOutlet var scView: UIScrollView!
let avPlayerViewController = AVPlayerViewController()
var avPlayer: AVPlayer?
override func viewDidLoad() {
super.viewDidLoad()
}
and my button code:
#IBAction func playButtonTapped3(sender: UIButton) {
userName = "\(self.inpt.text)"
self.presentViewController(self.avPlayerViewController, animated: true) { () -> Void in
self.avPlayerViewController.player?.play()
}
print(movieUrl)
}
so i want when press button (username) change value to whatever users entered in textBox
already output:
thanks for help
When you first create the movieURL the userName is not set. That is fine, however, when you press the button you need to update the movieURL as well as the username. Something like this:
userName = "\(self.inpt.text)"
movieURL = NSURL(string: "http://streamapp.ir:1935/lahzenegar/\(userName)/playlist.m3u8")

Resources