NSCocoaErrorDomain = 256 - ios

I'm using this code to get the php page response from a GET call from my iOS app.
NSLog(#"%#", parameters);
// Send data to the web services
NSError *error;
NSString *result = [NSString stringWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://178.63.103.3/hermes-resource/ws.php%#", parameters]] encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%#", error);
NSString *result_;
if (result)
{
result_ = [self convert:result];
}
That's the error I got from stringWithContentsOfURL method and the log of parameters string.
2014-07-18 11:44:51.036 Hermes[542:60b] ?name=Luca D'Alberti&email=email#ext.it&range=21-39&graphic=5&userx=1&gamed=Si&comment_game=&errors=No&comment_errors=&feed=Fvdgd fvdgd
2014-07-18 11:44:51.042 Hermes[542:60b] Error Domain=NSCocoaErrorDomain Code=256 "The operation couldn’t be completed. (Cocoa error 256.)"
Why this error do occur?

The error is NSFileReadUnknownError source: Foundation Constants

Related

How do I get around NSCocoaErrorDomain:257 when pulling a file from the Files app?

I'm trying to access a file to pull a copy into my app so that users can associate it with relevant information. It used to work just fine up until recently, and now I suddenly am getting the following message:
Failed to read file, error Error Domain=NSCocoaErrorDomain Code=257 "The file “[File name]” couldn’t be opened because you don’t have permission to view it." UserInfo={NSFilePath=/private/var/mobile/Library/Mobile Documents/com~apple~CloudDocs/[File name], NSUnderlyingError=0x281b88690 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}
This is the code that's throwing the error:
//AppDelegate.m
-(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
if (![url.pathExtension isEqualToString:#"pdf"] && ![url.pathExtension isEqualToString:#"png"] && ![url.pathExtension isEqualToString:#"jpg"] && ![url.pathExtension isEqualToString:#"jpeg"]){
return false;
}
NSError* error = nil;
NSString *path = [url path];
NSData *data = [NSData dataWithContentsOfFile:path options: 0 error: &error];
if(data == nil) {
NSLog(#"Failed to read file, error %#", error);
}
//Do stuff with the file
return true;
}
I did update to xcode 11 and iOS 13, so there may have been a change there that I wasn't aware of.
It turns out there's a "using" function that tells the app its accessing files outside of it's sandbox. The methods startAccessingSecurityScopedResource and stopAccessingSecurityScopedResource on NSURL need to be wrapped around the code using the url, like so:
BOOL isAcccessing = [url startAccessingSecurityScopedResource];
NSError* error = nil;
NSString *path = [url path];
NSData *data = [NSData dataWithContentsOfFile:path options: 0 error: &error];
if(data == nil) {
NSLog(#"Failed to read file, error %#", error);
}
if (isAccessing) {
[url stopAccessingSecurityScopedResource];
}
I'm not sure if there's anything specific to iOS 13 that requires this when it didn't previously, but that is the only real change between it working and not working.
Jordan has a great answer! Here's the version translated to Swift
let isAccessing = url.startAccessingSecurityScopedResource()
// Here you're processing your url
if isAccessing {
url.stopAccessingSecurityScopedResource()
}
As I encountered this myself and the comment to Jordan's answer confirmed this happens only on the real device. Simulator has no such an issue

kCFErrorDomainCFNetwork error -1005 AFNetworking

I have a singleton class:
+(id)sharedClient
{
static HackerNewsClient *__instance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSURL *url = [NSURL URLWithString:#"http://node-hnapi.herokuapp.com"];
__instance = [[HackerNewsClient alloc] initWithBaseURL:url];
});
return __instance;
}
And in a controller I am calling this like so:
[[HackerNewsClient sharedClient]GET:#"/news"
parameters:nil
success:^(NSURLSessionDataTask *task, id responseObject) {
NSArray *posts = [self parseEpisodeJSONData:responseObject];
completion(posts);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"ERROR: %#", error);
}];
The url this creates is http://node-hnapi.herokuapp.com/news which is a valid and working url. But the error message returned is
2014-07-08 08:51:15.942 hn[27435:1627947] ERROR: Error Domain=NSURLErrorDomain Code=-1005 "The operation couldn’t be completed. (NSURLErrorDomain error -1005.)" UserInfo=0x10ba2bf70 {NSErrorFailingURLStringKey=http://node-hnapi.herokuapp.com/news, NSErrorFailingURLKey=http://node-hnapi.herokuapp.com/news, _kCFStreamErrorDomainKey=1, _kCFStreamErrorCodeKey=57, NSUnderlyingError=0x10ba22ff0 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1005.)"}
I can't work out what would be causing this issue. Thanks
this error always appeared when the connection fails ..
if your connection work fine just try to restart the iPhone simulator spicily with iPhone 6 simulator ...!
check link : NSURLConnection GET request returns -1005, "the network connection was lost"
Look in the CFNetworkErrors header files for CFNetwork Framework.
In Xcode navigate to
ProjectName > Frameworks > CFNetwork.framework > Headers > CFNetworkErrors.h

AFNetworking request with Basic Auth works at first but fails after a few minutes

I have an app with data fed from an AFNetworking request with basic auth. I have a refresh button to perform the same function used to initially feed the data. This all works, but after a couple minutes it doesn't.
My code:
- (void) refreshData
{
// Show loading
NSLog(#"Refreshing...");
[LoadingView initInView:self.view];
// Get session data for auth key
SessionHelper *session = [SessionHelper sharedInstance];
// Setup request
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager setRequestSerializer:[AFHTTPRequestSerializer serializer]];
[manager.requestSerializer clearAuthorizationHeader];
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:session.authKey password:#""];
NSString *url = #"https://myurl.com/getdata";
[manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
self.data = [[NSMutableArray alloc] init];
[self.data addObjectsFromArray:responseObject];
[self.tableView reloadData];
[LoadingView remove];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", [error description]);
[operation cancel];
}];
}
Works repeatedly fine at first, but after a few minutes it hangs with the loading screen (from LoadingView) and the error:
Error: Error Domain=NSURLErrorDomain Code=-1012 "The operation
couldn’t be completed. (NSURLErrorDomain error -1012.)"
UserInfo=0x8a5ed20 {NSErrorFailingURLKey=https://myurl.com/getdata,
NSErrorFailingURLStringKey=https://myurl.com/getdata}
I thought maybe I needed to do clearAuthorizationHeader or something, but no go. Any ideas? Thanks!
Update: Logging operation.response.statusCode in the error message
gives me 0.
Update 2: Using AFNetworkActivityLogger gives me this after it starts failing:
2014-02-26 13:23:02.206 MyApp iPad[4087:60b]
GET 'https://myurl.com/getdata' 2014-02-26 13:23:02.646 MyApp
iPad[4087:60b] [Error] GET '(null)' (0) [0.4332 s]: Error
Domain=NSURLErrorDomain Code=-1012 "The operation couldn’t be
completed. (NSURLErrorDomain error -1012.)" UserInfo=0x17d9a990
{NSErrorFailingURLKey=https://myurl.com/getdata,
NSErrorFailingURLStringKey=https://myurl.com/getdata} 2014-02-26
13:23:02.648 MyApp iPad[4087:60b] Error: Error Domain=NSURLErrorDomain
Code=-1012 "The operation couldn’t be completed. (NSURLErrorDomain
error -1012.)" UserInfo=0x17d9a990
{NSErrorFailingURLKey=https://myurl.com/getdata,
NSErrorFailingURLStringKey=https://myurl.com/getdata}, Status Code: 0
Seems the URL is being sent as (null)...
Turns out, even though the GoDaddy certificate I'm using looks to be valid and supported by iOS 7 according to http://support.apple.com/kb/HT5012, adding this bit solves the problem. Seems to kind of defeat the purpose, but it works. I won't accept this answer yet in case someone can give some insight / something more helpful.
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
securityPolicy.allowInvalidCertificates = YES;
manager.securityPolicy = securityPolicy;

Dropbox Sync API Won't Download Any Files

I have been struggling with this for two days now, but I cannot get it to work. Part of the reason I'm fighting with this is that the official Dropbox Sync API tutorial does a very poor job explaining how to get this done.
So far I can write anything using the Dropbox API, but getting anything is being a whole different beast on its own.
I have the following code (apologies if it is chaotic - I have been testing a lot and it's just natural it will clutter up sooner or later) in my app delegate's - (void)applicationDidBecomeActive:(UIApplication *)application method:
if([[[DBAccountManager sharedManager] linkedAccount] isLinked])
{
DBError *erri = nil;
if(!self.collectionsFile.open)
{
DBPath *newPath = [[DBPath root] childPath:[NSString stringWithFormat:#"metadata/%#", #"user_collections.json"]];
//self.collectionsFile = [[DBFilesystem sharedFilesystem] createFile:newPath error:nil];
self.collectionsFile = [[DBFilesystem sharedFilesystem] openFile:newPath error:&erri];
}
DBFileStatus *newerStatus = self.collectionsFile.newerStatus;
DBFileStatus *status = self.collectionsFile.status;
NSLog(#"%# erri", erri.localizedDescription);
__block NSString *contents = [self.collectionsFile readString:nil];
NSLog(#"Contents %#", contents);
[self.collectionsFile addObserver:self block:^(){
NSLog(#"Observer called");
if([[DBFilesystem sharedFilesystem] completedFirstSync])
{
NSLog(#"First sync done");
if(newerStatus != nil)
{
NSLog(#"File is downloading.");
}else
{
NSLog(#"Im here dude %#", contents);
NSString *metadata = [(FTIBAppDelegate *)[[UIApplication sharedApplication] delegate] getMetadataPath];
NSString *collectionsFile = [NSString stringWithFormat:#"%#/%#", metadata, #"user_collections.json", nil];
[contents writeToFile:collectionsFile atomically:NO encoding:NSUTF8StringEncoding error:nil];
}
if(status.cached)
{
NSString *metadata = [(FTIBAppDelegate *)[[UIApplication sharedApplication] delegate] getMetadataPath];
NSString *collectionsFile = [NSString stringWithFormat:#"%#/%#", metadata, #"user_collections.json", nil];
[contents writeToFile:collectionsFile atomically:NO encoding:NSUTF8StringEncoding error:nil];
}
}
}];
}
Whenever I reinstall my app and link Dropbox again, I get this beautiful output:
2014-01-21 15:58:24.171 Mignori[913:60b] App linked successfully!
2014-01-21 15:58:24.301 Mignori[913:60b] [WARNING] ERR:
DROPBOX_ERROR_USAGE: sync.cpp:210: Checking file path before file
types info has been fetched. Wait for first sync to avoid creating a
file which may fail to upload later. 2014-01-21 15:58:24.473
Mignori[913:60b] [ERROR] ERR: DROPBOX_ERROR_ALREADYOPEN: file.cpp:188:
p(/v1/t5.json) already open (1) 2014-01-21 15:58:24.528
Mignori[913:60b] DropboxSync error - Error Domain=dropbox.com
Code=2004 "The operation couldn’t be completed. (dropbox.com error
2004.)" UserInfo=0x17028ba0 {desc=file.cpp:188: p(/v1/t5.json) already open (1)} 2014-01-21 15:58:24.531 Mignori[913:60b] The operation
couldn’t be completed. (dropbox.com error 2004.) erri 2014-01-21
15:58:24.532 Mignori[913:60b] Contents (null)
A couple of things to keep in mind:
The file (user_collections.json) does exist in my Dropbox - I'm updating it with a different device.
My File is a strong property of the app delegate.
I will appreciate any help to get this to work. Even a (better) sample code on how to get this done. I can update files in Dropbox with no problem at all, but downloading them is being much more complicated than I expected.
The problem was that I was trying to open the file when the initial sync wasn't completed. You have to wait until it's done. Set an NSThread to constantly check if your filesystem's completeFirstSync is completed.

creating event using facebook sdk 3.1

i am trying to create an event but getting error . i am writing following code to create event using facebook sdk 3.1
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"My Test Event",#"name",
#"Bangalore",#"location",
#"1297641600",#"start_time",
#"1297468800",#"end_time", nil];
NSString * pRequest = [NSString stringWithFormat:#"me/events"];
[FBRequestConnection startWithGraphPath:pRequest parameters:params HTTPMethod:#"POST" completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error)
{
NSLog(#"Facebook Post Success..");
} else
{
NSLog(#"Facebook Post Failed..");
NSLog(#"ERROR : %#", error.localizedDescription);
}
}];
error :
Error Domain=com.facebook.sdk Code=5 "The operation couldn’t be completed. (com.facebook.sdk error 5.)" UserInfo=0xa180200 {com.facebook.sdk:ParsedJSONResponseKey={
body = {
error = {
code = 100;
message = "(#100) Invalid parameter";
type = OAuthException;
};
};
code = 400;
}, com.facebook.sdk:HTTPStatusCode=400}
can anybody help .....
thanks in advance
The error is a 400 error a bad request. This means there is something wrong with you're request. Also the error that Facebook returns suggest that you have an invalid parameter. So I suggest to double check you're parameters that you are sending and make sure you sending the correct amount of parameters in the right order and the right values.

Resources