Unable to cancel a dial pad in phone number - ios

I think so This question is not duplicate one.
Call to phone number when touching cancel Action my app throws app to initial screen instead of displaying current screen.
Is this a bug in iOS11 or is there something that I am doing wrong from following code. this is my code.
#objc func CallAction(_ sender : UIButton)
{
var localDic :NSDictionary!
if is_searching {
localDic = searchingDataArray.object(at: sender.tag) as! NSDictionary
}else
{
localDic = myStudentsArray.object(at: sender.tag) as! NSDictionary
}
let phoneNumber=localDic["contact_no"] as! String
print("phoneNumber",phoneNumber )
guard let number = URL(string: "tel://" + phoneNumber) else { return }
UIApplication.shared.open(number)
}

Use the following code
guard let telNumber = URL(string: "telprompt://" + "+1234-567-89") else { return }
if #available(iOS 10.0, *) {
UIApplication.shared.open(telNumber)
} else {
// Fallback on earlier versions
}
hope its works..

Related

add prefix to uiTextField in swift

I am trying to add country code as prefix to textField so the user can enter the rest of his phone number
#IBAction func phoneLogin(_ sender: Any) {
let countryCode = "+1"
guard let phoneNumber = countryCode + MobileLbl.text! else { return }
if ((MobileLbl.text?.isEmpty) != nil) {
print("Fill Your Number")
}else {
OTPtxt.isHidden = false
VerifyBtn.isHidden = false
PhoneAuthProvider.provider().verifyPhoneNumber(phoneNumber, uiDelegate: nil) { (verificationId, error) in
if error == nil {
guard let verifyId = verificationId else { return }
self.def.setValue(verifyId, forKey: "verificationId")
self.def.synchronize()
print(verificationId)
} else {
print("Unable to get Secret verification from firebase", error?.localizedDescription)
}
}
}
}
I got this error Initializer for conditional binding must have Optional type, not 'String'
You're force unwrapping MobileLbl.text! which no longer makes it optional. Take off the exclamation point so it's just MobileLbl.text. Also have to move countryCode to another line as it isn't optional either.
let countryCode = "+1"
guard let phone = MobileLbl.text else { return nil }
let phoneNumber = countryCode + phone

Can't get UIButton to call block of code in Swift 4

I am trying to call a large block of code to run once a button (GoButton) is clicked, I have tried doing it this way but it just crashes, I also sometimes get the error that my button is equal to nil. any advice? All of the code below works just fine without the button being there, I want it to run once pressed. Also I'm new to swift programming so sorry if this is really easy. Thanks
Code Below:
override func viewDidLoad() {
super.viewDidLoad()
func GoButton(_ sender: Any) {
guard let APIUrl = URL(string: "https://api.openweathermap.org/data/2.5/weather?q=Crowland&appid=***APIKEY***&units=Metric") else { return }
URLSession.shared.dataTask(with: APIUrl) { data, response, error in
guard let data = data else { return }
let decoder = JSONDecoder()
do {
let weatherData = try decoder.decode(MyWeather.self, from: data)
if (self.MainLabel != nil)
{
if let gmain = weatherData.weather?.description {
print(gmain)
DispatchQueue.main.async {
self.MainLabel.text! = "Current Weather in: " + String (gmain)
}
}
}
if (self.LocationLabel != nil)
{
if let gmain = weatherData.name {
print(gmain)
DispatchQueue.main.async {
self.LocationLabel.text! = "Current Weather in: " + String (gmain)
}
}
}
if (self.HumidityLabel != nil)
{
if let ghumidity = weatherData.main?.humidity
{
print(ghumidity, "THIS IS HUMIDITY")
DispatchQueue.main.async {
self.HumidityLabel.text! = String (ghumidity)
}
}
}
if (self.WindLabel != nil)
{
if let gspeed = weatherData.wind?.speed {
print(gspeed, "THIS IS THE SPEED")
DispatchQueue.main.async {
self.WindLabel.text! = String(gspeed) + " mph"
}
}
}
if (self.TempLabel != nil)
{
if let ggtemp = weatherData.main?.temp {
print(ggtemp, "THIS IS THE TEMP")
DispatchQueue.main.async {
self.TempLabel.text! = String (ggtemp) + " c"
}
}
}
} catch {
print(error.localizedDescription)
}
}.resume()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
It seems like your GoButton function is somehow inside your viewDidLoad method? This should definitely not be the case as nested functions are hidden from the outside world by default.
If you are using storyboard, the correct way to link a button click to an action is to do it through the storyboard and IBActions. There are very many video/text tutorials showing you how to do so. Here is a video tutorial that I personally liked because of its clarity given that you are new to Swift - https://www.youtube.com/watch?v=Opz3juSW43Q. (I neither own nor have any affiliation with the video content in this link, I am merely linking it here as I think it might be helpful).

My progress bar can't load after back to main view and go back to download view again

I have 2 page in storyboard by using navigation controller
I use alamofire for download file and I set progress bar in download page after I tap back to main pain and go to download view again, the progress don't load but in background it print percent normally
my custom cell code:
func downloadBook(bookID:String,downloadURLString:String) {
//set up UI
self.loadingLabel.text = "Preparing"
UserDefaults.standard.set(kStatusPreparing, forKey: "HP\(bookID).pdf")
self.isUserInteractionEnabled = false
if let url = URL(string: downloadURLString) {
self.delegate?.didTapDownloadBook(bookID: bookID, downloadURL: url)
}
}
#IBAction func selectBook(_ sender: Any) {
if UserDefaults.standard.integer(forKey: "HP\(bookID!).pdf") == kStatusSuccess {
self.delegate?.openWebView(bookId: bookID!)
}else if (UserDefaults.standard.integer(forKey: "HP\(bookID!).pdf") == kStatusNotDownload){
let urlString = "http://www.narutoroyal.com/HP\(bookID!).pdf"
downloadBook(bookID: bookID!, downloadURLString: urlString)
}
}
and in my main view download code here:
func updateCellProgress(bookID: String,progress:Double) {
let visibleCell = collectionBook.visibleCells as! [LoadingCollectionViewCell]
for cell in visibleCell {
if cell.bookID == bookID {
print("Download Progress: \(progress*100)")
cell.loadingLabel.text = String(format: "%.2f", progress*100)
}
}
}
func updateCellStatus(bookID: String) {
let visibleCell = collectionBook.visibleCells as! [LoadingCollectionViewCell]
for cell in visibleCell {
if cell.bookID == bookID {
cell.loadingLabel.text = "Open"
cell.isUserInteractionEnabled = true
}
}
}
extension ViewController : LoadingCollectionViewCellDelegate {
func didTapDownloadBook(bookID: String, downloadURL: URL) {
Alamofire.request(downloadURL).downloadProgress(closure: { (progress) in
self.updateCellProgress(bookID: bookID,progress: progress.fractionCompleted)
}).responseData { (response) in
if let data = response.result.value {
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileURL = documentsURL.appendingPathComponent("HP\(bookID).pdf")
do {
try data.write(to:fileURL, options: .atomic)
UserDefaults.standard.set(kStatusSuccess, forKey: "HP\(bookID).pdf")
self.updateCellStatus(bookID: bookID)
} catch {
print(error)
}
}
}
}
}
here my full code : https://github.com/dekphoenix/downloadprogress
ps. please help me I stuck in this many days T^T

Swift 3 Open Link

I'm trying to run this function when a button is tapped:
#IBAction func openLink(_ sender: UIButton) {
let link1 = "https://www.google.com/#q="
let link2 = birdName.text!
let link3 = link2.replacingOccurrences(of: " ", with: "+") //EDIT
let link4 = link1+link3
guard
let query = link4.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed),
let url = NSURL(string: "https://google.com/#q=\(query)")
else { return }
UIApplication.shared.openURL(URL(url))
}
However, the last line is flagged as "cannot call value of non-function type "UIApplication". This syntax is from here, so I'm not sure whats going on.
Use guard to unwrap the textfield text property, replacing the occurrences, add percent encoding to the result and create an URL from the resulting string:
Try like this:
guard
let text = birdName.text?.replacingOccurrences(of: " ", with: "+"),
let query = text.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
let url = URL(string: "https://google.com/#q=" + query)
else { return }
if #available(iOS 10.0, *) {
UIApplication.shared.open(url)
} else {
UIApplication.shared.openURL(url)
}

adding URL link to UIButton from JSON data

I am trying to link an button on the UI to a link that I receive after parsing a JSON response. I've added an outlet to the button with the a variable containing the link.
#IBAction func goOnline(sender: AnyObject) {
UIApplication.sharedApplication().openURL(prodURL)
}
I parse the JSON data in a method called in viewDidLoad.
if let convertedJSONIntoDict = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String: AnyObject] {
if let JSONurl = convertedJSONIntoDict["url"] as? String {
dispatch_async(dispatch_get_main_queue()) { () -> Void in
self.prodURL = NSURL(string: JSONurl)!
}
}
}
When I click on the button I don't get any response. As always, any help is much appreciated.
i dont have enough reputation to comment so i am adding here
what value do you get in json url???
even you dont need to save the value in the main queue you can also write like
self.prodURL = NSURL(string: JSONurl)!
Swift 3
Define your strings and variables and then it's the following code:
#IBAction func websiteButton(_ sender: Any) {
let websiteURL = ("http://") + JSONurl!
guard let url = URL(string: websiteURL) else {
return //be safe
}
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
}
That should work.

Resources