iOS web view with urlstartswith - ios

if there is someone who can help me to create a simple iOS app , i need just the code
The app needs a WebView wich will load the following url http://www.applicationurl.com/?param=(udid)
The param udid needs to be static so it will never change
The app will have 1 Back button for the webview and 3 simple ifUrlStartsWith if's
if the link in webview is Click to Call it will call that phonenumber
if the link in webview is Apple Map's it will open the Apple maps to a static adress , the adress could be stored in NSSTRING mapadress=#"Romania Street Haleluia nr.2";
if the link in webview is Exit App it will automatically close the app
Can any one help me please ? i always get stuck at urlstartswith and the current url is not showing up.
The code i'm using
//
// ViewController.m
// Aqua Park President
//
// Created by Alex Bonta on 7/13/14.
// Copyright (c) 2014 Aqua President. All rights reserved.
//
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize webView;
- (void)viewDidLoad
{
// GET THE PHONE UDID
NSString *udid=[[[UIDevice currentDevice] identifierForVendor] UUIDString];
udid=[udid substringToIndex:5];
// Loading the url adress with the param of the uinique id
NSString *string = [NSString stringWithFormat:#"http://app.aquapark-felix.ro/?email=%#",udid];
NSURL *url = [NSURL URLWithString:string];
[webView loadRequest:[NSURLRequest requestWithURL:url]];
NSString *currentURL = webView.request.URL.absoluteString;
- (BOOL) webView;(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
//Catching URLs and telling the app what to do
if ([[[request URL] scheme] isEqualToString:#"tel"]) {
NSLog((#"ASA"));
}
}
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end

I have cleaned up your code as well as answering it. Please see the comments in the code for an explanation of the code and also please see the Apple URL Schemes Documentation. The Below code has been tested and works when you pass in a correct URL scheme such as
HTML for making phone call
1-408-555-5555
Natiave for making phone call
tel:1-408-555-5555
HTML for accessing maps app
Directions
Native for accessing maps app
http://maps.apple.com/?daddr=San+Francisco,+CA&saddr=cupertino
If you haven't configured these properly it will not work. As you are coming from a website you will need the HTML versions.
//
// ViewController.m
// Aqua Park President
//
// Created by Alex Bonta on 7/13/14.
// Copyright (c) 2014 Aqua President. All rights reserved.
//
#import "ViewController.h"
#implementation ViewController
// This can be removed as it is done automcatically for you.
//#synthesize webView;
- (void)viewDidLoad
{
// A call to the super must come first.
[super viewDidLoad];
// Construct a url request with the UUID string and pass it to the _webView
[_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://app.aquapark-felix.ro/?email=%#",[[[[UIDevice currentDevice] identifierForVendor] UUIDString] substringToIndex:5]]]]];
}
- (BOOL) webView;(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
// Check whether the URL scheme is of "tel"
// "loc" will not open the apple maps app this code is done so it will.
if([request.URL.scheme isEqualToString:#"tel"] || [request.URL.absoluteString hasPrefix:#"http://maps.apple.com/?q"]) {
// We need to make sure we can actually open the urls that have been passed in.
// We do this for two reason 1) if we couldn't it would be a bad user experience
// and 2) you can't make calls on a iPod.
if([[UIApplication sharedApplication] canOpenURL:request.URL]) {
// Yes we can make a phone call so lets make it.
// Based on your number being formatted correctly if it's not then it will not work.
[[UIApplication sharedApplication] openURL:request.URL];
}
// If all else fails and we can't open the url just return no.
// I would recommend a UIAlertView here to tell the user.
return NO;
}
// As for exiting the app don't do this at all.
// Every other URL just return YES and continue with the Request.
return YES;
}
#end

If you're trying to get the URL Scheme (http, loc, tel etc)
- (BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
//Catching URLs and telling the app what to do
if ([[[request URL] scheme] isEqualToString:#"tel"]) {
// Code
return NO;
}
return YES;
}
And so on for your other schemes.
This needs to go outside of viewDidload. See below.
// ViewController.m
// Aqua Park President
//
// Created by Alex Bonta on 7/13/14.
// Copyright (c) 2014 Aqua President. All rights reserved.
//
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize webView;
- (void)viewDidLoad
{
// GET THE PHONE UDID
NSString *udid=[[[UIDevice currentDevice] identifierForVendor] UUIDString];
udid=[udid substringToIndex:5];
// Loading the url adress with the param of the uinique id
NSString *string = [NSString stringWithFormat:#"http://app.aquapark-felix.ro/?email=%#",udid];
NSURL *url = [NSURL URLWithString:string];
[webView loadRequest:[NSURLRequest requestWithURL:url]];
NSString *currentURL = webView.request.URL.absoluteString;
[super viewDidLoad];
}
- (BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
//Catching URLs and telling the app what to do
if ([[[request URL] scheme] isEqualToString:#"tel"]) {
NSLog((#"ASA"));
return NO;
}
return YES;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end

Related

iOS :: Web site does not work in iOS Safari and UIWebView

I have an app with UIWebView, which loads a web site https://app.bridallive.com/. Previously it was working well in iPad, but now it does not.
It loads neither in UIWebView (in a simplest possible app) and in iOS Safari. Works well in Mac OS.
I tried to diagnose it with:
-(void) loadWebSite {
NSURL * url = [NSURL URLWithString:#"https://app.bridallive.com/#/dashboard?iPadApp=true"];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest: request];
}
- (void)viewDidLoad {
[super viewDidLoad];
[self loadWebSite];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
NSLog(#"Error : %#",error);
}
NSAppTransportSecurity is set to YES and the web site has valid and trusted certificate.
this is what I used in futher experiments:
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self loadWebSite];
}
but this does not give any errors.
Can anyone suggest a way to diagnose this in iOS?
Best regards,
Andrey
UIWebview has a protocol, UIWebViewDelegate, it helps you to observe changes in your
It implements a few method using what you can observe the changes in your UIWebview loading lifecyclye:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSLog(#"shouldStart");
return true;
}
- (void)webViewDidStartLoad:(UIWebView *)webView {
NSLog(#"webViewDidStartLoad");
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSLog(#"webViewDidFinishLoad");
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
NSLog(#"%#", error);
NSLog(#"didFailLoadWithError");
}
In order to receive the callback on this functions, sign up for the delegate on your classes interface in .h for example.
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController <UIWebViewDelegate>
#end
I have set up a sample project, and upon opening the URL, i receive the following error in the didFailLoadWithError callback:
Error Domain=WebKitErrorDomain Code=101 "(null)"
It seems you are not encoding you request properly. You should encode the string the following way:
NSString *encodedString=[[NSString stringWithFormat:#"https://app.bridallive.com/#/dashboard?iPadA‌​pp=true"] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
NSURL *weburl = [NSURL URLWithString:encodedString];

How to load URL in Uiwebview with GameCenter data as parameters?

I have a browser webgame ported to iOS using UIWebView (storyboard, not xib). The app is already published and works relatively well. My challenge now is to implement GameCenter properly so I can get the local player's playerID and then have a trustable unique id of the user. That's the only feature I really need from GameCenter.
The GameCenter functionality is actually implemented and working well, but for a reason I still couldn't understand I can't make the setAuthenticateHandler, located in a different class file, to access the UIebView so I can load an URL passing the playerId (among other parameters) via POST.
The WebViewController.m has a method who loads an URL in the UIWebView. The setAuthenticateHandler do call this method, but the UIWebView is null and of course it's not possible to load the URL. If I call the method inside WebViewController.m the URL is loaded correctly.
I was using ARC and then changed to MRC according to https://stackoverflow.com/a/14613361/3063226, but the behavior didn't change, the UIWebView is still null when GameCenter setAuthenticateHandler calls the Load_URL method.
Any help is very welcome. I have tried and researched a LOT for days before coming here to ask a question, I'm stuck!
GCHelper.m
- (void)authenticateLocalUser {
if (!gameCenterAvailable) return;
NSLog(#"Authenticating local user...");
if (![GKLocalPlayer localPlayer].isAuthenticated) {
[[GKLocalPlayer localPlayer] setAuthenticateHandler:(^(UIViewController* viewcontroller, NSError *error) {
if (!error && [GKLocalPlayer localPlayer].playerID != nil)
{
NSLog(#"Player logged in GameCenter!");
NSLog([NSString stringWithFormat: #"1111 (GCHelper) playerID: [%#]", [GKLocalPlayer localPlayer].playerID);
// --
WebViewController *yourClassInstance = [[WebViewController alloc] init];
[yourClassInstance Load_URL:true]; // this is not working as expected!!
// -
}
else
{
NSLog(error.localizedDescription);
}
})];
} else {
NSLog(#"Already authenticated!");
}
}
WebViewController.h
#import <UIKit/UIKit.h>
#interface WebViewController : UIViewController <UIWebViewDelegate>
-(void) Load_URL:(BOOL)Nativa;
#property (strong, nonatomic) IBOutlet UIWebView *PagPrincipal;
#end
WebViewController.m
#import "WebViewController.h"
#import "NSData+AESCrypt.h"
#import "NSString+AESCrypt.h"
#import "NSString+URL_Encode.h"
#import "GCHelper.h"
#interface WebViewController ()
-(void) Load_URL:(BOOL)Nativa;
#end
-(void) Load_URL :(BOOL)Nativa
{
NSURL *url = [NSURL URLWithString: #"http://www.webgameurl.com"];
NSString *body = [NSString stringWithFormat: #"iac=%#", [self URL_Codigo :Nativa :vip_aux]];
NSMutableURLRequest *requestObj = [[NSMutableURLRequest alloc]initWithURL: url];
[requestObj setHTTPMethod: #"POST"];
[requestObj setHTTPBody: [body dataUsingEncoding: NSUTF8StringEncoding]];
// HERE!! This returns null when called from GCHelper.m, but is ok when called from WebViewController.m !!
NSLog([NSString stringWithFormat:#"Webview >>> >>> >>> [%#]", _PagPrincipal.description]);
_PagPrincipal.delegate = self;
[_PagPrincipal loadRequest:requestObj];
This is it. The _PagPrincipal is the UIWebView itself, it's a storyboard. I'm not an iOS Objective-C specialist, so for sure there are things I just don't master. Using Xcode 6.1.1, the app is designed for iOS8+. Testing in a real iPad Mini 1 (non-retina) and iPhone 5.

How to send an iOS photo on TV with Chromecast?

I have been playing a bit with the Chromecast SDK those days. What I am currently trying to do is to send a UIImage (for example a photo taken with the iPhone) on the TV using the Chromecast.
I am able to load "external" image using an URL but I can't figure out how to send a locally stored image!
So is there a way to send it using base64 encoding, or to set up a stream, or even to mirror the screen ? I am a bit lost, if someone could give me a hint or some sample code, that'll be great !
You can host a small web server in your app and then provide the URL to that server to the Chromecast receiver app to load the photos from your device. The Cast protocol channel is not designed to handle large binary transfers.
Building up on responses provided by Leon and Alok, i.e. serving images from your iOS device over HTTP using Cocoa HTTP server, you can find an example on at GitHub with detailed explanation in this blog post.
Also don't forget that to be served to your ChromeCast, you will need to enable CORS.
In short, and once you have added Cocoa HTTP Server to your project, you can
subclass HTTPDataResponse as follows in order to enable CORS
CamCaptureDataResponse.h
#import "HTTPDataResponse.h"
#interface CamCaptureDataResponse : HTTPDataResponse
#end
CamCaptureDataResponse.m
#import "CamCaptureDataResponse.h"
#implementation CamCaptureDataResponse
-(NSDictionary*)httpHeaders {
return #{
#"Access-Control-Allow-Origin":#"*",
#"Access-Control-Allow-Methods":#"GET,PUT,POST,DELETE",
#"Access-Control-Allow-Headers":#"Content-Type"
};
}
#end
Use this new DataResponse class in your own request handler by subclassing HTTPConnection
CamCaptureConnection.h
#import "HTTPConnection.h"
#interface CamCaptureConnection : HTTPConnection
#end
CamCaptureConnection.m
#import "CamCaptureConnection.h"
#import "CamCaptureHTTPServer.h"
#import "CamCaptureDataResponse.h"
#implementation CamCaptureConnection
-(NSObject<HTTPResponse> *)httpResponseForMethod:(NSString *)method URI: (NSString *)path {
NSArray* pathComponents = [path componentsSeparatedByString:#"/"];
if ([pathComponents count] < 2) {
return [[CamCaptureDataResponse alloc] initWithData:[#"ERROR" dataUsingEncoding:NSUTF8StringEncoding]];
}
NSString *command = [pathComponents objectAtIndex:1];
if ([command isEqualToString:#"PING"]) {
return [[CamCaptureDataResponse alloc] initWithData:[#"PONG" dataUsingEncoding:NSUTF8StringEncoding]];
}
if ([command isEqualToString:#"PIC"]) {
// Change the following line with whichever image you want to serve to your ChromeCast!
NSData *imageData = UIImageJPEGRepresentation([CamCaptureHttpServer instance].captureImage, 0.3);
if (imageData) {
return [[CamCaptureDataResponse alloc] initWithData:imageData];
} else {
return [[CamCaptureDataResponse alloc] initWithData:[#"NO_IMAGE" dataUsingEncoding:NSUTF8StringEncoding]];
}
}
return [[CamCaptureDataResponse alloc] initWithData:[#"ERROR_UNKNOWN_COMMAND" dataUsingEncoding:NSUTF8StringEncoding]];
}
#end
Then before you start, your web server, first register your new connection class as follows
NSError *error;
httpServer = [[CamCaptureHttpServer alloc] init];
[httpServer setConnectionClass:[CamCaptureConnection class]];
[httpServer setType:#"_http._tcp."];
[httpServer setPort:1234];
[httpServer start:&error];
Yes ! you can use CocoaHTTPServer is a small, lightweight, embeddable HTTP server for Mac OS X or iOS applications.
#import "iPhoneHTTPServerAppDelegate.h"
#import "iPhoneHTTPServerViewController.h"
#import "HTTPServer.h"
#import "DDLog.h"
#import "DDTTYLogger.h"
// Log levels: off, error, warn, info, verbose
static const int ddLogLevel = LOG_LEVEL_VERBOSE;
#implementation iPhoneHTTPServerAppDelegate
#synthesize window;
#synthesize viewController;
- (void)startServer
{
// Start the server (and check for problems)
NSError *error;
if([httpServer start:&error])
{
DDLogInfo(#"Started HTTP Server on port %hu", [httpServer listeningPort]);
}
else
{
DDLogError(#"Error starting HTTP Server: %#", error);
}
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Configure our logging framework.
// To keep things simple and fast, we're just going to log to the Xcode console.
[DDLog addLogger:[DDTTYLogger sharedInstance]];
// Create server using our custom MyHTTPServer class
httpServer = [[HTTPServer alloc] init];
// Tell the server to broadcast its presence via Bonjour.
// This allows browsers such as Safari to automatically discover our service.
[httpServer setType:#"_http._tcp."];
// Normally there's no need to run our server on any specific port.
// Technologies like Bonjour allow clients to dynamically discover the server's port at runtime.
// However, for easy testing you may want force a certain port so you can just hit the refresh button.
// [httpServer setPort:12345];
// Serve files from our embedded Web folder
NSString *webPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"Web"];
DDLogInfo(#"Setting document root: %#", webPath);
[httpServer setDocumentRoot:webPath];
[self startServer];
// Add the view controller's view to the window and display.
[window addSubview:viewController.view];
[window makeKeyAndVisible];
return YES;
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
[self startServer];
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
// There is no public(allowed in AppStore) method for iOS to run continiously in the background for our purposes (serving HTTP).
// So, we stop the server when the app is paused (if a users exits from the app or locks a device) and
// restart the server when the app is resumed (based on this document: http://developer.apple.com/library/ios/#technotes/tn2277/_index.html )
[httpServer stop];
}
#end

Delegate to know when phone call ends which was initiated by app

I have a code which places a phone call using below code :
// Make a call to given phone number
- (void)callPhoneNumber:(NSString *)phoneNumber
{
if (!self.webview)
self.webview = [[UIWebView alloc] init];
self.webview.delegate = self;
// Remove non-digits from phone number
phoneNumber = [[phoneNumber componentsSeparatedByCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]] componentsJoinedByString:#""];
// Make a call
NSURL * url = [NSURL URLWithString:[NSString stringWithFormat:#"tel:%#", phoneNumber]];
[self.webview loadRequest:[NSURLRequest requestWithURL:url]];
[self.view addSubview:self.webview];
}
This makes a call. What I want is, I want to know when user ends a call. I have to perform an operation when user ends a call. Is there any way for it?
What I tried is, I set delegate of webview to current controller. But none of the delegate methods is called.
- (void)webViewDidStartLoad:(UIWebView *)webView
{
DLog(#"Start Loading");
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
DLog(#"Finish Loading");
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
DLog(#"Did fail with error : %#", error);
}
I don't know if you need this info but I use webview so that when phone call is made, flow remains within the app and on call end, app screen is displayed rather than user manually coming to app from native contact app.
CoreTelephony framework has a CTCallCenter Class with callEventHandler property.
#property (nonatomic, copy) void (^callEventHandler)(CTCall*);
You will have to define a handler block in your application and assign it to this property.
If your application is active when a call event takes place, the system dispatches the event to your handler immediately when call state changes. Refer apple documents found here.
I used below code to get notified of call events.
// Create CTCallCenter object
callCenter = [[CTCallCenter alloc] init];
// Assign event handler. This will be called on each call event
self.callCenter.callEventHandler = ^(CTCall* call) {
// If call ended
if (call.callState == CTCallStateDisconnected)
{
NSLog(#"Call ended.");
}
};
For other call states check out Call States. For more info on CTCallCenter look at Apple doc for CTCallCenter.
You should be implementing this delegate method of UIWebView
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
on end call operation your webview will notify this delegate method about your action perform and you can handle it in there for example
-(BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
if (navigationType == UIWebViewNavigationTypeLinkClicked )
{
NSURL *url = [request URL];
NSLog(#"URL ===== %#",url);
// you can check your end call operation URL and handle it accordingly
if ([[url absoluteString] rangeOfString:#"#"].location == NSNotFound)
{
[[UIApplication sharedApplication] openURL:[request URL]];
return NO;
}
//return NO;
}
return YES;
}

External google search link open in browser

I want to open the google search link like 'https://www.google.co.in/#q=adam+scott' in sencha touch hybrid ios app. I tried to use var ref = window.open(url, '_blank','location=yes'); but it is not loading the page and if I change the _blank to _system it is loading the page but not showing done button to move to previous page.
Please let me know if some body has done it.
I think this is what you are looking for:
navigator.app.loadUrl('https://www.google.co.in/#q=adam+scott', { openExternal:true } );
open your MainViewController.m class and add this line of code before #end
- (BOOL) webView:(UIWebView*)theWebView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{
NSURL *url = [request URL];
// Intercept the external http requests and forward to Safari.app
// Otherwise forward to the PhoneGap WebView
if ([[url scheme] isEqualToString:#"http"] || [[url scheme] isEqualToString:#"https"]){
[[UIApplication sharedApplication] openURL:url];
return NO;
}
else {
return [super webView:theWebView shouldStartLoadWithRequest:request navigationType:navigationType];
}
}

Resources