I want to call phone number "#51234" in Xcode use telprompt [duplicate] - ios

This question already has answers here:
Phone call number with hashtag on iOS
(3 answers)
Closed 4 years ago.
I want to call phone number "#51234" in Xcode use telprompt.
but telprompt is reject it.
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:#"telprompt://#5%#", nzoneNum]]];
nzomeNum is "1234"

At least as of iOS 11, one can dial numbers with a hashtag (#) or asterisk (*).
Make calls with these characters by first encoding the phone number, then adding the tel: prefix, and finally turning the resulting string into a URL.
Swift 4, iOS 11
// set up the dial sequence
let nzoneNum = "1234"
let prefix = "#5"
let dialSequence = "\(prefix)\(nzoneNum)"
// "percent encode" the dial sequence with the URL Host allowed character set
guard let encodedDialSequence =
dialSequence.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) else {
print("Unable to encode the dial sequence.")
return
}
// add the `tel:` url scheme to the front of the encoded string
let dialURLString = "tel:\(encodedDialSequence)"
// set up the URL with the scheme/encoded number string
guard let dialURL = URL(string: dialURLString) else {
print("Couldn't make the dial string into an URL.")
return
}
// dial the URL
UIApplication.shared.open(dialURL, options: [:]) { success in
if success { print("SUCCESSFULLY OPENED DIAL URL") }
else { print("COULDN'T OPEN DIAL URL") }
}
Objective-C, iOS 11
// set up the dial sequence
NSString *nzoneNum = #"1234";
NSString *prefix = #"#5";
NSString *dialSequence = [NSString stringWithFormat:#"%#%#", prefix, nzoneNum];
// set up the URL Host allowed character set, and "percent encode" the dial sequence
NSCharacterSet *urlHostAllowed = [NSCharacterSet URLHostAllowedCharacterSet];
NSString *encodedDialSequence = [dialSequence stringByAddingPercentEncodingWithAllowedCharacters:urlHostAllowed];
// add the `tel` url scheme to the front of the encoded string
NSString *dialURLString = [NSString stringWithFormat:#"tel:%#", encodedDialSequence];
// set up the URL with the scheme/encoded number string
NSURL *dialURL = [NSURL URLWithString:dialURLString];
// set up an empty dictionary for the options parameter
NSDictionary *optionsDict = [[NSDictionary alloc] init];
// dial the URL
[[UIApplication sharedApplication] openURL:dialURL
options:optionsDict
completionHandler:^(BOOL success) {
if (success) { NSLog(#"SUCCESSFULLY OPENED DIAL URL"); }
else { NSLog(#"COULDN'T OPEN DIAL URL"); }
}];

Unfortunately you can't make calls to any number including a hashtag. Apple clearly restricts those calls: iPhoneURLScheme_Reference
To prevent users from maliciously redirecting phone calls or changing the behavior of a phone or account, the Phone app supports most, but not all, of the special characters in the tel scheme. Specifically, if a URL contains the * or # characters, the Phone app does not attempt to dial the corresponding phone number.

Related

iOS URL Scheme Microsoft Outlook App

This seems impossible to find, unless perhaps there isn't one for it. But anyone know (if there is one) the iOS URL Scheme for opening the Microsoft Outlook Mobile App right to the Compose Screen with pre-defined TO_EMAIL, SUBJECT and BODY?
Here is a link I found that helped me out with the IOS Outlook URL Scheme.
From that I was able to come up with this code:
// Create an array of recipients for the email.
NSArray* emailRecipients = #[#"example#email.com", #"example2#email.com"];
// Create a mutable string to hold all of the recipient email addresses and add the first one.
NSMutableString* emailTo = [[NSMutableString alloc] initWithString:emailRecipients[0]];
// Loop through all of the email recipients except for the first one.
for (int index = 1; index < emailRecipients.count; index++)
{
// Add a semicolon and then the email address at the current index.
[emailTo appendFormat:#";%#", emailRecipients[index]];
}
// Get the email subject from the subject text field.
NSString* emailSubject = fieldSubject.text;
// Encode the string for URL.
NSString* encodedSubject = [emailSubject stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
// Get the email body from the body text field.
NSString* emailBody = fieldBody.text;
// Encode the string for URL.
NSString* encodedBody = [emailBody stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
// See if the subject or body are empty.
if (![emailSubject length] || ![emailBody length])
{
// Exit.
return;
}
// Create a string with the URL scheme and email properties.
NSString *stringURL = [NSString stringWithFormat:#"ms-outlook://compose?to=%#&subject=%#&body=%#", emailTo, encodedSubject, encodedBody];
// Convert the string to a URL.
NSURL *url = [NSURL URLWithString:stringURL];
// Open the app that responds to the URL scheme (should be Outlook).
[[UIApplication sharedApplication] openURL:url];
The URL scheme for Outlook is: ms-outlook://compose?to=example#email.com&subject=Subject&body=Message
Hope this helps!
Swift
func outlookDeepLink(subject: String, body: String, recipients: [String]) throws -> URL {
enum MailComposeError: Error {
case emptySubject
case emptyBody
case unexpectedError
}
guard !subject.isEmpty else { throw MailComposeError.emptySubject }
guard !body.isEmpty else { throw MailComposeError.emptyBody }
let emailTo = recipients.joined(separator: ";")
var components = URLComponents()
components.scheme = "ms-outlook"
components.host = "compose"
components.queryItems = [
URLQueryItem(name: "to", value: emailTo),
URLQueryItem(name: "subject", value: subject),
URLQueryItem(name: "body", value: body),
]
guard let deepURL = components.url else { throw MailComposeError.unexpectedError }
return deepURL
}
Usage
try! UIApplication.shared.open(
outlookDeepLink(
subject: "subject",
body: "body",
recipients: ["example#email.com", "example2#email.com"]
)
)
Note that:
Don't forget to tell iOS you are going to call ms-outlook. (Add it to LSApplicationQueriesSchemes in info.plist, Otherwise, You will get an clear error message in console if you forget it)
Also don't forget to check if the app actually exists before trying to open the url. (canOpenURL is here to help)

Retrieving and Parsing Text From Specific Webpage Using Swift

I need to retrieve the text from a specific website. However, I only need a few parts of it. How can I accomplish this using swift.
I have found the following in objective-c, but am not sure it provides how to reference it from a specific site:
NSString *webString = [webView stringByEvaluatingJavaScriptFromString:#"document.documentElement.innerText"];
NSScanner *stringScanner = [NSScanner scannerWithString:webString];
NSString *content = [[NSString alloc] init];
while ([stringScanner isAtEnd] == NO) {
[stringScanner scanUpToString:#"Start of the text you want" intoString:null];
[stringScanner scanUpToString:#"End of the text you want" intoString:&content];
}`
I have put an example of what I mean below:
Again, I would like to accomplish this using Swift.
If your HTML was easily targetable with identifiers or class names, I would suggest using a library such as Kanna. But I've had a look at your page and the text you need is lost amidst an ocean of divs...
So I've quickly hacked a way to get your text with componentsSeparatedByString: I'm cutting the HTML in blocks until I get to the part we're interested in.
Note that it's far from being the most efficient way: instead of using componentsSeparatedByString you should come with a way of identifying the HTML block you want and search for it with NSScanner.
That being said, here's my example of a working hack, tested in a Playground:
enum CustomErrors : String, ErrorType {
case InvalidURL = "Invalid URL"
}
do {
let str = "http://www.golfwrx.com/328370/mizuno-to-offer-custom-grips-at-no-additional-charge/"
guard let url = NSURL(string: str) else { throw CustomErrors.InvalidURL }
let html = try String(contentsOfURL: url)
let separator1 = "<div class='mailmunch-forms-before-post' style='display: none !important;'></div><p>"
let temp = html.componentsSeparatedByString(separator1)
let separator2 = "</p>\n<p>"
let temp2 = temp[1].componentsSeparatedByString(separator2)
let separator3 = "</p><div class='mailmunch-forms-in-post-middle'"
let separated = temp2[1].componentsSeparatedByString(separator3)
let result = separated[0]
print(result)
} catch {
print(error)
}
Note: my example is in Swift 2 (Xcode 7).
Sorry about the specifics, I'm an Objective-C guy. but, here is an example of how to use NString to get the contents of a websites HTML
NSString *url = #"http://www.example.com"; // Your URL
NSURL *urlRequest = [NSURL URLWithString:url]; // Make a request with your URL
NSError *err = nil; // Error handler
NSString *html = [NSString stringWithContentsOfURL:urlRequest encoding:NSUTF8StringEncoding error:&err]; // Try to get the HTML in the string
if(err)
{
//Do something as it didn't work! Maybe a connection problem
}
else
{
// Use NScanner on html string
}
http://nshipster.com/nsscanner/ is a good place to learn about NScanner for swift
EDIT: Here is the above translated to swift
var err: NSError? // Error handler
let url: NSURL = NSURL(string: "http://www.example.com") // NSURL, put your website URL in here
let string = NSString(contentsOfURL: url, encoding: NSUTF8StringEncoding, error: &err) // String will now hold your HTML
// Now use NScanner (See Link) to parse the HTML output
My swift is rusty. but this might help you. This is roughly translated but outlines exactly what you need

URL encoding iOS NSURL error

URL which opens in Firefox,Chrome browsers on desktop, doesn't open in WebView on iPhone.
This URL is supposedly accessing a GET request.
When creating the NSURL without percentescaping the url doesn't get generated.
When using percentescape the url redirects to a Bad url content.
Is there a different encoding used on desktop browsers and not on the iPhone? or mobile Safari?
Are there different ways to encode the URL in iOS other than using
-stringByAddingPercentEscapesUsingEncoding
-CFURLCreateStringByAddingPercentEscapes
which generates bad request content pages from server.
Any help would be really great, Thanks.
EDIT:
The URL been generated is as below http://something.test.com/iostest/index.html?{"a":"b"}
Managed to figure that not encoding the curly brackets is causing the issue in iOS.
as in
NSString *tempUrlSting = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)tempURLA,CFSTR("{}"), CFSTR("\""), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding)));
NSURL *tempUrl=[NSURL URLWithString:tempUrlSting];
If not encoding the braces in the URL but encoding the rest using [Rob's answer][1] as above. When creating the NSURL, the url is empty.
If encoding the braces the URL gets generated fine, but the server throws an exception.
This Question suggests to use CFNetworking.
EDIT
Used CFNetworking as below
-(void)getDataFromUrl{
CFStringRef tempURLA = CFSTR("http://my.test.server/iostest/index.html?{\"a\":\"b\"}");
CFStringRef tempUrlSting = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)tempURLA,CFSTR("{}"), CFSTR("\""), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
CFURLRef myURL = CFURLCreateWithString(kCFAllocatorDefault, tempUrlSting, NULL);
CFStringRef requestMethod = CFSTR("GET");
CFHTTPMessageRef myRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, requestMethod, myURL,kCFHTTPVersion1_1);
CFStringRef headerFieldName = CFSTR("Accept");
CFStringRef headerFieldValue = CFSTR("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
CFHTTPMessageSetHeaderFieldValue(myRequest, headerFieldName, headerFieldValue);
[self performHTTPRequest:myRequest];
}
-(void)performHTTPRequest:(CFHTTPMessageRef)request {
CFURLRef gotdatab = (__bridge CFURLRef)(CFBridgingRelease(CFHTTPMessageCopyRequestURL(request)));
// NSLog(#"(CFHTTPMessageRef request %#",gotdatab);
CFReadStreamRef requestStream = CFReadStreamCreateForHTTPRequest(NULL, request);
CFReadStreamOpen(requestStream);
NSMutableData *responseBytes = [NSMutableData data];
NSError *error;
while (TRUE) {
if (CFReadStreamHasBytesAvailable(requestStream)) {
UInt8 streambuffer[1024];
int readBytes = CFReadStreamRead (requestStream,streambuffer,sizeof(streambuffer));
NSLog(#"Read: %d",readBytes);
[responseBytes appendBytes:streambuffer length:readBytes];
}
if (CFReadStreamGetStatus(requestStream) == kCFStreamStatusError) {
error = (NSError*)CFBridgingRelease(CFReadStreamCopyError (requestStream));
if ([error code] == 61) {
// connection refused
NSLog(#"Error occured: %d",[error code]);
}
break;
}
if (CFReadStreamGetStatus(requestStream) == kCFStreamStatusAtEnd) {
NSLog(#"Stream reached end!");
error = nil;
break;
}
}//
CFHTTPMessageRef response = (CFHTTPMessageRef)CFReadStreamCopyProperty(requestStream, kCFStreamPropertyHTTPResponseHeader);
if (response==NULL) {
NSLog(#"response is null");
return;
}
}
The above was done using examples from here and here
Above method still has the same issue. That is: if {} are not encoded the URL doesn't get generated. If the {} are encoded the server doesn't return a proper value.
Any suggestions pls?
Sometimes URL encoded format already except for the é-character which should probably be encoded as %c3%a9. Desktop browser is quite liberal with invalid URLs, thats why it works in Safari etc.
So if you have a NSString and you want to convert it into a proper URL encoding then use the below method of NSString class.
NSURL* url = [NSURL URLWithString:[strURL stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
You should edit your question showing us an example of your URL and your GET parameters. If you're percent escaping, for example, some reserved character in the domain name or the URL path, that suggests one solution (e.g. stringByAddingPercentEscapesUsingEncoding is fine). If you're percent escaping the broader array of reserved characters in the parameters of a GET request (notably = or +), then stringByAddingPercentEscapesUsingEncoding is simply not up to the job and you'd have to use CFURLCreateStringByAddingPercentEscapes (but only on the parameter keys and their values, not on the full URL string). I use a method like the following on the parameters as I append them to the URL:
- (NSString *)percentEscapeURLParameter:(NSString *)string
{
return CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)string,
NULL,
(CFStringRef)#":/?#!$&'()*+,;=",
kCFStringEncodingUTF8));
}
If you're saying that CFURLCreateStringByAddingPercentEscapes is not working for you, you'd have to show us how you're using it. Make sure you are doing it just on the GET parameter values, that you're supplying the necessary "legal characters to escape" parameter, that you're not escaping something that shouldn't be, etc.

Correcting user submitted URL in Xcode/Objective C

I'm trying to programme a mini browser in Xcode however at the moment the UIWebView will only load URLs that include the http ://www The user submits their URL using a UITextField and the contents become a string.
I wondered if there was a way to either search the submitted string and add the http or www or both where required or format the text input so it automatically checks to see if the correct address is used.
Thanks
Do something like this:
NSString *urlString = ... // the user entered URL string
if (![urlString hasPrefix:#"http://"]) {
urlString = [#"http://" stringByAppendingString:urlString];
}
Note that this is just a rough suggestion to get you started. This code doesn't handle cases such as the URL already having a prefix of "https://" or typos such as "htp://".
A better approach might be:
NSURL *url = [NSURL URLWithString:urlString];
NSString *scheme = [url scheme];
if (scheme.length == 0) {
// The string has no scheme - add "http://"
} else {
// check for valid schemes
}

Phone call number with hashtag on iOS

How do I make a call to this number *199*123456789# on iOS?
I used the following code but it doesn't work.
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:#"tel:*199*123456789#"]];
Reposted and modified from my answer to the now-closed question "iOS - I want to call phone number "#51234" in Xcode useing telprompt":
At least as of iOS 11, one can dial numbers with a hashtag (#) or asterisk (*).
Make calls with these characters by first encoding the phone number, then adding the tel: prefix, and finally turning the resulting string into a URL.
Swift 4, iOS 11
// 1) set up the dial sequence as a String
let dialSequence = "*199*123456789#"
// 2) "percent encode" the dial sequence with the "URL Host Allowed" character set
guard let encodedDialSequence =
dialSequence.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) else {
print("Unable to encode the dial sequence.")
return
}
// 3) add the `tel:` url scheme to the front of the encoded string
// NOTE: the '//' part is optional: either 'tel:' or 'tel://' will work.
let dialURLString = "tel:\(encodedDialSequence)"
// 4) set up the URL with the scheme+encoded number string
guard let dialURL = URL(string: dialURLString) else {
print("Couldn't convert the dial string into an URL.")
return
}
// 5) dial the URL
UIApplication.shared.open(dialURL, options: [:]) { success in
if success { print("SUCCESSFULLY OPENED DIAL URL") }
else { print("COULDN'T OPEN DIAL URL") }
}
Objective-C, iOS 11
// 1) set up the dial sequence as a String
NSString *dialSequence = #"*199*123456789#";
// 2) "percent encode" the dial sequence with the "URL Host Allowed" character set
NSCharacterSet *urlHostAllowed = [NSCharacterSet URLHostAllowedCharacterSet];
NSString *encodedDialSequence = [dialSequence stringByAddingPercentEncodingWithAllowedCharacters:urlHostAllowed];
// 3) add the 'tel:' url scheme to the front of the encoded string
// NOTE: the '//' part is optional: either 'tel:' or 'tel://' will work.
NSString *dialURLString = [NSString stringWithFormat:#"tel:%#", encodedDialSequence];
// 4) set up the URL with the scheme+encoded number string
NSURL *dialURL = [NSURL URLWithString:dialURLString];
// 5) set up an empty dictionary for the options parameter
NSDictionary *optionsDict = [[NSDictionary alloc] init];
// 6) dial the URL
[[UIApplication sharedApplication] openURL:dialURL
options:optionsDict
completionHandler:^(BOOL success) {
if (success) { NSLog(#"SUCCESSFULLY OPENED DIAL URL"); }
else { NSLog(#"COULDN'T OPEN DIAL URL"); }
}];
Replace * with %2A and # with %23:
NSURL *tel = [NSURL URLWithString:#"tel:%2A199%2A123456789%23"];
[[UIApplication sharedApplication] openURL:tel];
You need to use tel:// not just tel:

Resources