change user agent multiple times - iphone

I am trying to toggle user agent for a uiwebview between iPhone and iPad. So to have a button that will change from iPad user agent to iPhone user agent and backward.
I found this link: http://www.mphweb.com/en/blog/easily-set-user-agent-uiwebview
Unfortunately, the user agent can be changed only once, even if I recreate the uiwebview.
Does anyone has an idea about how to do it?
Btw, I also tried set the user agent in urlrequest header, without success.
Thanks

Me too, I have been able to set the UserAgent once only. Then I can't change it anymore. I tried on the simulator and on the device too. Same trouble.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSDictionary *dictionary = #{#"UserAgent" : #"MyOWnUserAgent_2"};
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
}
I don't use web views. I just make calls like:
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:urlRequest] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
I cleaned, deleted the app from the device, I rebuilt, I quit, reboot, rebuilt... The problem is still there. I run XCode 7.3 (7D175) on OS X 10.11.5 (15F34) and build against Deploymen Target iOS 9.1, Base SDK iOS 9.3.
Any clue?

try this
static void appendUA(NSString *uaStr) {
if (!uaStr)
return;
UIWebView *tempWebView = [[UIWebView alloc] initWithFrame:CGRectZero];
NSString *secretAgent = [tempWebView stringByEvaluatingJavaScriptFromString:#"navigator.userAgent"];
secretAgent = [secretAgent stringByAppendingString:uaStr];
NSDictionary<NSString *, id> *domain = [[NSUserDefaults standardUserDefaults] volatileDomainForName:NSRegistrationDomain];
if (domain) {
NSMutableDictionary<NSString *, id> *newDomain = [domain mutableCopy];
[newDomain setObject:secretAgent forKey:#"UserAgent"];
domain = newDomain;
} else {
domain = [[NSDictionary alloc]
initWithObjectsAndKeys:secretAgent, #"UserAgent", nil];
}
[[NSUserDefaults standardUserDefaults] removeVolatileDomainForName:NSRegistrationDomain];
[[NSUserDefaults standardUserDefaults] setVolatileDomain:domain forName:NSRegistrationDomain];
[[NSUserDefaults standardUserDefaults] synchronize];
}
You should call this function BEFORE create WKWebview/UIWebView, and space is NOT automatically added.
appendUA(#" ====TEST_UA====");
WKWebView *wkWebView = [WKWebView new];
//...

Related

NSUserDefaults values becoming nil

I am observing strange behaviour of NSUserDefaults. During testing on iphone 4(32-bit) it is working fine. When i send the same app to my client using iPhone 5S(64-bit), NSUserDefault values are becoming nil. Is the behaviour of NSUserDefaults is changing on 32-bit and 64-bit ios versions? I have also used [[NSUserDefaults standardUserDefaults]synchronize] after saving values in NSUserDefaults.I am observing this kind of behaviour from ios 7.1 versions.
AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//to stop updating locations in subsequent launches
if (![#"1" isEqualToString:[[NSUserDefaults standardUserDefaults]
objectForKey:#"aValue"]]) {
//Action here
NSLog(#"LOCATION IS ON");
locationManager = [[CLLocationManager alloc] init];
locationVC = [[LocationVC alloc]init];
[locationVC InitializeWith:_managedObjectContext LocationManager:locationManager];
//[locationVC InitializeWith:_managedObjectContext LocationManager:nil];
}
else {
NSLog(#"LOCATION IS OFF");
locationManager = [[CLLocationManager alloc] init];
locationVC = [[LocationVC alloc]init];
//[locationVC InitializeWith:_managedObjectContext LocationManager:locationManager];
[locationVC InitializeWith:_managedObjectContext LocationManager:nil];
}
}
LocationVC.m
LocationVC *locationVC;
-(void) InitializeWith:(NSManagedObjectContext *)context LocationManager:(CLLocationManager *)locationManager{
//to update location during first launch
if (![#"1" isEqualToString:[[NSUserDefaults standardUserDefaults]
objectForKey:#"aValue"]]) {
[[NSUserDefaults standardUserDefaults] setValue:#"1" forKey:#"aValue"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(#"LOCATION IS ON");
self->locationManager=locationManager;
self->locationManager.delegate = self;
self->locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self->locationManager.distanceFilter = kCLDistanceFilterNone;
[self->locationManager startUpdatingLocation];
_managedObjectContext=context;
}
//in subsequent launches
else{
NSLog(#"LOCATION IS OFF");
_managedObjectContext=context;
[self->locationManager stopUpdatingLocation];
}
}
In my client's iPhone 5S(64-bit), location icon is reappearing after 10 minutes eventhough i have called [self->locationManager stopUpdatingLocation]; in subsequent application lauches.
Is the behaviour of NSUserDefaults is changing on 32-bit and 64-bit ios versions?
No, NSUserDefaults (based on property lists) are designed to be platform independent. You can even copy a binary plist file from a Power PC Mac to an Intel machine, an iPhone 32 bit, or iPhone 64 bit and the file will always produce identical results.
The NSUserDefaults class is known to be very robust.
It's very likely that the error is in your code. If you need more help, please provide more information about how you detect and reproduce the error.
Edit: It seems that you used the wrong method to set #"aValue":
[[NSUserDefaults standardUserDefaults] setValue:#"1" forKey:#"aValue"];
The correct method to set preferences is -setObject:forKey:.
setValue:fortKey: is part of KVC and is not documented to do something specific in NSUserDefaults. While it seems that in current implementations (iOS 7.1) NSUserDefaults overrides setValue:forKey: that's an undocumented feature not guaranteed to work as expected.

Get device token to push notify the second time on iPhone

I need to obtain the device token on my iPhone to test the push notify.
On my iPhone I had already agreed to notify push permissions. I try to remove and reinstall the app but nothing. I try to put a breackpoint in the didRegisterForRemoteNotificationsWithDeviceToken method but nothing.
Any suggestion?
This is my code:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
/**** PUSH NOTIFY ****/
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeBadge];
self.window.rootViewController = self.tabBarController;
[self.window makeKeyAndVisible];
return YES;
}
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSMutableString *str = [[NSMutableString alloc] initWithFormat:#"http://www.mysite.com/storeToken.php?task=register&token=%#", [self stringWithDeviceToken:deviceToken]];
//NSLog(#"%#",str);
NSUserDefaults *pref = [NSUserDefaults standardUserDefaults];
[pref setObject:[self stringWithDeviceToken:deviceToken] forKey:#"token"];
[pref synchronize];
NSURL *url = [NSURL URLWithString:str];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request startSynchronous];
[str release];
}
- (NSString*)stringWithDeviceToken:(NSData*)deviceToken {
const char* data = [deviceToken bytes];
NSMutableString* token = [NSMutableString string];
for (int i = 0; i < [deviceToken length]; i++) {
[token appendFormat:#"%02.2hhX", data[i]];
}
return [[token copy] autorelease];
}
This is the error that it print:
Error: Error Domain=NSCocoaErrorDomain Code=3000 "nessuna stringa di autorizzazione 'aps-environment' valida trovata per l'applicazione" UserInfo=0x296e80 {NSLocalizedDescription=nessuna stringa di autorizzazione 'aps-environment' valida trovata per l'applicazione}
It is good to have another delegate method for error handling:
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(#"Fail to register for remote notifications: %#", [error localizedDescription]);
}
After question update it's more clear that problem is in wrong provisioning profile (generic or without 'aps-evironment'). So:
Remove all expired profiles and all profiles for that app from both XCode and device
Check push notifications are enabled for your app (in provisioning portal)
Download provisioning profile from portal, install it to XCode
Check that selected profile (in build settings / codesigning identity) matches the app, and is not the generic/wildcard one (sometimes autoselection goes wrong)
As usual (XCode caching "magic"), it's better to restart XCode and remove the application from device before build
Build & Pray

facebook dialog failing silently when not called immediately after authorize

I have the following function to post to Facebook using the latest iOS Facebook SDK.
-(void)fbPost:(NSMutableDictionary *) params{
NSLog(#"fbPost called");
if (![facebook isSessionValid]) {
NSLog(#"session invalid, calling fblogin");
[self fblogin];
}
if ([facebook isSessionValid]) {
NSLog(#"session valid, calling publishToFB");
[self.facebook dialog:#"stream.publish" andParams:params andDelegate:self];
}
}
It works fine when there is no existing session: it logs in to facebook, gets permissions, returns to the app, shows the dialog and publishes the status. However, when trying a second time, isSessionValid returns true the first time and nothing happens, although the log shows publishToFB is called.
The session is persisted in fbDidLogin:
[[NSUserDefaults standardUserDefaults] setObject:self.facebook.accessToken forKey:#"AccessToken"];
[[NSUserDefaults standardUserDefaults] setObject:self.facebook.expirationDate forKey:#"ExpirationDate"];
[[NSUserDefaults standardUserDefaults] synchronize];
and loaded in application didFinishLaunchingWithOptions:
facebook.accessToken = [[NSUserDefaults standardUserDefaults] stringForKey:#"AccessToken"];
facebook.expirationDate = (NSDate *) [[NSUserDefaults standardUserDefaults] objectForKey:#"ExpirationDate"];
I made sure to ask for offline_access permission when logging in:
_permissions = [[NSArray arrayWithObjects:
#"publish_stream",#"offline_access",nil] retain];
It appears the problem was in drawing the dialog in this code in FBDialog.m
UIWindow* window = [UIApplication sharedApplication].keyWindow;
if (!window) {
window = [[UIApplication sharedApplication].windows objectAtIndex:0];
}
If I comment out the If clause, it works OK. I guess that in my app setup, "keyWindow" is not front-most, so the dialog was not showing up.

how to tell whether Facebook is still loggin or not?

After
_facebook = [[Facebook alloc] init];
and
[_facebook authorize:kAppId permissions:_permissions delegate:self];
How can I tell whether the _facebook is (still) logged-in/valid to do further [_facebook requestWithMethodName: ...]?
Or should I just simply [_facebook authorize:...] again and again? Thanks!
I was having the same issue which i solved with the solution of another Member from here, dont know link exactly. but here's the solution
When you are logged into the facebook
[[NSUserDefaults standardUserDefaults] setObject:self.facebook.accessToken forKey:#"AccessToken"];
[[NSUserDefaults standardUserDefaults] setObject:self.facebook.expirationDate forKey:#"ExpirationDate"];
In next View Controller, where you want to use the facebook with same session
_facebook.accessToken = [[NSUserDefaults standardUserDefaults] stringForKey:#"AccessToken"];
_facebook.expirationDate = (NSDate *) [[NSUserDefaults standardUserDefaults] objectForKey:#"ExpirationDate"];
if ([_facebook isSessionValid] == NO) {
//[_facebook authorize:kAppId permissions:self.permissions delegate:self]; //Create new facebook instance
}
Let me know if i put something which does not work for you.
Thanks

NSUserDefaults not present on first run on simulator

I've got some settings saved in my Settings.bundle, and I try to use them in application:didFinishLaunchingWithOptions, but on a first run on the simulator accessing objects by key always returns nil (or 0 in the case of ints). Once I go to the settings screen and then exit, they work fine for every run thereafter.
What's going on? Isn't the point of using default values in the Settings.bundle to be able to use them without requiring the user to enter them first?
If I got your question right, in your app delegate's - (void)applicationDidFinishLaunching:(UIApplication *)application, set the default values for your settings by calling
registerDefaults:dictionaryWithYourDefaultValues
on [NSUserDefaults standardUserDefaults]
- (void)applicationDidFinishLaunching:(UIApplication *)application {
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:3], #"SomeSettingKey",
#"Some string value", #"SomeOtherSettingKey",
nil];
[ud registerDefaults:dict];
}
These values will only by used if those settings haven't been set or changed by previous executions of your application.
As coneybeare said "You should detect if it is the first load, then store all your defaults initially."
On applicationDidFinishLaunching try to set default value in your preference.
Here is the sample:
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
if([defaults objectForKey:#"YOUR_KEY"] == nil)
{
[defaults setValue:#"KEY_VALUE" forKey:#"YOUR_KEY"];
}
When application will run second time it will come with KEY_VALUE for YOUR_KEY.
Thanks,
Jim.
Isn't the point of using default
values in the Settings.bundle to be
able to use them without requiring the
user to enter them first?
No. The point of the settings bundle is to give the user a place to edit all 3rd Party app settings in a convenient place. Whether or not this centralization is really a good idea is a User Experience issue that is off topic.
To answer your question, you should detect if it is the first load, then store all your defaults initially.
And while we are on the subject, I would also check out In App Settings Kit as it provides your app with a simple way to display your app settings in both places (in-app and Settings.app) with minimal code.
The values in the Settings.bundle are intended for the Settings app to able to fill in default values for your app. They are not used by your own app.
But you can set defaults yourself with the registerDefaults: method of NSUserDefaults. This will not actually set them on disk but just give "defaults for the defaults": they are used when no value has been set by the user yet.
Setting registerDefaults: must be done before any use of the default values. The "applicationDidFinishLaunching:" method that others suggested for this, is too late in most cases. By the time "applicationDidFinishLaunching:" is called, your views have already been loaded from the nib files, and their "viewDidLoad:" methods have been called. And they may typically read user defaults.
To guarantee that the defaults are set before first use, I use the following utility class, which loads the values from the Root.plist file and sets them with "registerDefaults:". You use this class to read user defaults instead of "[NSUserDefaults standardUserDefaults]". Use "[Settings get]" instead.
As a bonus, it also contains a registration method for user default change notifications, because I always forget how that is done.
#import "Settings.h"
#implementation Settings
static bool initialized = NO;
+ (void) setDefaults
{
NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
NSString *settingsBundlePath = [bundlePath stringByAppendingPathComponent:#"Settings.bundle"];
NSBundle *settingsBundle = [NSBundle bundleWithPath:settingsBundlePath];
NSString *settingsPath = [settingsBundle pathForResource:#"Root" ofType:#"plist"];
NSDictionary *settingsDict = [NSDictionary dictionaryWithContentsOfFile:settingsPath];
NSArray *prefSpecifierArray = [settingsDict objectForKey:#"PreferenceSpecifiers"];
NSMutableDictionary *appDefaults = [[NSMutableDictionary alloc] init];
for (NSDictionary *prefItem in prefSpecifierArray)
{
NSString *key = [prefItem objectForKey:#"Key"];
if (key != nil) {
id defaultValue = [prefItem objectForKey:#"DefaultValue"];
[appDefaults setObject:defaultValue forKey:key];
}
}
// set them in the standard user defaults
[[NSUserDefaults standardUserDefaults] registerDefaults:appDefaults];
if (![[NSUserDefaults standardUserDefaults] synchronize]) {
NSLog(#"Settings setDefaults: Unsuccessful in writing the default settings");
}
}
+ (NSUserDefaults *)get
{
if (!initialized) {
[Settings setDefaults];
initialized = YES;
}
return [NSUserDefaults standardUserDefaults];
}
+ (void) registerForChange:(id)observer selector:(SEL)method
{
[[NSNotificationCenter defaultCenter] addObserver:observer selector:method name:NSUserDefaultsDidChangeNotification object:nil];
}
+ (void) unregisterForChange:(id)observer
{
[[NSNotificationCenter defaultCenter] removeObserver:observer name:NSUserDefaultsDidChangeNotification object:nil];
}