Image with url iphone

iOS: load an image from url

I need to load an image from a url and set it inside an UIImageView; the problem is that I don’t know the exact size of the image, then how can I show the image correctly?

9 Answers 9

Just use the size property of UIImage, for example:

In swift regarding using optionals:

The main thread must be always remain free so it serves the user interface and user interactions.

To download Asynchronous image with Kingfisher library you can follow this step,url :https://github.com/onevcat/Kingfisher:

You can also download image with default URLSession.shared.dataTask

SWIFT 5.0 + fetch on background

One common mistake in displaying an image downloaded from json or a url is the problem of queues. ALL UI-related things need to be done in the main queue, so if you forgot this, even perfect code (above answers are good) won’t display your image on occasion. To call the mainQueue, use code like this, and note that calling main queue might need to be done seperately in the called imageDisplay function:

Swift safe code version:

Be in mind that this code is not thread safe, you should run it on a background thread. For example:

If you prefer you can even move it to an UIImage extension:

Источник

I’ll try to explain my doubt, but please consider that I’m new to Xcode and I have a lot of things to learn. In my iPhone App I’d like that when I touch an image, the app redirects to an external web URL. Is it possible to do it directly from the Storyboard? I didn’t used a ViewController, so I can’t call the function.

Thank you in advance.

3 Answers 3

  1. Add a button to your Storyboard.
  2. Set the button as custom and assign the image as the background of the button.
  3. Launch the Safari browser with your URL from the IBAction of your button.

Here is how to launch the Safari browser with your URL (got this code from here) :

Easier option is, that I would suggest is use a UIButton with required image, and provide button action method which opens your web URL.

If you want to go with UIImageView only, then add tap gesture recognizer over that, which gives you tap event. Over that event method, you can call your web URL.

Here is a link which provide detail explanation about gesture recognizer.

Hope this will help you.

You can use a UIButton instead of a UIImage and assign the image to the Button in your InterfaceBuilder.

In the IBAction Outlet which must be connected to your UIButton you must then write the following Code:

Since you have to link your storyboard Outlets to a Viewcontroller to handle the UIButton taps, you must use a ViewController.

I also strongly recommend to read about the basics of the MVC Pattern Apple uses in his Apps. I’ve never seen someone to write an app without using Viewcontrollers. They usually contain all your App Logic.

Источник

Как получить ссылку на фото или видео из iPhone (iPad) и поделиться ей, не устанавливая никаких приложений

Стандартная функция Общие альбомы на iOS, iPadOS и macOS предлагает владельцам iPhone, iPad и Mac легко делиться своими фото и видео с любыми пользователями (в том числе Android, Windows и т.д.). В этом случае, на базе сайта icloud.com создается фото-вебсайт в из отдельных фото и видео или же целых альбомов.

Читайте также:  Daemons iphone что это

Для чего это нужно?

Владелец такого фото-вебсайта может пригласить других пользователей дополнять новыми материалами интернет-альбом и делиться им со всеми или избранными контактами.

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

Данная возможность может оказаться весьма полезной в путешествиях или деловых поездках – отснятый материал можно будет автоматически отправлять определенному кругу лиц или выложить в открытый доступ.

Полученную ссылку на Общий альбом можно просматривать в браузере любого компьютера, планшета или смартфона.

Как создать Общий альбом фото (видео) в режиме web-сайта с URL-ссылками на iPhone или iPad

1. На iPhone или iPad откройте приложение Настройки и перейдите в раздел Фото.

2. Активируйте переключатель Общие альбомы.

3. Откройте раздел Медиатека приложения Фото или готовый альбом, созданный ранее (инструкция) и нажмите кнопку Выбрать в правом верхнем углу, выберите фото (видео) для добавления в «интернет-альбом» и нажмите кнопку Поделиться.

4. Выберите параметр В общий доступ.

5. Введите название альбома, например: «Поездка в Испанию» или «Свадьба Антона и Татьяны» (в нашем случае Яблык) и нажмите кнопку Далее в правом верхнем углу.

6. Введите адреса электронной почты (не обязательно) тех пользователей, которых вы хотите пригласить в Общий альбом (им придет приглашение на e-mail) или оставьте это поле пустым, для того чтобы создать «интернет-альбом» с открытым доступом (в этом случае ваши фото и видео смогут увидеть только те, кто получит от вас ссылку на альбом).

7. Введите комментарий к фото или видео (необязательно) и нажмите кнопку Опубликовать.

8. Перейдите в приложении Фото во вкладку Альбомы.

9. В разделе Общие альбомы вы увидите все созданные альбомы с доступом. Выберите интересующий.

10. Для настройки доступа нажмите иконку значка Люди в правом верхнем углу.

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

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

— для того чтобы сделать альбом доступным в Интернете по ссылке, активируйте переключатель Открытый веб-сайт. С другой стороны, выключите этот переключатель, в случае если необходимо убрать альбом из открытого доступа.

— для того чтобы поделиться ссылкой на Открытый веб-сайт, нажмите кнопку «Поделиться ссылкой», в появившемся всплывающем меню выберите Скопировать.

— для того чтобы включить уведомления при добавлении новых фото и видео от подписчиков альбома, включите переключатель Уведомления.

— для удаления альбома нажмите в самом низу кнопку-ссылку «Удалить общий альбом».

11. Для добавления новых фото и видео в выбранные альбом, воспользуйтесь кнопкой «+».

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

Мобильная версия Общего альбома:

Компьютерная версия Общего альбома:

Как создать Общий альбом фото (видео) в режиме web-сайта с URL-ссылками на Mac

1. Откройте раздел Медиатека приложения Фото или готовый альбом, созданный ранее и выделите фото (видео) для добавления в «интернет-альбом».

О том, как выделять фото (файлы), находящиеся не рядом в списке на Mac, мы рассказывали в этом материале.

2. Нажмите кнопку «Поделиться» на панели инструментов или перейдите по пути Файл → Поделиться в строке меню.

3. Выберите «Общие альбомы». Вы заметите в верхней части небольшого окна число фотографий в альбоме, которым вы будете делиться.

4. Выберите «Новый общий альбом».

5. Дайте вашему альбому имя. Вы можете добавить людей, чтобы поделиться с ними сразу или отложить этот шаг на потом. По желанию вы можете добавлять комментарии к альбому.

6. Щелкните «Создать».

После этого вы должны увидеть свой недавно созданный общий альбом на боковой панели в разделе «Общие альбомы».

7. Для настройки доступа нажмите иконку значка Люди на верхней панели.

Для получения ссылки на Общий альбом, установите галочку напротив пункта Открытый веб-сайт.

Заключение

Создавая альбом в «Фото», вы можете и не знать, что в будущем захотите поделиться своими снимками. Это могут быть фотографии с недавнего праздника или другого торжества, или просто фотографии домашних животных или ваших домашних проектов.

Читайте также:  Актуальные модели айфонов 2021

А делаете ли вы ваши альбомы общими? Предпочитаете ли создавать их изначально такими или просто при необходимости воспользуетесь нашим советом?

Источник

how to store url image in cache memory then display in imageview in iphone

I directly open URL image in Imageview but i want to store the images in cache memory for future reference. help me to solve my problem..

Thanks in advance

3 Answers 3

You can use SDWebImage which uses image caching.

This library provides a category for UIImageVIew with support for remote images coming from the web.

An UIImageView category adding web image and cache management to the Cocoa Touch framework

An asynchronous image downloader

An asynchronous memory + disk image caching with automatic cache expiration handling

A background image decompression

A guarantee that the same URL won’t be downloaded several times

A guarantee that bogus URLs won’t be retried again and again

A guarantee that main thread will never be blocked

Performances! Use GCD and ARC

It’s a classic problem in iOS development, I write a class OnlineImageView before, which is using NSOperationQueue — Now GCD maybe better.

You wanna access an online image:

  1. First, you try to hit the image (with the key, maybe url) in the memory cache, but missed.
  2. Second, you try to find the image in the disk, missed again.
  3. Then, you should download the online image asynchronously, using GCD or some other methods.
  4. When the image is downloaded successfully, show it in the UIImageView, and cache it in the memory, write it down to the disk for future use.

Источник

Loading image in image view from a URL, using the iPhone sdk?

I’ve gone through a lot of code from the web in an attempt to load an image view via URL. Unfortunately, none of the solutions I tried has worked for me and I get very strange errors. I am getting image data, but no image from this NSData. I used the below code with a sample URL and it works, giving me the represented image. However when I switch it to use my actual URL I run into problems because it seems like it is attempting to create/return an image which is too large in size. Here is my code:

I’d appreciate any help, thanks in advance.

5 Answers 5

You can convert your response from your URL to NSData and then use

Hope this helps.

EDIT:

Also to make it work in background you should call it using a seperate thread in an asynchronous manner so that it wont block your main thread as shown below.

For large amounts of data you should consider using NSURLConnection:

This way you can keep track of the data returned from the server with:

You have stated that I have used below code with different url and it is giving image then it would be helpful if you provided the URL that you are trying to use.

Another idea to help track down the issue would be to UIWebView to verify that you are able to load the required image.

Please try the following code. i have tested it. its working fine.

THIS WILL HELP YOU GET THE IMAGE AND THE PARAGRAPH AND TITLE FROM YOUR WEBSITE!

If you want me to help you or get the second image or any help you need type in comment I will re write my code.

This is a answer quite late but I think it still might help in your future. You can go into parsing the website and that is the right way to do it but I will show you how to do it a different way, this can also be used to read xml, html, .com, anything and also, .rss so it can read RSS Feeds.
Here :

Читайте также:  Panzer glass iphone 12 pro max

This can get your first paragraph, if you request I will show you how to get the second paragraph and so on. So if you want to get money change your scanner to find $ Title would be name but if it is not tell me I will show you how to get second title or header. See this and down. I will show you how to get the html or xml from the whole website so you can see the whole code of the website and look for the about so read the website first and then read the code and you see the dogs name in the code find what it is under title tag or under header and change the code underneath to your needs read this whole post to understand everything. This below is main code of how to get info. Go to second code block to find out how to get code of your website in your Log or Console. To find your image same thing look through the NSLog and look for any image links like www.example.com/images/image.jpg or image.png or image.gif or some image extension and look at what code is initiating this like is it or there are literally 100’s of image codes in html and xml, look for the url look at the code and then use it in your scanner change the

to your code and then make sure only the url of the image is still there like keep shortening it until you have nothing except url.

you want : www.example.com/images/image.jpg

You would use the scanner below and change the

to so scan it until it is static so if you know that that part will always be the same then scan it up to there and then the second part of the scanner end it with \»

See the first code block underneath the big one? This is the part we need to change —

NSString *webString2222 = mastaString;

In our case we change this part to —

Now it has the url but the first part of the scanner always stays so use —

NSString *filteredTitle = [content2222 stringByReplacingOccurrencesOfString:@»

Then use this to download the image —

//This is your URL NSURL *URL = [NSURL URLWithString:@»URL HERE»]; //This is the data your pulling (dont change) NSData *data = [NSData dataWithContentsOfURL:URL];

Title ? Same deal change the

to a in RSS and . Image ? Same deal change the

to what ever your RSS or website uses to get a image to find But remember for both of them when you change the

` you see the link which says stringByReplacingOccurences of you have to change that as well.

out then you have to delete this and make your code like this :

Now check your log it shows your whole website html or rss code then you scroll and read it and find your image link and check the code before it and change the String Scanner to your needs which is quite awesome and you have to change the stringByReplacingOccurences of.

Like I said images are a bit tricky when you do it with this method but XML Parsing is a lot easier ONCE you learn it , lol. If you request I will show you how to do it. Tell me if your having problems looking through the html or xml and specify which website again and I will look through and I will tell you how to get everything you want. Make sure :

If you want me to show you how to do it in XML just comment. If you want me to show you how to find the second paragraph or image or title or something just comment.

IF YOU NEED ANYTHING JUST COMMENT.

Bye have fun with code I provided, anything wrong JUST COMMENT! .

Источник

Оцените статью