Czy mogę załadować interfejs użytkownika z adresu URL?
Mam adres URL dla obrazu (dostałem go z UIImagePickerController), ale nie mam już obrazu w pamięci(adres URL został zapisany z poprzedniego uruchomienia aplikacji). Czy mogę ponownie załadować interfejs z adresu URL?
Widzę, że UIImage ma imageWithContentsOfFile: ale mam URL. Czy mogę użyć nsdata ' s dataWithContentsOfURL: aby odczytać adres URL?
EDIT1
Na podstawie odpowiedzi @ Daniel próbowałem poniższego kodu, ale nie działa...
NSLog(@"%s %@", __PRETTY_FUNCTION__, photoURL);
if (photoURL) {
NSURL* aURL = [NSURL URLWithString:photoURL];
NSData* data = [[NSData alloc] initWithContentsOfURL:aURL];
self.photoImage = [UIImage imageWithData:data];
[data release];
}
Kiedy go uruchomiłem konsola pokazuje:
-[PhotoBox willMoveToWindow:] file://localhost/Users/gary/Library/Application%20Support/iPhone%20Simulator/3.2/Media/DCIM/100APPLE/IMG_0004.JPG
*** -[NSURL length]: unrecognized selector sent to instance 0x536fbe0
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSURL length]: unrecognized selector sent to instance 0x536fbe0'
Patrząc na stos wywołań, wywołuję URLWithString, który wywołuje URLWithString:relativeToURL:, następnie Initwithstring: relativeToURL:, następnie _CFStringIsLegalURLString, następnie CFStringGetLength, następnie forwarding_prep_0, następnie forwarding , następnie- [NSObject doesNotRecognizeSelector].
Jakieś pomysły, dlaczego mój NSString (adres photourla to 0x536fbe0)nie odpowiada na długość? Dlaczego pisze, że nie odpowiada na -[długość NSURL]? Prawda? wiesz, że param to NSString, a nie NSURL?
EDIT2
OK, jedynym problemem z kodem jest konwersja ciągu na URL. Jeśli zakoduję ciąg, Wszystko inne działa dobrze. Więc coś jest nie tak z moim Nsstringiem i jeśli nie mogę tego rozgryźć, myślę, że powinno to przejść jako inne pytanie. Po włożeniu tej linii (wkleiłem ścieżkę z dziennika konsoli powyżej) działa dobrze:
photoURL = @"file://localhost/Users/gary/Library/Application%20Support/iPhone%20Simulator/3.2/Media/DCIM/100APPLE/IMG_0004.JPG";
10 answers
Możesz to zrobić w ten sposób (synchronicznie, ale kompaktowo):
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:MyURL]]];
Znacznie lepszym podejściem jest użycie LazyTableImages firmy Apple do zachowania interaktywności.Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-23 09:37:50
Możesz spróbować SDWebImage , zapewnia:
- Ładowanie asynchroniczne
- buforowanie do użytku offline
- Umieść obrazek posiadacza, aby pojawił się podczas wczytywania
- działa dobrze z UITableView
Szybki przykład:
[cell.imageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-03-01 11:42:41
Pobierz DLImageLoader i spróbuj wykonać folowing code
[DLImageLoader loadImageFromURL:imageURL
completed:^(NSError *error, NSData *imgData) {
imageView.image = [UIImage imageWithData:imgData];
[imageView setContentMode:UIViewContentModeCenter];
}];
Kolejny typowy przykład użycia Dllimageloader, który może komuś pomóc...
PFObject *aFacebookUser = [self.fbFriends objectAtIndex:thisRow];
NSString *facebookImageURL = [NSString stringWithFormat:
@"http://graph.facebook.com/%@/picture?type=large",
[aFacebookUser objectForKey:@"id"] ];
__weak UIImageView *loadMe = self.userSmallAvatarImage;
// ~~note~~ you my, but usually DO NOT, want a weak ref
[DLImageLoader loadImageFromURL:facebookImageURL
completed:^(NSError *error, NSData *imgData)
{
if ( loadMe == nil ) return;
if (error == nil)
{
UIImage *image = [UIImage imageWithData:imgData];
image = [image ourImageScaler];
loadMe.image = image;
}
else
{
// an error when loading the image from the net
}
}];
Jak wspomniałem powyżej kolejną świetną biblioteką do rozważenia w dzisiejszych czasach jest Haneke (niestety nie jest tak lekka).
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-09 10:32:51
I wersja swift:
let url = NSURL.URLWithString("http://live-wallpaper.net/iphone/img/app/i/p/iphone-4s-wallpapers-mobile-backgrounds-dark_2466f886de3472ef1fa968033f1da3e1_raw_1087fae1932cec8837695934b7eb1250_raw.jpg");
var err: NSError?
var imageData :NSData = NSData.dataWithContentsOfURL(url,options: NSDataReadingOptions.DataReadingMappedIfSafe, error: &err)
var bgImage = UIImage(data:imageData)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-21 21:29:36
Wypróbuj ten kod, możesz ustawić ładowanie obrazu za pomocą niego, aby użytkownicy wiedzieli, że Twoja aplikacja ładuje obraz z adresu url:
UIImageView *yourImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"loading.png"]];
[yourImageView setContentMode:UIViewContentModeScaleAspectFit];
//Request image data from the URL:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://yourdomain.com/yourimg.png"]];
dispatch_async(dispatch_get_main_queue(), ^{
if (imgData)
{
//Load the data into an UIImage:
UIImage *image = [UIImage imageWithData:imgData];
//Check if your image loaded successfully:
if (image)
{
yourImageView.image = image;
}
else
{
//Failed to load the data into an UIImage:
yourImageView.image = [UIImage imageNamed:@"no-data-image.png"];
}
}
else
{
//Failed to get the image data:
yourImageView.image = [UIImage imageNamed:@"no-data-image.png"];
}
});
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-13 15:45:30
Sprawdź AsyncImageView
dostarczone przez tutaj . Jakiś dobry przykładowy kod, a może nawet być użyteczny "po wyjęciu z pudełka" dla Ciebie.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-05-07 03:05:40
AFNetworking zapewnia asynchroniczne ładowanie obrazu do interfejsu UIImageView z obsługą funkcji zastępczych. Obsługuje również sieć asynchroniczną do pracy z interfejsami API w ogóle.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-02-08 15:00:09
Jeśli jesteś naprawdę , absolutnie pozytywnie jesteś pewien, że nsurl jest adresem URL pliku, tzn. {[1] } ma gwarancję powrotu true w Twoim przypadku, możesz po prostu użyć:
[UIImage imageWithContentsOfFile:url.path]
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-26 16:00:28
Sposób użycia rozszerzenia Swift do UIImageView
(Kod źródłowy tutaj):
Tworzenie właściwości obliczeniowej dla skojarzonego UIActivityIndicatorView
import Foundation
import UIKit
import ObjectiveC
private var activityIndicatorAssociationKey: UInt8 = 0
extension UIImageView {
//Associated Object as Computed Property
var activityIndicator: UIActivityIndicatorView! {
get {
return objc_getAssociatedObject(self, &activityIndicatorAssociationKey) as? UIActivityIndicatorView
}
set(newValue) {
objc_setAssociatedObject(self, &activityIndicatorAssociationKey, newValue, UInt(OBJC_ASSOCIATION_RETAIN))
}
}
private func ensureActivityIndicatorIsAnimating() {
if (self.activityIndicator == nil) {
self.activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
self.activityIndicator.hidesWhenStopped = true
let size = self.frame.size;
self.activityIndicator.center = CGPoint(x: size.width/2, y: size.height/2);
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
self.addSubview(self.activityIndicator)
self.activityIndicator.startAnimating()
})
}
}
Custom Initializer and Setter
convenience init(URL: NSURL, errorImage: UIImage? = nil) {
self.init()
self.setImageFromURL(URL)
}
func setImageFromURL(URL: NSURL, errorImage: UIImage? = nil) {
self.ensureActivityIndicatorIsAnimating()
let downloadTask = NSURLSession.sharedSession().dataTaskWithURL(URL) {(data, response, error) in
if (error == nil) {
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
self.activityIndicator.stopAnimating()
self.image = UIImage(data: data)
})
}
else {
self.image = errorImage
}
}
downloadTask.resume()
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-19 16:56:33
Upewnij się, że włączysz te ustawienia z iOS 9:
Ustawienia bezpieczeństwa transportu aplikacji W Info.plist aby zapewnić ładowanie obrazu z adresu URL, aby umożliwić pobranie obrazu i ustawienie go.
I napisz ten kod:
NSURL *url = [[NSURL alloc]initWithString:@"https://www.google.co.in/"];
NSData *data =[NSData dataWithContentsOfURL:url];
quickViewImage.image = [UIImage imageWithData:data];
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-09 16:41:51