gpt4 book ai didi

iphone - 使用 url 设置 UIImageView 图像

转载 作者:行者123 更新时间:2023-12-03 18:12:52 24 4
gpt4 key购买 nike

是否可以读取图像的 url 并将 UIImageView 设置到该 url 处的图像?

最佳答案

对于这样一个简单的任务,我强烈建议不要集成诸如 Three20 之类的项目,该库是一个怪物,并且启动和运行起来不是很简单。

我会推荐这种方法:

NSString *imageUrl = @"http://www.foo.com/myImage.jpg";
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:imageUrl]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
myImageView.image = [UIImage imageWithData:data];
}];

编辑 Swift 3.0

let urlString = "http://www.foo.com/myImage.jpg"
guard let url = URL(string: urlString) else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print("Failed fetching image:", error)
return
}

guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
print("Not a proper HTTPURLResponse or statusCode")
return
}

DispatchQueue.main.async {
self.myImageView.image = UIImage(data: data!)
}
}.resume()

*编辑 Swift 2.0

let request = NSURLRequest(URL: NSURL(string: urlString)!)

NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) -> Void in

if error != nil {
print("Failed to load image for url: \(urlString), error: \(error?.description)")
return
}

guard let httpResponse = response as? NSHTTPURLResponse else {
print("Not an NSHTTPURLResponse from loading url: \(urlString)")
return
}

if httpResponse.statusCode != 200 {
print("Bad response statusCode: \(httpResponse.statusCode) while loading url: \(urlString)")
return
}

dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.myImageView.image = UIImage(data: data!)
})

}.resume()

关于iphone - 使用 url 设置 UIImageView 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4962561/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com