Do you want to share content, devices, purchases, or other resources with your Apple Family members but end up seeing the 1005 error code? Do you also see the same code while adding a member to your shared Apple Family account?
If Apple Family displays error code 1005, this happens when the Family Sharing account settings are incorrect or the shared features are disabled on your device. To resolve the error, make sure you are using the same Apple ID as Apple Family Sharing or enable the shared features.
In this article, we’ll explore the possible reasons for the Apple Family error 1005 and discuss how you can fix the error in no time.
Why Isn’t Apple Family Share Working And Keep Showing Error 1005?
One of the following might be the reasons why Apple Family shows error 1005:
- The device does not meet the system requirements for Family Sharing
- Incorrect Family Sharing account settings
- Using different Apple IDs for Media & Purchasing
- The Shared feature services are disabled
- Purchase is hidden
- The app is not sharable
- The family member has already subscribed to Apple Music on a trial basis.
- Outdated device OS
How Do I Fix The Apple Family Error 1005?
The following are some quick and easy solutions to resolve the Apple Family error 1005.
Sign In and Out Of Apple ID
Signing in and out of the Apple ID on your device can help fix the minor glitches causing the error code 1005 or other problems, such as authorization with TikTok.
- Go to “Settings.”
- Tap your Apple profile and open the Apple ID details.
- Choose “Sign Out.”
- Next, enter your Apple ID details and tap “Turn Off.”
- Select the type of data you want to keep a copy of and tap “Sign Out.”
Check the Family Sharing Settings
The next solution is to check whether you are using the correct Apple ID for family sharing on your device.
Mac:
- Select “System Settings” from the Apple Menu.
- Click “Family” > “Purchases.”
- Check your Apple ID details here and launch “App Store.”
- Click “Store.”
- Select “Account.”
- Click “Account Settings” and ensure that you are using the same Apple ID as Apple Family Sharing.
iPhone:
- Head to “Settings.”
- Select “Family.”
- Tap your name and see which Apple ID is used.
- Select “Purchases.”
- Tap “Apple ID for Purchases” and ensure you’re signed in with the same Apple ID you use for Apple Family Sharing.
Apple TV:
- Connect the Apple TV to your Smart TV and turn it on.
- Open “Menu” on Apple TV.
- Then, go to “Settings.”
- Head to “User & Accounts,” check your Apple ID details and ensure that it is the same one you use for Apple Family Sharing.
Check If the App Is Enabled For Family Sharing
Since some apps might not be shareable on Family Sharing, your family won’t be able to re-download them on their device when you purchase them.
- Open “App Store” on your Mac/iPhone/iPad/Apple TV.
- Search for the app and tap it.
- Check the Support section and see if Family Sharing is listed.
Log Out and Re-Login To Media & Purchases
Another solution to resolve the error code 1005 is to sign out of Media & Purchase and sign in again using the same Apple ID as Family Sharing.
Mac
- Launch “App Store.”
- Click “Store.”
- Select “Sign Out.”
- Click “Sign In” and use the correct Apple ID.
iPhone/iPad:
- Head to “Settings.”
- Tap “[Your name.]/ Profile”
- Select “Media & Purchases.”
- Next, select “Sign Out.”
- Again, open “Media & Purchases.”
- Tap “Not (your name),” and log in again.
Apple TV:
- Head to “Settings” on your Apple TV.
- Select “Users & Accounts.”
- Choose “[your name].”
- Choose “Store.”
- Select “Sign Out.”
- Choose “Sign In” to add your Family Sharing Apple ID.
Note: Your device must meet certain system requirements to use Family Sharing. This includes using iPhone with iOS 8 or later and OS X Yosemite or later for Mac.
Enable Sharing Features
It is possible that the shared features are disabled on your Family Sharing account, resulting in the error code 1005.
- Open “Settings” on your iPhone/iPad.
- Tap the “Profile” icon.
- Select “Family Sharing.”
- Then, choose “Share Features.”
- Toggle on all the services.
Unhide the Purchase
If you’ve hidden the purchase, your family member will not be able to access it through Family Sharing and may get the 1005 error.
Unhide Purchase on Mac:
- Launch “App Store.”
- Click “[Your Name]” from the sidebar.
- Choose “Account Settings” or “View Information.”
- Sign in to your Apple ID.
- Click “Manage” under “Hidden Purchases/Hidden items.”
- Find the app you want to unhide and click “Unhide.”
- Click “Done,” and the app will appear in your Purchase list.
Unhiding Purchase on iOS:
- Open “App Store” from your device’s App Library/Home screen.
- Tap the “Account/Your Profile” button.
- Tap your “Apple ID/Name.”
- Next, sign in with your Apple ID.
- Tap “Hidden Purchases.”
- Select the app, tap “Unhide,” and you are done!
Remove and Re-Add The Family Members
Removing and re-adding the family members can also resolve Apple Family error code 1005.
- Open “Setting” from the Home screen/App Library on your iOS device.
- Tap “Family Sharing.”
- Choose the member you want to remove and tap “Remove.”
- Tap “Add Member” and send an invitation to the family member.
Note: If you are getting the error code while adding a family member, ensure that you are not exceeding the Apple Family Sharing member’s limit.
Wait For The Trial To Expire
If your family member has already got a trial subscription to Apple Music to play and download songs, they won’t be able to access your Family Sharing subscription until their trial period expires.
Therefore, wait for the trial period to expire and share your subscription with them again.
Update the Device Software/Firmware
The last solution is updating your device’s firmware/software to the latest version.
Mac:
- Click “System Settings” or “System Preferences.”
- Next, go to “General.”
- Click “Software Update.”
- Click “Update Now” or “Upgrade Now.”
iOS device:
- Go to “Settings.”
- Tap “General.”
- Select “Software Update.”
- Tap “Install Now” or “Download and Install.”
- Enter your device password and tap “Install Now.”
Apple TV:
- On the Apple TV remote, press the “Menu” button.
- Head to the “Settings” column using the Apple TV remote.
- Select “System.”
- Choose “Software Updates.”
- Select “Update Software.”
- Choose “Download and Install.”
Note: Make sure to back up your data before updating the device.
Conclusion
In this article, we’ve explored why Apple Family shows the error 1005 while you are adding members to share resources and purchases with them. We’ve also figured out a few ways to get rid of the error with tried-and-tested workarounds.
However, if you are still seeing the same error code, contact Apple Support for further guidance and help.
Если вы пользуетесь iPad или iPhone, возможно, вы столкнулись с проблемами при просмотре, редактировании или отправке фотографий. Когда вы открываете приложение «Фото» или загружаете фотографию, вы получаете сообщение об ошибке «Сбой загрузки фото». За ошибкой следует сообщение «Произошла ошибка при загрузке этого фото из Медиатеки iCloud».
Вы можете столкнуться с этой проблемой, если включена функция «Оптимизация хранилища». Эта функция экономит место на вашем устройстве от Apple. Когда вы включаете эту функцию, полное разрешение фотографий и видео сохраняются в iCloud. Если фотографии или видео не могут быть выгружены из iCloud, вы увидите вышеупомянутое сообщение об ошибке. Более того, когда ваш iPhone автоматически оптимизирует вашу библиотеку, вы столкнетесь с такой же проблемой.
Говоря об устранении этой проблемы, читайте дальше, чтобы узнать, как ее исправить!
Серверы iCloud могут испытывать некоторые проблемы
Порой при загрузке фотографий на iPhone или iPad возникают проблемы на стороне сервера iCloud, и вы получаете данную ошибку. В этом случае вам следует немного подождать, а так же посетить страницу состояния системы Apple, выполнив следующие действия:
- Перейдите на сайт состояния системы Apple
- Найдите в списке службу «Фото»
- Если у службы фотографий возникла проблема, появится примечание с объяснением проблемы.
Если горит красный индикатор, вам придется подождать, пока Apple не решит проблему с системой iCloud. Ваши фото и видео начнут загружаться, как онлайн-сервис будет заново запущен.
Убедитесь, что ваш iPhone или iPad обновлен
Обновите свое устройство до последней версии iOS или iPadOS по беспроводной сети, выбрав «Настройки» — «Основные»> — Обновление ПО». Следуйте инструкциям на экране, если доступно обновление. Или же вы можете обновить свое устройство, подключив его к компьютеру с помощью кабеля USB. После подключения устройства перейдите в iTunes, перейдите в «Общие» и нажмите «Проверить наличие обновлений». Теперь следуйте инструкциям на экране.
Перезагрузите ваш iPhone или iPad
Вы можете попробовать перезагрузить свой iPhone или iPad. Шаги по перезагрузке iPhone различаются в зависимости от модели iPhone или iPad. Вот шаги для большинства моделей устройств iOS.
- Для iPhone X, iPhone 11, iPhone 12 или более новых моделей, и для iPad с Face ID, нажмите и удерживайте кнопку увеличения или уменьшения громкости и кнопку питания. Подождите, пока не отобразится ползунок отключения питания, перетащите ползунок и выключите устройство. Для включения — нажмите и удерживайте кнопку питания пока не появится логотип Apple.
- Для других моделей iPhone и iPad нажмите и удерживайте кнопку питания, дождитесь появления ползунка. Перетащите ползунок и выключите устройство. Снова включите устройство, нажав и удерживая кнопку питания, пока не появится логотип.
Ваше устройство подключено к Интернету?
Важно убедиться, что ваше устройство подключено к интернету. Проверьте подключение к Интернету, зайдя в Safari и посетив любой веб-сайт. Если он загружает, ваш Интернет подключен, а если нет, выполните следующие действия:
- Перезагрузите ваше устройство.
- Включите режим полета на 10 секунд и выключите его.
- Отключите роутер от розетки и снова подключите его через 30 секунд.
- В случае использования приложения «Фотографии» для передачи данных по сотовой сети необходимо включить параметр «Использовать сотовые данные» для фотографий. Перейдите в «Настройки» и «Сотовая связь» или нажмите «Мобильные данные» и затем включите «Фотографии».
Убедитесь, что на вашем устройстве достаточно памяти
Иногда недостаточное пространство для хранения также вызывает ошибки при загрузке фотографий. Чтобы проверить хранилище, перейдите в «Настройки» — «Основные»> — Хранилище». Следуйте инструкциям, чтобы оптимизировать хранилище вашего устройства. У вас должно быть не менее 1 ГБ свободного места.
Чтобы проверить место в iCloud, выберите «Настройки» — «ваше имя» — «iCloud». Удалите ненужные приложения или контент, чтобы освободить место.
Удалить и восстановить фотографии
Попробуйте удалить и восстановить свои фотографии, чтобы исправить ошибку загрузки фотографий на вашем устройстве.
- Перейдите в «Фото» и нажмите «Все фото».
- Найдите фото или видео с сообщением об ошибке и удалите его.
- Снова перейдите к фотографиям, а затем «Недавно удаленные».
- Найдите удаленную фотографию и коснитесь Восстановить.
- Откройте фотографию в Альбоме и посмотрите, сможете ли вы загрузить фотографию
Другие решения
Вы также можете попробовать следующие:
- В случае проблем с совместимостью, преобразуйте изображения в поддерживаемый формат, например HEIC в JPEG или PGN или JPEG или PNG в HEIC.
- Попробуйте поделиться фотографиями и видео в любом месседжере, которые вы не можете открыть. А затем сохраните их снова и снова откройте.
Удалось ли вам решить ошибку «Сбой загрузки фото» на iPhone или iPad?? Поделитесь своим ответом в комментариях ниже.
Поделиться ссылкой:
Looks like no one’s replied in a while. To start the conversation again, simply
ask a new question.
I am having trouble moving photos out of the new Photos app. I tried dragging an dropping, I tried dragging to PS Elements and then I tried exporting to a file on my desktop. Each time I get this message. It seems I cannot export … any suggestions? Many thanks!!
MacBook
Pro,
Mac OS X (10.6.7)
Posted on Apr 22, 2015 2:52 PM
3 replies
Dec 11, 2015 8:55 PM in response to Kahshe
🙂If draggin photos from iphoto to desktop is not working, Try a different way…..This is what worked for me..Select the image you want, then go to File > Export > Export 1 File. after you follow the prompts place a folder or location where you want this image to save to. Hope this helps as it did for me. ℹ
Jan 17, 2016 3:06 PM in response to Vic van Dijk
I’m having this problem also. Quitting did not work for me, but a full shut down and restart did. Weird! 😕
Error 1005 in Photos
I’ve tried to load icloud image using phasset with options
requestOptions.isSynchronous = false requestOptions.isNetworkAccessAllowed = true
I get CloudPhotoLibraryErrorDomain Code=1005 error I don’t understand where I make mistake, I have used SDWebImagePhotosPlugin methods as well as Photos methods like requestImageDataAndOrientation and requestImageData, still I get the image as nil and the above error
this is my code:
imageManager.requestImageDataAndOrientation(for: deviceImage, options: phImageRequestOptions()) { data,deliveryMode, orentation, _ in
if data != nil {
completion(data)
} else {
SDImageLoadersManager.shared.loaders = [SDWebImageDownloader.shared, SDImagePhotosLoader.shared]
SDWebImageManager.defaultImageLoader = SDImageLoadersManager.shared
let photosURL = NSURL.sd_URL(with: deviceImage)
SDImagePhotosLoader.shared.requestImage(with: photosURL as URL?, options: [.highPriority,.retryFailed,.refreshCached], context: [.customManager: self.manager], progress: nil) { image, data,error, success in
if image != nil {
completion(image?.pngData())
} else {
completion(nil)
}
}
}
I have this issue also, running on an iOS 8 device.
It is detailed some more here and seems to be a case of iOS trying to use connections that have already timed out.
My issue isn’t the same as the Keep-Alive problem explained in that link, however it seems to be the same end result.
I have corrected my problem by running a recursive block whenever I receive an error -1005 and this makes the connection eventually get through even though sometimes the recursion can loop for 100+ times before the connection works, however it only adds a mere second onto run times and I bet that is just the time it takes the debugger to print the NSLog’s for me.
Here’s how I run a recursive block with AFNetworking:
Add this code to your connection class file
// From Mike Ash's recursive block fixed-point-combinator strategy https://gist.github.com/1254684
dispatch_block_t recursiveBlockVehicle(void (^block)(dispatch_block_t recurse))
{
// assuming ARC, so no explicit copy
return ^{ block(recursiveBlockVehicle(block)); };
}
typedef void (^OneParameterBlock)(id parameter);
OneParameterBlock recursiveOneParameterBlockVehicle(void (^block)(OneParameterBlock recurse, id parameter))
{
return ^(id parameter){ block(recursiveOneParameterBlockVehicle(block), parameter); };
}
Then use it likes this:
+ (void)runOperationWithURLPath:(NSString *)urlPath
andStringDataToSend:(NSString *)stringData
withTimeOut:(NSString *)timeOut
completionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
OneParameterBlock run = recursiveOneParameterBlockVehicle(^(OneParameterBlock recurse, id parameter) {
// Put the request operation here that you want to keep trying
NSNumber *offset = parameter;
NSLog(@"--------------- Attempt number: %@ ---------------", offset);
MyAFHTTPRequestOperation *operation =
[[MyAFHTTPRequestOperation alloc] initWithURLPath:urlPath
andStringDataToSend:stringData
withTimeOut:timeOut];
[operation setCompletionBlockWithSuccess:
^(AFHTTPRequestOperation *operation, id responseObject) {
success(operation, responseObject);
}
failure:^(AFHTTPRequestOperation *operation2, NSError *error) {
if (error.code == -1005) {
if (offset.intValue >= numberOfRetryAttempts) {
// Tried too many times, so fail
NSLog(@"Error during connection: %@",error.description);
failure(operation2, error);
} else {
// Failed because of an iOS bug using timed out connections, so try again
recurse(@(offset.intValue+1));
}
} else {
NSLog(@"Error during connection: %@",error.description);
failure(operation2, error);
}
}];
[[NSOperationQueue mainQueue] addOperation:operation];
});
run(@0);
}
You’ll see that I use a AFHTTPRequestOperation
subclass but add your own request code. The important part is calling recurse(@offset.intValue+1));
to make the block be called again.
У меня есть приложение, которое отлично работает на Xcode6-Beta1 и Xcode6-Beta2 с iOS7 и iOS8. Но с Xcode6-Beta3, Beta4, Beta5 я столкнулся с проблемами сети с iOS8, но все отлично работает на iOS7. Я получаю сообщение об ошибке "The network connection was lost."
. Ошибка следующая:
Ошибка: Ошибка домена = NSURLErrorDomain Code = -1005 «Сетевое соединение было потеряно». UserInfo = 0x7ba8e5b0 {NSErrorFailingURLStringKey =, _kCFStreamErrorCodeKey = 57, NSErrorFailingURLKey =, NSLocalizedDescription = Сетевое соединение было потеряно., _kCFStreamErrorDomainKey = 1, NSUnderlyingError = 0x7a6957e0 «Сетевое соединение было потеряно.» }
Я использую AFNetworking 2.x и следующий фрагмент кода для выполнения сетевого вызова:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager setSecurityPolicy:policy];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:<example-url>
parameters:<parameteres>
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Success: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
Я пробовал NSURLSession
, но все равно получаю ту же ошибку.
Ответ 1
Перезапуск симулятора исправил проблему для меня.
Ответ 2
У нас была именно эта ошибка, и она оказалась проблемой с базовой реализацией HTTP NSURLRequest
:
Насколько мы можем судить, когда iOS 8/9/10/11 получает HTTP-ответ с заголовком Keep-Alive
, она сохраняет это соединение для повторного использования позже (как и должно быть), но сохраняет его больше, чем Параметр timeout
заголовка Keep-Alive (кажется, он всегда поддерживает соединение в течение 30 секунд.) Затем, когда приложение отправляет второй запрос менее чем через 30 секунд, оно пытается повторно использовать соединение, которое могло быть сбрасывается сервером (если прошло больше, чем реальный Keep-Alive
).
Вот решения, которые мы нашли до сих пор:
- Увеличьте параметр времени ожидания сервера выше 30 секунд. Похоже, что iOS всегда ведет себя так, как будто сервер будет держать соединение открытым в течение 30 секунд, независимо от значения, указанного в заголовке Keep-Alive. (Это можно сделать для Apache, установив параметр
KeepAliveTimeout
. - Вы можете просто отключить механизм поддержания активности для клиентов iOS на основе User-Agent вашего приложения (например, для Apache:
BrowserMatch "iOS 8." nokeepalive
в файле модаsetenvif.conf
) - Если у вас нет доступа к серверу, вы можете попробовать отправить ваши запросы с заголовком
Connection: close
: это скажет серверу немедленно прекратить соединение и ответить без заголовков поддержки активности. НО в настоящий момент NSURLSession, кажется, переопределяет заголовокConnection
при отправке запросов (мы не тестировали это решение всесторонне, так как мы можем настроить конфигурацию Apache)
Ответ 3
Для моего, Resetting content and settings
симулятора работает.
В reset симулятор выполнит следующие шаги:
iOS Simulator → reset Содержание и настройки → Нажмите reset (на предупреждение, которое придет)
Ответ 4
Время выполнения симулятора iOS 8.0 имеет ошибку, согласно которой, если ваша сетевая конфигурация изменяется при загрузке имитируемого устройства, API-интерфейсы более высокого уровня (например, CFNetwork) в моделируемой среде выполнения будут считать, что он потерял сетевое подключение. В настоящее время рекомендуемым решением является просто перезагрузка имитируемого устройства при изменении конфигурации сети.
Если вы столкнулись с этой проблемой, добавьте дополнительные дублированные радары в http://bugreport.apple.com, чтобы получить повышенный приоритет.
Если вы видите эту проблему, не изменив конфигурации сети, то это не известная ошибка, и вы обязательно должны указать радар, указав, что проблема не является известной ошибкой, измененной конфигурацией сети.
Ответ 5
Также есть проблема с бета 5 и AFNetworking 1.3 при работе на симуляторе iOS 8, которая приводит к ошибке соединения:
Domain = NSURLErrorDomain Code = -1005 «Сетевое соединение потеряно.»
Тот же самый код прекрасно работает на симуляторах iOS 7 и 7.1, и мой прокси-сервер отладки показывает, что сбой происходит до того, как на самом деле попытка подключения (т.е. Запросы не регистрируются).
Я отследил сбой NSURLConnection и сообщил об ошибке в Apple. Смотрите строку 5 на прикрепленном изображении:
.
Изменение использования https
позволяет подключаться к симуляторам iOS 8, хотя и с периодическими ошибками.
Проблема все еще присутствует в Xcode 6.01 (gm).
Ответ 6
для меня проблема заключалась в том, чтобы перезапустить симулятор и reset содержимое и настройки.
Ответ 7
Открытие Чарльза решило проблему для меня, что кажется очень странным…
Charles — это прокси-сервер HTTP/HTTP-монитор/обратный прокси-сервер, который позволяет разработчику просматривать весь трафик HTTP и SSL/HTTPS между их компьютером и Интернетом. Это включает в себя запросы, ответы и заголовки HTTP (которые содержат файлы cookie и информацию о кэшировании).
Ответ 8
Я столкнулся с этой проблемой при использовании Alamofire. Моя ошибка заключалась в том, что я отправлял пустой словарь [:]
для параметров по запросу GET
, а не по отправке параметров nil
.
Надеюсь, это поможет!
Ответ 9
См. комментарий pjebs от 5 января в Github.
Метод1:
if (error.code == -1005)
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
dispatch_group_t downloadGroup = dispatch_group_create();
dispatch_group_enter(downloadGroup);
dispatch_group_wait(downloadGroup, dispatch_time(DISPATCH_TIME_NOW, 5000000000)); // Wait 5 seconds before trying again.
dispatch_group_leave(downloadGroup);
dispatch_async(dispatch_get_main_queue(), ^{
//Main Queue stuff here
[self redoRequest]; //Redo the function that made the Request.
});
});
return;
}
Также некоторые предлагают повторно подключиться к сайту,
то есть. Сбой запроса POST TWICE
Решение. Используйте метод для подключения к сайту, return (id), если сетевое соединение было потеряно, верните его, чтобы использовать тот же метод.
Метод 2
-(id) connectionSitePost:(NSString *) postSender Url:(NSString *) URL {
// here set NSMutableURLRequest => Request
NSHTTPURLResponse *UrlResponse = nil;
NSData *ResponseData = [[NSData alloc] init];
ResponseData = [NSURLConnection sendSynchronousRequest:Request returningResponse:&UrlResponse error:&ErrorReturn];
if ([UrlResponse statusCode] != 200) {
if ([UrlResponse statusCode] == 0) {
/**** here re-use method ****/
return [self connectionSitePost: postSender Url: URL];
}
} else {
return ResponseData;
}
}
Ответ 10
Я тоже получал эту ошибку, но на реальных устройствах, а не на симуляторе. Мы заметили ошибку при доступе к нашему серверу heroku на HTTPS (сервер gunicorn) и сделали POSTS с большими bodys (что-то более 64Kb). Мы используем HTTP Basic Auth для аутентификации и заметили, что ошибка была решена НЕ используя метод делегата didReceiveChallenge:
на NSURLSession, а скорее выпекаем в аутентификации в исходный заголовок запроса, добавив Authentiation: Basic <Base64Encoded UserName:Password>
. Это предотвращает необходимость 401 для запуска сообщения делегата didReceiveChallenge:
, а последующее сетевое соединение потеряно.
Ответ 11
У меня была такая же проблема. Решение было простым, я установил HTTPBody
, но не установил HTTPMethod
в POST
. После исправления все было в порядке.
Ответ 12
У меня такая же проблема. Я не знаю, как AFNetworking реализует запрос https, но причина для меня — проблема с кешем NSURLSession.
После отслеживания моего приложения из safari и последующей отправки запроса http появится сообщение «Ошибка загрузки http 1005». Если я перестану использовать "[NSURLSession sharedSession]"
, но использовать настраиваемый экземпляр NSURLSession для вызова метода «dataTaskWithRequest:» следующим образом, проблема будет решена.
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
config.URLCache = nil;
self.session = [NSURLSession sessionWithConfiguration:config];
Просто не забудьте установить config.URLCache = nil;
,
Ответ 13
Мне пришлось выйти из XCode, удалить содержимое папки DerivedData (~/Library/Developer/Xcode/DerivedData или /Library/Developer/Xcode/DerivedData ) и выйти из симулятора, чтобы сделать эту работу.
Ответ 14
У меня тоже есть эта проблема, работающая на устройстве iOS 8.
Здесь подробно описано и, похоже, это случай, когда iOS пытается использовать соединения, которые уже были отключены.
Моя проблема не совпадает с проблемой Keep-Alive, описанной в этой ссылке, однако, похоже, это тот же конечный результат.
Я исправил свою проблему, запустив рекурсивный блок всякий раз, когда получаю сообщение об ошибке -1005, и это приводит к тому, что соединение в конечном итоге проходит, хотя иногда рекурсия может зацикливаться на 100 раз, прежде чем соединение будет работать, однако оно добавляет просто второй — во время выполнения, и я уверен, что это всего лишь время, когда отладчик должен распечатать NSLog для меня.
Вот как я запускаю рекурсивный блок с AFNetworking:
Добавьте этот код в файл класса подключения
// From Mike Ash recursive block fixed-point-combinator strategy https://gist.github.com/1254684
dispatch_block_t recursiveBlockVehicle(void (^block)(dispatch_block_t recurse))
{
// assuming ARC, so no explicit copy
return ^{ block(recursiveBlockVehicle(block)); };
}
typedef void (^OneParameterBlock)(id parameter);
OneParameterBlock recursiveOneParameterBlockVehicle(void (^block)(OneParameterBlock recurse, id parameter))
{
return ^(id parameter){ block(recursiveOneParameterBlockVehicle(block), parameter); };
}
Затем использовать его нравится это:
+ (void)runOperationWithURLPath:(NSString *)urlPath
andStringDataToSend:(NSString *)stringData
withTimeOut:(NSString *)timeOut
completionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
OneParameterBlock run = recursiveOneParameterBlockVehicle(^(OneParameterBlock recurse, id parameter) {
// Put the request operation here that you want to keep trying
NSNumber *offset = parameter;
NSLog(@"--------------- Attempt number: %@ ---------------", offset);
MyAFHTTPRequestOperation *operation =
[[MyAFHTTPRequestOperation alloc] initWithURLPath:urlPath
andStringDataToSend:stringData
withTimeOut:timeOut];
[operation setCompletionBlockWithSuccess:
^(AFHTTPRequestOperation *operation, id responseObject) {
success(operation, responseObject);
}
failure:^(AFHTTPRequestOperation *operation2, NSError *error) {
if (error.code == -1005) {
if (offset.intValue >= numberOfRetryAttempts) {
// Tried too many times, so fail
NSLog(@"Error during connection: %@",error.description);
failure(operation2, error);
} else {
// Failed because of an iOS bug using timed out connections, so try again
recurse(@(offset.intValue+1));
}
} else {
NSLog(@"Error during connection: %@",error.description);
failure(operation2, error);
}
}];
[[NSOperationQueue mainQueue] addOperation:operation];
});
run(@0);
}
Вы увидите, что я использую подкласс AFHTTPRequestOperation
, но добавляю свой собственный код запроса. Важной частью является вызов recurse(@offset.intValue+1));
для повторного вызова блока.
Ответ 15
Я получал ошибку на устройстве iOS 7, когда я использовал бета-версию Xcode 6.2.
Переход с бета-версии Xcode 6.2 на 6.1.1 исправил проблему, по крайней мере, на устройстве iOS 7.
Ответ 16
Если проблема возникает на устройстве, проверьте, проходит ли трафик через прокси (Настройки > Wi-Fi > (информация) > HTTP-прокси). У меня была настройка устройства для использования с Чарльзом, но я забыл про прокси. Кажется, что без того, чтобы Чарльз действительно выполнял эту ошибку.
Ответ 17
Если кто-то получает эту ошибку при загрузке файлов на серверный сервер, убедитесь, что на принимающем сервере установлен максимальный размер содержимого, допустимый для вашего носителя. В моем случае для NGINX требуется более высокий client_max_body_size
. NGINX отклонил запрос до того, как будет выполнена загрузка, поэтому код ошибки не вернулся.
Ответ 18
На 2017-01-25
Apple выпустила технический Q & A относительно этой ошибки:
Технические вопросы и ответы Apple QA1941
Обработка ошибок «сетевое соединение потеряно»
A: NSURLErrorNetworkConnectionLost является ошибкой -1005 в домене ошибок NSURLErrorDomain и отображается для пользователей как «Сетевое соединение было потеряно». Эта ошибка означает, что базовое TCP-соединение, несущее HTTP-запрос, отключено во время выполнения HTTP-запроса (дополнительную информацию об этом см. Ниже). В некоторых случаях NSURLSession может повторять такие запросы автоматически (в частности, если запрос идемпотентен), но в других случаях, которые не допускаются стандартами HTTP.
https://developer.apple.com/library/archive/qa/qa1941/_index.html#//apple_ref/doc/uid/DTS40017602
Ответ 19
Получил проблему в течение нескольких месяцев и, наконец, обнаружил, что когда мы отключили DNSSEC в нашем домене api, все было в порядке:
Ответ 20
Я подключался через VPN. Отключение VPN решило проблему.
Ответ 21
Я ударил эту ошибку при передаче NSURLRequest в NSURLSession без установки запроса HTTPMethod.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlComponents.URL];
Ошибка домена = NSURLErrorDomain Code = -1005 «Сетевое соединение было потеряно».
Добавьте HTTPMethod
, хотя соединение прекрасно работает
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlComponents.URL];
[request setHTTPMethod:@"PUT"];
Ответ 22
Проверьте, можете ли вы запросить другие приложения (например, сафари). Если это не может быть что-то на вашем компьютере. В моем случае у меня была эта проблема с Avast Antivirus, которая блокировала мой запрос симуляторов (не спрашивайте меня почему).
Ответ 23
Перезапуск компьютера исправил проблему для меня с помощью Xcode9.1. Я перезапустил симулятор и Xcode, он не работает.
Ответ 24
У меня была эта проблема по следующей причине.
TL;DR: Проверьте, отправляется ли запрос GET
, который должен отправлять параметры на URL, а не в свойстве NSURLRequest HTTBody
.
=============================================== ===
Я установил сетевую абстракцию в своем приложении, и он работал очень хорошо для всех моих запросов.
Я добавил новый запрос на другой веб-сервис (не мой), и он начал бросать мне эту ошибку.
Я пошел на детскую площадку и начал с нуля строить строгий запрос, и это сработало. Поэтому я начал приближаться к своей абстракции, пока не нашел причину.
У моей реализации абстракции была ошибка:
Я отправил запрос, который должен был отправить параметры, закодированные в URL-адресе, и я также заполнил свойство NSURLRequest HTTBody
параметрами запроса.
Как только я удалил HTTPBody
, он сработал.
Ответ 25
Я получал эту ошибку и также замечаю, что приложение Postman также падало, но работало в приложении Advanced Rest Client (ARC) и работало в Android.
Поэтому мне пришлось установить Charles для отладки сообщения, и я замечаю, что код ответа был -1.
Проблема заключалась в том, что программист REST забыл вернуть код ответа 200.
Я надеюсь, что это поможет другим разработчикам.
Ответ 26
Всякий раз, когда появляется ошибка -1005, необходимо снова вызвать API.
AFHTTPRequestOperationManager *manager =
[AFHTTPRequestOperationManager manager];
[manager setSecurityPolicy:policy];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:<example-url>
parameters:<parameteres>
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Success: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
if (error.code == -1005) {
// Call method again...
}
}];
Вам нужно добавить свой код, чтобы снова вызвать функцию. Убедитесь, что вы вызывали метод один раз, иначе вызовите рекурсивный цикл.
Ответ 27
Я столкнулся с той же проблемой, я включил Network Link Conditioner для медленного тестирования сети для приложения. Это создавало эту ошибку несколько раз. Когда я отключил ее в Settings > Developer > Network Link Conditioner
, это решило мою проблему.
Надеюсь, это поможет кому-то.
Ответ 28
Я столкнулся с той же проблемой, когда звонил, используя сервер своей компании из приложения iOS 12 с физического устройства. Проблема заключалась в том, что жесткий диск сервера был заполнен. Освобождение места на сервере решило проблему.
Я обнаружил ту же ошибку в другой ситуации, которую я считаю из-за тайм-аута, который нельзя параметризировать через стандартный сетевой API, предоставляемый Apple (URLSession.timeoutIntervalForRequest
и URLSession.timeoutIntervalForResource
). Даже там.. сделал ответ сервера быстрее решил проблему
Ответ 29
В моем случае это было связано с тем, что я подключался к HTTP, и он работал по протоколу HTTPS.
Ответ 30
Это может быть проблемой параметра, который вы передаете в тело запроса. Я также столкнулся с той же проблемой. Но потом я наткнулся на ответ CMash здесь fooobar.com/info/127920/…, и я изменил свой параметр, и он работает.
Проблема в параметре, который я передавал, касается String Encoding
.
Надеюсь это поможет.
Looks like no one’s replied in a while. To start the conversation again, simply
ask a new question.
I am having trouble moving photos out of the new Photos app. I tried dragging an dropping, I tried dragging to PS Elements and then I tried exporting to a file on my desktop. Each time I get this message. It seems I cannot export … any suggestions? Many thanks!!
MacBook
Pro,
Mac OS X (10.6.7)
Posted on Apr 22, 2015 2:52 PM
3 replies
Dec 11, 2015 8:55 PM in response to Kahshe
🙂If draggin photos from iphoto to desktop is not working, Try a different way…..This is what worked for me..Select the image you want, then go to File > Export > Export 1 File. after you follow the prompts place a folder or location where you want this image to save to. Hope this helps as it did for me. ℹ
Jan 17, 2016 3:06 PM in response to Vic van Dijk
I’m having this problem also. Quitting did not work for me, but a full shut down and restart did. Weird! 😕
Error 1005 in Photos
Are you bothered by your Apple Family share error 1005?
The full error is “Something went wrong” followed by “The operation couldn’t be completed. (com.apple.family.error error-1005)“.
Then you have come to the right place so sit tight and keep reading.
Apple Family share is a feature in apple devices through which you can share various apps in your device with up to 5 members of your family.
It is a great feature through which you can enjoy the same things as a family.
However, an error can completely destroy your plan of doing so.
That is why this guide will help you to understand the reasons why the error is coming to your device and how you will be able to fix it.
Reasons For Apple Family Error 1005
There can be various reasons why your Apple device is showing the error 1005 when you are trying to access family share.

These reasons are listed below for your better understanding of the issue.
- The device does not have the requirement for the feature of Family sharing and in that case, you will not be able to access the feature from that device.
- Account setting is wrong for family sharing.
- You are using different accounts for your media and purchase.
- The shared feature services are disabled on the devices.
- You have hidden the purchase and until you unhide it, you can not share it with other people.
- The app that you are trying to share is not shareable as you can only share apps that are shareable with your family members and not all apps.
- The person that you are trying to share with has already subscribed to a trial service from an app, in that case, you can not share your app with that person as they already have a subscription to that app.
- The device needs an update as it is using an older OS which is preventing the device from functioning properly.
Fixes For Apple Family Error Code 1005
When you have encountered the error code 1005 while trying to share an app to your family member through your Apple Device, it can become quite a frustrating experience for you.
In the previous secretion of our guides, you have identified the issues that can be the reasons for the error code 1005 in your Apple device.
In this section, we will be showing you all the solutions that you can try to stop the issue from arising.
1. Log Out And Log In Again With Your Apple ID
The first thing that you should try is to log out of your Apple ID and then log in again after sometime.
If it is a glitch then this will be able to solve the issue.
2. Check The Family Sharing Setting
You should also check the family sharing setting and make sure that it is enabled properly which will let you share the media and apps with other family members.
To do that just follow the steps below and you will be able to easily do so.
For Mac
Step 1: Go to Settings from the Apple menu.
Step 2: Open Family then go to Purchase.
Step 3: Check your Apple ID details and then open the App Store.
Step 4: Go to Store and then Account.
Step 5: Click on Settings and make sure that you are using the same ID for both purchasing and sharing.
For iPhone and iPad
Step 1: Go to Settings.
Step 2: Then go to Family.
Step 3: Tap on your name and check your Apple ID.
Step 4: Now select Purchases.
Step 5: Check the ID that you are using for purchase by going to Apple ID for Purchase.
3. Check Whether The App Is Enabled For Family Sharing
You should make sure that the app is enabled for family sharing before you try to share it with your family.
Follow the below mentioned steps to check it.
Step 1: First open the App store from your iOS device.
Step 2: Search for the app and open it.
Step 3: Go to the Support Section and check whether it is enabled for family sharing.
4. Log Out And Then Again Login In Media Purchase
You can also sign out of the Media and Purchase and then again sign in with your Apple ID. To do that follow the below steps.
For Mac
Step 1: Go to the App Store.
Step 2: Open Store.
Step 3: Click on Sign Out.
Step 4: Now, Sign In again.
For iPhone and iPad
Step 1: Go to Settings.
Step 2: Tap on your Profile.
Step 3: Go to Media and Purchases.
Step 4: Tap on Not (Name) and then log in again.
5. Enable Your Family Sharing Features
You should also check whether family sharing is enabled on your Apple device.
If it is not enabled you will keep getting the error code and will not be able to share the apps or media with your other family members.
To check the settings please follow the steps given below.
Step 1: Open Settings on your iOS device.
Step 2: Click on the profile icon.
Step 3: Select Family sharing from the options.
Step 4: Navigate to Share features.
Step 5: Now toggle on all the options in there.
6. Unhide Your Purchase
Another reason why you might be seeing the error 1005 might be due to the fact that you have hidden your purchase.
In that case unhiding it would solve the issue.
To do that follow the steps below.
Step 1: First, open the App Store.
Step 2: Click on your name from the sidebar.
Step 3: Now choose Account settings or View information.
Step 4: Sign in by using your Apple ID.
Step 5: Select Manage under Hidden items/Hidden Purchases.
Step 6: Navigate to the app that you want to unhide and select Unhide.
Step 7: Click Done and your app is now unhidden.
It will appear among all the other apps on your device.
For iOS devices
Step 1: Open App Store.
Step 2: Tap on your Profile button.
Step 3: Tap on your Apple ID.
Step 4: Now, Sign in with your Apple ID.
Step 5: Tap on Hidden Purchases.
Step 6: Navigate and find the app that you want to unhide and then tap on Unhide and you are done.
7. Remove And Re-add The Family Member
You can also remove your family member from your device and then re-add them and check whether that solves the issue of error code 1005.
Step 1: Open Settings from your iOS device.
Step 2: Now, tap on Family sharing.
Step 3: Choose the member that you want to remove from the list and then press Remove.
Step 4: You can tap on Add member after this and send an invitation to that family member to join your device.
Note: Make sure that you do not exceed the number of family members that you can add to your Apple Device, otherwise you will get the error code 1005.
8. Update Your Software
As an alternative solution, you can try to update the device software if it is not updated.
If the error 1005 is occurring due to your device software then doing this will make the error get solved.
For Mac device
Step 1: Click on System settings.
Step 2: Now go to General.
Step 3: Open Software Update.
Step 4: Click on Update now.
For iPhone and iPad
Step 1: Go to Settings.
Step 2: Select General.
Step 3: Tap on Software Update.
Step 4: You can select Install Now or Download and Install.
Step 5: Enter the device password and install the upgrade.
9. Wait Till The Trial Period Of The App Ends
If your family member has already taken a trial subscription of the app or the media that you are trying to share with them then also you will not be able to share it with them and will be seeing the error code of 1005.
When that happens the only thing that you can do is to wait till the trial subscription of that app expires on their device and then only you will be able to share the app with them through Apple family sharing.
10. Contact The Apple Support Team
When you have tried all these solutions but still your Family sharing is not working on your device then we recommend that you get your device checked out by a professional.
In this case, it is best that you contact the Apple Support Team and communicate your problem to them, in which case they will be able to help you.
Similar Posts:
I’m trying to upload a binary file from iOS to a server on local Wifi. The uploader on the server works fine from its web page, but I can’t get it to upload from Swift. It looks to me like my request is not properly formed, but I haven’t been able to figure out what it’s missing.
Thanks for any help.
~ Nancy
Here’s my upload routine:
func uploadFile() {
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let updateURL = URL(string: ("http://" + currentBaseString + "/update"))
var request = URLRequest(url: updateURL!)
print("SETUP Upload Request: ", request)
request.httpMethod = "POST"
guard let fileURL = Bundle.main.url(forResource: "R2-0701", withExtension: "bin") else {
print("Failed to create URL for file.")
return
}
do {
let data = try Data(contentsOf: fileURL)
print("SETUP Found the data filen")
request.httpBody = data
let task = URLSession.shared.uploadTask(with: request as URLRequest, fromFile: fileURL) { data, response, error in
if error != nil {
print ("RRC Task error: (String(describing: error))")
return
}
guard let response = response as? HTTPURLResponse, (200...299).contains(response.statusCode) else {
print ("Server error")
return
}
if let mimeType = response.mimeType,
mimeType == "multipart/form-data",
let updateData = data,
let dataString = String(data: updateData, encoding: .utf8) {
print ("got data: (dataString)")
}
}
task.resume()
}
catch {
print("Error opening file: (error)")
}
}
My URL construction is fine, it works for GET requests. «R2-0701.bin» is the filename of a file added to the project.
Here’s the server HTML:
<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'>
</script>
<form method='POST' action='#' enctype='multipart/form-data' id='upload_form'>
<table cellpadding = '10' align='center''>
<tr>
<td bgcolor='AA0000' align='center' style='color:white;'>
<p font-color='white' text-size='12' >
<b>Reprogram</b>
</p>
</td>
</tr>
<tr>
<td>
<input type='file' name='update'>
</td>
</tr>
<tr>
<td align='center'>
<input type='submit' value='Update'>
</form>
</td>
</tr>
<tr>
<td align='center'>
<div id='prg'>progress: 0%</div>
</td>
</tr>
</table>
<script>
$('form').submit(function(e){
e.preventDefault();
var form = $('#upload_form')[0];
var data = new FormData(form);
$.ajax({
url: '/update',
type: 'POST',
data: data,
contentType: false,
processData:false,
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener('progress', function(evt) {
if (evt.lengthComputable) {
var per = evt.loaded / evt.total;
$('#prg').html('progress: ' + Math.round(per*100) + '%');
}
}, false);
return xhr;
},
success:function(d, s) {
console.log('success!')
},
error: function (a, b, c) {
}
});
});
</script>;
Here’s the output:
SETUP Upload Request: http://192.168.86.41/update
SETUP Found the data file
2022-07-04 17:21:52.075958-0600 RoadrunnerComfort[5034:11127394] Task <25F2EC07-30D7-4532-BD6A-D35A41716AF2>.<7> HTTP load failed, 1048855/0 bytes (error code: -1005 [4:-4])
2022-07-04 17:21:52.082677-0600 RoadrunnerComfort[5034:11127423] Task <25F2EC07-30D7-4532-BD6A-D35A41716AF2>.<7> finished with error [-1005] Error Domain=NSURLErrorDomain Code=-1005 «The network connection was lost.» UserInfo={_kCFStreamErrorCodeKey=-4, NSUnderlyingError=0x283fb49c0 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 «(null)» UserInfo={NSErrorPeerAddressKey=<CFData 0x2812ecc80 [0x22eb841b8]>{length = 16, capacity = 16, bytes = 0x10020050c0a856290000000000000000}, _kCFStreamErrorCodeKey=-4, _kCFStreamErrorDomainKey=4}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalUploadTask <25F2EC07-30D7-4532-BD6A-D35A41716AF2>.<7>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
«LocalUploadTask <25F2EC07-30D7-4532-BD6A-D35A41716AF2>.<7>»
), NSLocalizedDescription=The network connection was lost., NSErrorFailingURLStringKey=http://192.168.86.41/update, NSErrorFailingURLKey=http://192.168.86.41/update, _kCFStreamErrorDomainKey=4}
2022-07-04 17:21:52.083212-0600 RoadrunnerComfort[5034:11127396] [tcp] tcp_input [C7:2] flags=[R.] seq=3409008496, ack=2962928595, win=5744 state=LAST_ACK rcv_nxt=3409008496, snd_una=2962927159
RRC Task error: Optional(Error Domain=NSURLErrorDomain Code=-1005 «The network connection was lost.» UserInfo={_kCFStreamErrorCodeKey=-4, NSUnderlyingError=0x283fb49c0 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 «(null)» UserInfo={NSErrorPeerAddressKey=<CFData 0x2812ecc80 [0x22eb841b8]>{length = 16, capacity = 16, bytes = 0x10020050c0a856290000000000000000}, _kCFStreamErrorCodeKey=-4, _kCFStreamErrorDomainKey=4}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalUploadTask <25F2EC07-30D7-4532-BD6A-D35A41716AF2>.<7>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
«LocalUploadTask <25F2EC07-30D7-4532-BD6A-D35A41716AF2>.<7>»
), NSLocalizedDescription=The network connection was lost., NSErrorFailingURLStringKey=http://192.168.86.41/update, NSErrorFailingURLKey=http://192.168.86.41/update, _kCFStreamErrorDomainKey=4})`