Registering for notification causes error on mac - objective-c

I am doing something like this:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// Insert code here to initialize your application
NSApplication *application = [aNotification object];
NSRemoteNotificationType myTypes = NSRemoteNotificationTypeBadge;
[application registerForRemoteNotificationTypes:myTypes];
}
//Successful
-(void)application:(NSApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
NSLog(#"device token: %#", deviceToken);
}
//Failure to register
-(void)application:(NSApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
NSLog(#"ERROR: %#\nError object: %#", [error localizedDescription], error);
}
And I am getting the following error:
2014-06-14 20:47:13.656 RajamManagerStation[1878:303] ERROR: The operation couldn’t be completed. (OSStatus error 1.)
Error object: Error Domain=NSOSStatusErrorDomain Code=1 "The operation couldn’t be completed. (OSStatus error 1.)" (kCFHostErrorHostNotFound / kCFStreamErrorSOCKSSubDomainVersionCode / kCFStreamErrorSOCKS5BadResponseAddr / kCFStreamErrorDomainPOSIX / evtNotEnb / siInitSDTblErr / kUSBPending / dsBusError / kStatusIsError / kOTSerialSwOverRunErr / cdevResErr / EPERM: / Error code is the version of SOCKS which the server wishes to use / / POSIX errno; interpret using <sys/errno.h> / event not enabled at PostEvent / slot int dispatch table could not be initialized. / / bus error / / / Couldn't get a needed resource; alert / Operation not permitted)
I dont understand what I can do to fix it.
I was watching the WWDC apple video in 2011 relating to push notifications, and there was a slide in there that showed:
It tells me that if the error delegate callback is called that I should check my privisioning profile for entitlements.
I have done everything I possiby could to get things working but I am receiving this error still. What can I do to fix it?
UPDATE 1 - Just to affirm that I have enabled push notification services in the enabled services list.
UPDATE 2 - Affirming that push notifications is there on the provisioning profile

Switch on the Push Notifications capability for your target. In XCode, go to Target -> Capabilities, and ensure "Push Notifications" is set to ON:
(Thanks to #mateusmaso's comment for this solution!)

Related

presentMediaPlayerControllerWithURL dismissing immediately without playing the audio

I'm creating a watch application which records an audio and play that audio. The recorded audio is saved in the Apps Groups and I used the following code for playing the audio.
- (void)playAudio
{
// Playing the audio from the url using the default controller
[self presentMediaPlayerControllerWithURL:self.audioFileURL options:#{WKMediaPlayerControllerOptionsAutoplayKey : #YES} completion:^(BOOL didPlayToEnd, NSTimeInterval endTime, NSError * _Nullable error) {
NSLog(#"Error = %#",error);
}];
}
Unfortunately I am getting the following error and the player controller get dismissed immediately.
Error Domain=com.apple.watchkit.errors Code=4 "The operation could not be completed" UserInfo={NSLocalizedFailureReason=An unknown error occurred (1), NSUnderlyingError=0x16daa810 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}, NSLocalizedDescription=The operation could not be completed}.
Then I downloaded a sample project (WatchKitAudioRecorder Sample code) from Apple WatchOS Developer library but they are also having the same issue. I don't know why this is not working even in Apple Sample code :(
Finally I found that the data is not writing to the url path. Also should be written in the following path: Library/Caches/filename.extension
Here is a sample code, which may help someone.
- (void)writeAudioToAppGroupsWithData:(NSData *)audioData
{
// Writing the audio data to the App Groups
NSURL *containerURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:APP_GROUP_IDENTIFIER];
containerURL = [containerURL URLByAppendingPathComponent:[NSString stringWithFormat:DIRECTORY_PATH]];
[audioData writeToURL:containerURL atomically:YES];
}
In this case make sure that your DIRECTORY_PATH is Library/Caches/filename.extension. Eg: Library/Caches/Audio.mp3

iOS Push Notifications sent but not received

I am completely new to the Objective-C language. All I need to implement is the Push Notifications bit on my app for now. I have written the Client side on XCode 6 and the server side in Java using the javapns library. Now, while the server manages to send the notification (I get the confirmation message), I receive nothing on my device, be it the app is active or running in background.
Can somebody please direct me in the right direction? Thank you!
#import "AppDelegate.h"
#interface AppDelegate ()
#end
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert |UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
return YES;
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)newDeviceToken{
//Store the Device Token
NSLog(#"%#", newDeviceToken);
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
NSLog(#"Failed to register with error: %#", error);
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
NSLog(#"Push received: %#", userInfo);
}
Server side:
public class PushServer {
public static void main(String[] args) {
try {
BasicConfigurator.configure();
Push.alert("Message!", "***.p12", "***", false,
"92ab*************91af4");
} catch (CommunicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (KeystoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This is the output I receive when I try to send the notification:
0 [main] DEBUG javapns.notification.Payload - Adding alert [Message!]
210 [main] DEBUG javapns.communication.ConnectionToAppleServer - Creating SSLSocketFactory
229 [main] DEBUG javapns.communication.ConnectionToAppleServer - Creating SSLSocket to gateway.sandbox.push.apple.com:2195
1077 [main] DEBUG javapns.notification.PushNotificationManager - Initialized Connection to Host: [gateway.sandbox.push.apple.com] Port: [2195]: 735b478[SSL_NULL_WITH_NULL_NULL: Socket[addr=gateway.sandbox.push.apple.com/17.172.232.46,port=2195,localport=53762]]
1079 [main] DEBUG javapns.notification.PushNotificationManager - Building Raw message from deviceToken and payload
1080 [main] DEBUG javapns.notification.PushNotificationManager - Built raw message ID 1 of total length 73
1080 [main] DEBUG javapns.notification.PushNotificationManager - Attempting to send notification: {"aps":{"alert":"Message!"}}
1080 [main] DEBUG javapns.notification.PushNotificationManager - to device: 92a**********1af4
2327 [main] DEBUG javapns.notification.PushNotificationManager - Flushing
2327 [main] DEBUG javapns.notification.PushNotificationManager - At this point, the entire 73-bytes message has been streamed out successfully through the SSL connection
2327 [main] DEBUG javapns.notification.PushNotificationManager - Notification sent on first attempt
2327 [main] DEBUG javapns.notification.PushNotificationManager - Reading responses
2749 [main] DEBUG javapns.notification.PushNotificationManager - Found 0 notifications that must be re-sent
2749 [main] DEBUG javapns.notification.PushNotificationManager - No notifications remaining to be resent
2749 [main] DEBUG javapns.notification.PushNotificationManager - Closing connection
Any help is appreciated.
By chance would you happen to be building with Xcode 7 and targeting iOS 9?
If so, you are likely running into the new security default setting which requires accessing URLs securely, as described here:
Disabling ATS for an in-app browser in iOS 9?
Also, you seem to be mixing old methods with new.
registerUserNotificationSettings is an iOS 8 method that replaced registerForRemoteNotificationTypes.
So, only using the former, it looks like you're only targeting iOS 8 and later.
But then you use didReceiveRemoteNotification:, which is the old version of the method, corresponding to registerForRemoteNotificationTypes. But since you're going with the newer versions, you should be using
didReceiveRemoteNotification:fetchCompletionHandler.
You need to convert NSData to string and get actual device token by implementing following changes in your method.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSString *myToken = [[[[deviceToken description] stringByReplacingOccurrencesOfString: #"<" withString: #""]
stringByReplacingOccurrencesOfString: #">" withString: #""]
stringByReplacingOccurrencesOfString: #" " withString: #""];
// *** Now user `myToken` to send notification ***
NSLog(#"%#",myToken);
}
Along with it you need to make sure you are running your application with same provisional profile (Developer/Distribution) which is used to send push notification on your server side. both should be same. I hope its clear to you.

iBeacon: Settings of CLBeaconRegion identifier?

I use Apple AirLocate demo App to create an iBeacon.
Identifier: com.example.apple-samplecode.AirLocate
UUID: E2C56DB5-DFFB-48D2-B060-D0F5A71096E0
Major: 0
Minor: 0
Measured Power: -59
The signal is successfully picked up by an Android beacon detector App.
However, when I use the following codes to detect the iBeacon in iOS 8, the beacon does not show up:
self.coreLocation = [[CLLocationManager alloc] init];
_coreLocation.delegate = self;
NSString *identifier = [NSString stringWithFormat:#"com.example.apple-samplecode.AirLocate.%#", #"E2C56DB5-DFFB-48D2-B060-D0F5A71096E0"];
CLBeaconRegion *region = [[CLBeaconRegion alloc] initWithProximityUUID:uuid identifier:identifier];
if(region) {
region.notifyOnEntry = YES;
region.notifyOnExit = YES;
[_coreLocation startMonitoringForRegion:region];
}
No matter which value I use in the identifier field, the beacon is never found by CLLocationManager. Its delegates, didDetermineState: and didRangeBeacons: were never been called. However, delegate monitoringDidFailForRegion received this:
The operation couldn’t be completed. (kCLErrorDomain error 4.)
After looked up some documentations online, the error code 4 means:
Access to the region monitoring service was denied by the user.
But I use the following codes to prove my app is authorized to monitor region:
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
if(status == kCLAuthorizationStatusDenied) {
NSLog(#"didChangeAuthorizationStatus: Denied");
} else if(status == kCLAuthorizationStatusNotDetermined) {
NSLog(#"didChangeAuthorizationStatus: Not Determined");
} else if(status == kCLAuthorizationStatusAuthorizedAlways) {
NSLog(#"didChangeAuthorizationStatus: Authorized Always");
} else if(status == kCLAuthorizationStatusAuthorizedWhenInUse) {
NSLog(#"didChangeAuthorizationStatus: Authorized When In Use");
} else if(status == kCLAuthorizationStatusRestricted) {
NSLog(#"didChangeAuthorizationStatus: Restricted");
} else {
NSLog(#"didChangeAuthorizationStatus: Unknown");
}
}
and it returns:
didChangeAuthorizationStatus: Authorized When In Use
Given that:
I'm using iPhone 5s with iOS 8.1.2
I added NSLocationWhenInUseUsageDescription in Info.plist
In Capabilities page, I enabled "Location updates" and "Uses Bluetooth LE accessories" (Xcode added corresponding entries to Info.plist)
Requested "When In Use" Authorization via [self.coreLocation requestWhenInUseAuthorization]
Allowed "Location Service" and "Push Notification" during first launch of the App
Airplane Mode is OFF
Bluetooth is ON
Wi-Fi is ON, connected to Internet
Settings > General > Background App Refresh is ON
Settings > Privacy > Locations Services > My App > While Using (tick)
[CLLocationManager isMonitoringAvailableForClass:[CLRegion class]] returns YES
What did I miss to cause this error 4 ? Also, does the identifier necessary to match with the iBeacon's Bundle Identifier (why Android can detect all beacons, but iOS need to specify identifiers)?
Reference: Region Monitoring and iBeacon
A couple of suggestions:
Try an off the shelf iOS detector from the AppStore like Locate to eliminate a hardware issue.
If the above works, try uninstalling and reinstalling your app. I have seen the location permission get screwed up if the authorization code was added after the app was already run.
Also, it may be helpful to post your Info.plist in case there is an issue there.

resolving an NSURLErrorCannotOpenFile error

I wrote some code to download a URL to my disk, using an NSURLRequest and an NSURLDownload. The download starts fine (at least, it sends downloadDidBegin:(NSURLDownload *)download), but then it sends
-(void)download:(NSURLDownload *)download didFailWithError:(NSError *)error
My implementation of the function is as follows:
{
[download release];
NSLog(#"Download failed! Error - %# %#",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
The logged error is
2011-07-17 01:48:43.194 URLDownloader[28031:903] Download failed! Error - The operation couldn’t be completed. (NSURLErrorDomain error -3001.) [the URL in the NSURLRequest]
From what I can tell, this is the NSURLErrorCannotOpenFile error. I cannot find any explanation of why this error occurs, other then "Returned when NSURLDownload was unable to open the downloaded file on disk." from the documentation. So, why is this happening?
Fact that might be helpful(?): NSURLErrorCannotOpenFile is enumerated as kCFURLErrorCannotOpenFile. I have no idea what this means either....
Alright, so I was just being foolish. I had created a path using NSURL's absoluteString method instead of the path method. This was just bad coding on my part...

Use twitter ios sdk oAuth

I try to use MGTwitterEngine for twitter Iphone integration,
this is supporting both xAuth and oAuth as per its documentation
and firstly I try it using xAuth as which function I am calling named getXAuthAccessTokenForUsername
But my application is in developing stage .. and twitter not approving it .. they will approve it after release...
I am not able to use oAuth using MGTwitterEngine
Can anybody help me...
Even I am not able to use oAuth version from source
http://mobile.tutsplus.com/tutorials/iphone/twitter-api-iphone/comment-page-1/
I can update my status successfully using it...But not able do any thing else
I try
[_engine getUserInformationForEmail:#"battan20#gmail.com"];
//_engine is the twitterengine object
then getting error
Request 9EF8DE73-6E04-46F1-9D90-484F90FCA44F failed with error: Error Domain=HTTP Code=404 "The operation couldn’t be completed. (HTTP error 404.)"
Request 016DB024-1BFB-4E9B-8734-3FFCCB93D6E4 failed with error: Error Domain=HTTP Code=403 "The operation couldn’t be completed. (HTTP error 403.)"
Please help me
Amit Battan
When today I call
NSString *abc = [twitterObj getUserInformationFor:#"amit_battan"];
NSLog(#"abc...%#",abc);
Then I got the log
abc...F4BBA3C6-5783-46FF-A383-1B9C2319AB43
Request F4BBA3C6-5783-46FF-A383-1B9C2319AB43 succeeded
means it works ok...
But How I get the output.. in which function/variable
-(void)userInfoReceived:(NSArray *)userInfo forRequest:(NSString *)connectionIdentifier {
NSMutableArray *mFollowerArray = nil;
mFollowerArray = [userInfo retain];
NSLog(#"count = %d",[mFollowerArray count]);
for (int i=0; i<[mFollowerArray count]; i++) {
NSLog(#" %#",[mFollowerArray objectAtIndex:i]);
}
}
above code might help