Error Domain=NSCocoaErrorDomain Code=256
I was working on a proof of concept app for Apple APS notifications, and happy to have the basics working. The next step I had was to send the device token to my server, so that it could be stored in a database, and matched up with a user account.
So, I wrote a simple ASPX page that took in the querystring value “token” and stored it in the database (10 minutes work). then I wanted to write some Objective C code, to add to the didRegisterForRemoteNotificationsWithDeviceToken event so that it could call my URL, with the assigned device token.
A simple way of making a Syncronous HTTP request in Objective C is
NSError* error; // this is not required, but good to have
NSString* apiUrlStr = [NSString stringWithFormat:@”http://dev.testsite.com/test.json”%5D; // First create an NSString with the link that you need to query:
NSURL* apiUrl = [NSURL URLWithString:apiUrlStr]; // Convert the String to an NSURL.
NSString *apiResponse = [NSString stringWithContentsOfURL:apiUrl encoding:NSASCIIStringEncoding error:&error];
But, as soon as I tried this:
NSString* apiUrlStr = [NSString stringWithFormat:@”http://www.website.com/aps/notify.aspx?token=%@”,deviceToken];
I got this error in the console window
013-10-17 18:39:27.975 PushChat[136:307] My token is: <5214df32 2acfa9eb 57aafaa1 29417e30 f76a2c3d e3591538 975e5623 e091af36>
2013-10-17 18:39:28.048 PushChat[136:307] Url called is: http://www.website.com/aps/notify.aspx?token=<5214df32 2acfa9eb 57aafaa1 29417e30 f76a2c3d e3591538 975e5623 e091af36>
2013-10-17 18:39:28.191 PushChat[136:307] Api response: (null)
2013-10-17 18:39:28.255 PushChat[136:307] Any Error: Error Domain=NSCocoaErrorDomain Code=256 “The operation couldn’t be completed. (Cocoa error 256.)” UserInfo=0x144df0 {}
The simple solutions offered online were
A. Your phone has no Wifi connection. (DUH)
B. If connecting to HTTPS:// the certificate may be bad.
Neither were the case, so, applying some logic, I thought that perhaps it didn’t like the non-url-encoded querystring, with spaces and angle brackets. Which, ironically, needed to be stripped off at the server anyway, so I added the code:
NSString* strToken = [NSString stringWithFormat:@”%@”, deviceToken];
strToken = [strToken stringByReplacingOccurrencesOfString:@” ” withString:@””];
strToken = [strToken stringByReplacingOccurrencesOfString:@”<” withString:@””];
strToken = [strToken stringByReplacingOccurrencesOfString:@”>” withString:@””];
And, it worked perfectly!
My first bit of real problem solving in Objective C. Very happy 🙂
A note on error handling:
NSError* error = nil;
… make the HTTP request …
if (error != nil)
{
NSLog(@”Error: %@”, error);
}
Always helps diagnose a problem.
LikeLike