Ошибка 1012 не удалось завершить операцию

Last modified: Jul 9, 2014 8:07 AM

Last modified: Jul 9, 2014 8:07 AM

Rating: 5 out of 5



3

2 likes


44,338 views



Last modified Jul 9, 2014 8:07 AM

This tip is derived from the thread started by

AppStore Error «NSURLErrorDomain error -1100» – how to fix it

by roto. Corrected a couple typos and after the quote added some commentary:

After searching around for a longer time how to fix this problem in Software-Update, I finally found out how to manage this:

1. Delete PLISTs

/Users/<my username>/Library/Preferences/com.apple.appstore.plist

/Users/<my username>/Library/Preferences/com.apple.appstore.plist.lockfile

/Users/<my username>/Library/Preferences/com.apple.softwareupdate.plist

[/ indicates the path from the boot hard drive to folders inside. Use Go to Folder in the Go menu to navigate to that folder

replacing <my username> with the login user trying to access the store, the file in question is after the last slash. Quitting from the Mac App Store is recommended before you delete these files, by going to the Mac App Store menu and selecting Quit.]

2. In Applications -> Utilities -> Terminal type or copy/paste:

sudo killall -HUP mDNSResponder

[Hit enter/return key when done typing the above. Enter your administrative password when requested followed by return/enter key.]

Mac OS X 10.6.6 to 10.6.8 users should use instead:

sudo dscacheutil -flushcache

Source: OS X: How to reset the DNS cache

3. Restart

Then:

1. Open System Preferences — Network

2. Highlight active connection

3. Click Advanced.

4. TCP/IP

5. Renew DHCP Lease

Step 2, mDNSResponder issues should not happen unless:

1. The internet service provider is not supporting your IPv6 or IPv4 configuration.

2. The internet service provider has latency issues, such as satellite connections.

3. The internet service provider has a proxy/firewall configuration getting in the way. Often this setup is common with schools and corporate networks.

4. The DNS at the internet service provider is corrupted. To isolate this, change the DNS to an http://www.opendns.org/ one.

Also generally speaking sudo commands should not be issued, or moving any files after a sudo command without ensuring file sharing is first turned off. The good portion of this tip is the reboot which clears the login for sudo, which can leave your machine vulnerable until the reboot has been executed.

Software such as Little Snitch, and software firewalls may also interfere with the connection, as well as peer2peer software.

I need to parse a xml file from a password protected URL I tried the following

NSURLCredential *credential = [NSURLCredential credentialWithUser:@"admin"  password:@"123456" persistence:NSURLCredentialPersistenceForSession];
NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc]
                                         initWithHost:@"xyz.com"
                                         port:80
                                         protocol:@"http"
                                         realm:nil
                                         authenticationMethod:NSURLAuthenticationMethodDefault];  
[[NSURLCredentialStorage sharedCredentialStorage] setCredential:credential
                                             forProtectionSpace:protectionSpace];    
url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"GET"];
[request setValue:@"application/xml" forHTTPHeaderField:@"Content-Type"];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
NSURLResponse *response;
NSError *error;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse: &response error: &error];   
 NSString *dataStr=[[NSString alloc]initWithData:returnData encoding:NSUTF8StringEncoding]; 
 NSLog(@"data == %@n error in connecting == %@",dataStr,error);

I got the following response

data == <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>401 Authorization Required</title>
</head><body>
<h1>Authorization Required</h1>
<p>This server could not verify that you
are authorized to access the document
requested.  Either you supplied the wrong
credentials (e.g., bad password), or your
browser doesn't understand how to supply
the credentials required.</p>
<p>Additionally, a 401 Authorization Required
error was encountered while trying to use an ErrorDocument to handle the request.</p>
</body></html>

error in connecting == Error Domain=NSURLErrorDomain Code=-1012 «The operation couldn’t be completed. (NSURLErrorDomain error -1012.)» UserInfo=0x6e51b90 {NSErrorFailingURLKey=http://example.com/api/ID/password/xml/,

Any help is appreciated !

Я получаю следующую ошибку при запуске моего кода из xcode.

Домен ошибки = Код NSURLErrorDomain = -1012 «Операция не может быть завершена. (Ошибка NSURLErrorDomain -1012.)» UserInfo = 0x17166b740 {NSErrorFailingURLStringKey=https://…./move/resource/v1/user/me/activity/summary?start_date=2015-01-21&end_date=2015-01-14&detail=true, NSUunderlyingError=0x17405b630 «Операция не может быть завершена. (kCFErrorDomainCFNetwork ошибка -1012.)», NSErrorFailingURLKey=https://…./move/resource/v1/user/me/activity/summary?start_date=2015-01-21&end_date=2015-01-14&detail=true}

Вот мой код

  NSString *urlSummaryString = [[NSString stringWithFormat: @"%@summary?start_date=%@&end_date=%@&detail=true", kMisfitCloudEndpoint, strStartDate,strEndDate] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    __block NSMutableDictionary *responseDict = [NSMutableDictionary dictionary];
    __block NSError *error = nil;
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlSummaryString] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20.0];
    [request setValue:@"access_token" forHTTPHeaderField:self.misfitAccessToken];
    [request setHTTPMethod:@"GET"];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if(connectionError){
            // Handle the connection error
            return ;
        }}];

Может ли кто-нибудь помочь мне, что здесь не так. Это связано с сертификатом SSL на сервере и связано с безопасностью. Когда я использую CocoaRestClient для выполнения своего запроса, он работает отлично.

Может ли какой-нибудь орган подробно объяснить мне, что вызывает эту проблему, или может ли какой-либо орган решить эту проблему. Я должен использовать метод [NSURLConnection sendAsynchronousRequest]. Я использую Xcode 6.1 и ios 8.1.2.

2 ответа

В моем случае я делаю очень глупую ошибку.

[request setValue:self.misfitAccessToken forHTTPHeaderField:@"access_token" ];

Это решило мою проблему


2

Abdul Samad
22 Янв 2015 в 14:37

Это ошибка kCFURLErrorUserCancelledAuthentication, Ошибки -10xx относятся к перечислению CFNetworkErrors. Название этой константы говорит само за себя. Сервер по какой-то причине отменил аутентификацию


2

user1232690
3 Сен 2015 в 01:16

нам было трудно защитить сетевые подключения нашего приложения с помощью SSL с помощью AFNetworking 2.5.0.

мы используем самозаверяющий центр сертификации и реализовали пользовательскую политику безопасности с использованием закрепленных сертификатов.

мы протестировали довольно много конфигураций, предоставляемых AFNetworking, но пока не повезло. Сообщение об ошибке, которое мы получаем:

2015-01-05 19: 03: 07.191 AppName[9301: 319051] ошибка обновления пользователя
путешествие. Ошибка: Ошибка Domain=NSURLErrorDomain Код=-1012 «На
операция не может быть завершена. (Ошибка NSURLErrorDomain -1012.)»
UserInfo=0x7ae056b0
{NSErrorFailingURLKey=https://api.XXX.com/XXX/XXX/,
NSErrorFailingURLStringKey=https://api.XXX.com/XXX/XXX/}

наш сертификат отлично работает на других клиентах, таких как cURL и Android. При использовании HTTP наша реализация работает отлично.

кто-нибудь знает о каких-либо проблемах связанные с закрепленными сертификатами и AFNetworking? Если да, мы будем признательны за любые советы, которые у вас могут быть.

вот часть реализации:

+ (AFSecurityPolicy*)customSecurityPolicy {
   AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
   NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"filename" ofType:@"der"];
   NSData *certData = [NSData dataWithContentsOfFile:cerPath];
   [securityPolicy setAllowInvalidCertificates:NO];
   [securityPolicy setValidatesCertificateChain:NO];
   [securityPolicy setPinnedCertificates:@[certData]];
   return securityPolicy;
}

+ (AFHTTPRequestOperationManager*)customHttpRequestOperationManager {
   AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
   manager.securityPolicy = [self customSecurityPolicy]; // SSL
   return manager;
}

+(void)getRequestWithUrl:(NSString*)url success:(void(^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void(^) (AFHTTPRequestOperation *operation, NSError *error))failure {
   [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
   AFHTTPRequestOperationManager *manager = [HttpClient customHttpRequestOperationManager];
   manager.responseSerializer = [AFHTTPResponseSerializer serializer];
   [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
       [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
       success(operation, responseObject);
   } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
       [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
       failure(operation, error);
   }];
}

спасибо!

8 ответов


после прочтения кода AFNetworking и проверки журналов изменений, вот что я должен был сделать, чтобы заставить это работать.

создайте объект AFSecurityPolicy с помощью AFSSLPinningModeCertificate:

AFSecurityPolicy* policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];

по умолчанию AFNetworking проверяет доменное имя сертификата. Наши сертификаты генерируются на серверной основе, и не все из них будут иметь доменное имя, поэтому нам нужно отключить это:

[policy setValidatesDomainName:NO];

так как сертификаты являются самоподписанными, они технически «недействительны», поэтому нам нужно разрешить и это:

[policy setAllowInvalidCertificates:YES];

наконец, AFNetworking попытается проверить сертификат на всем пути вверх по цепочке сертификатов, которая мне кажется, что она будет идти только вверх по цепочке к нашему CA, но по какой-то причине это не так, поэтому мы должны отключить это тоже:

[policy setValidatesCertificateChain:NO];

и это все! Установите политику безопасности в диспетчере запросов, как вы уже делаете, и она должна работать штраф.

Итак, резюмируем, все, что вам действительно нужно изменить в коде, который вы опубликовали, это:

A) Как Дэвид Caunt упомянуто, измените режим закрепления с AFSSLPinningModeNone до AFSSLPinningModeCertificate

и

B) добавьте строку, чтобы отключить проверку доменного имени:[policy setValidatesDomainName:NO]

еще одно примечание, AFNetworking теперь автоматически проверяет ваш пакет .файлы cer, поэтому, если вы должны были переименовать свой сертификат, чтобы иметь .расширение cer, вы можете устранить код для получения данных сертификата из пакета и установки закрепленных сертификатов.


поскольку вы инициализировали manager, вы можете сделать:

manager.securityPolicy.allowInvalidCertificates = YES;
manager.securityPolicy.validatesDomainName = NO;

и он будет работать для самозаверяющего сертификата


Я получал эту ошибку,Error Domain=NSURLErrorDomain Code=-1012 NSErrorFailingURLStringKey

только нижеприведенное изменение заставило его работать на меня.

self.validatesDomainName = NO;

вы создаете AFSecurityPolicy С SSLPinningMode режим AFSSLPinningModeNone.

для AFNetworking доверять серверу, с режимом закрепления установлен в AFSSLPinningModeNone, вы должны установить allowInvalidCertificates to YES, но это напротив чего вы пытаетесь достичь.

вместо этого вы должны создать свою политику безопасности с помощью режима закрепления AFSSLPinningModeCertificate или AFSSLPinningModePublicKey:

AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];

3

автор: David Snabel-Caunt


- (AFSecurityPolicy *)securityPolicy {
    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"*.something.co.in" ofType:@"cer"];
    NSData *certData = [NSData dataWithContentsOfFile:cerPath];
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
    [securityPolicy setAllowInvalidCertificates:YES];
    [securityPolicy setPinnedCertificates:@[certData]];
    [securityPolicy setValidatesDomainName:NO];
    [securityPolicy setValidatesCertificateChain:NO];
    return securityPolicy;
}

это то, что ошибка генерации политики безопасности выглядит как —

- (AFSecurityPolicy *)securityPolicy {
    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"*.something.co.in" ofType:@"cer"];
    NSData *certData = [NSData dataWithContentsOfFile:cerPath];
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
    [securityPolicy setAllowInvalidCertificates:NO];
    [securityPolicy setPinnedCertificates:@[certData]];
    [securityPolicy setValidatesDomainName:YES];
    return securityPolicy;
}

теперь придерживаясь правила «не исправить, если он не нарушен»


имея дело с аналогичной проблемой, это обычно для вещей, кажущихся нормальными через HTTPS-соединения браузера, так как многие браузеры кэшируют файлы сертификатов от третьих лиц, так что они не всегда должны быть загружены. Поэтому вполне может быть, что ваша цепочка сертификатов не полностью доверена, как вы, возможно, поверили.

другими словами, может показаться, что безопасно подключаться к браузеру, но в зависимости от настроек AFNetworking ваше приложение фактически не будет принимать цепочка сертификатов. После того, как вы убедитесь, что ваши настройки подходят, следующий шаг-убедиться, что цепочка сертификатов действительно так хороша, как вы думаете. Загрузите приложение под названием SSL Detective и запросите свой сервер. Вы также можете использовать www.ssldecoder.org. Убедитесь, что в вашей цепочке нет красных (ненадежных) элементов. Если есть, измените настройку сертификата на сервере.

учитывая, что настройки AFNetworking следующие:

 [securityPolicy setAllowInvalidCertificates:NO];
 [securityPolicy setValidatesCertificateChain:NO];

Это может не похоже на цепочку сертификатов, потому что она подписана самостоятельно. Возможно, Вам также придется переключить их на «да».


для меня, у меня use_frameworks! установить в my Podfile — проект не делает пользователя Swift, и я использовал Pods на AFNetworking. Комментируя это, исправил проблему для меня.


Я пробовал все это, но ничего не помогло, тогда я искал эту строку

‘ NSLog (@»для проверки доменного имени для самозаверяющих сертификатов необходимо использовать закрепление.»);’

и ниже этой строки я изменил

‘ return NO;’
к

‘вернуться да;’

и это магия.

спасибо.


Понравилась статья? Поделить с друзьями:
  • Ошибка 10022 easyanticheat
  • Ошибка 1002 социал клаб
  • Ошибка 1002 рокстар геймс
  • Ошибка 1002 ошибка графического интерфейса directx недоступен
  • Ошибка 1002 не удалось установить соединение websocket