从 JSON 文件 swift 和 link 加载 NSURL 到 imageView
Load a NSURL from a JSON file swift and link it to an imageView
我正在尝试从 JSON 文件中获取 URL 的“路径”,并将其 link 到我项目中的 imageView。图片和路径像这样 JSON 一行
{image:"http//www.something.com", path:"http://www.godbsdahb.com" }
我设法下载并用图像填充滚动视图,但现在我想单击图像然后重定向到另一个 URL。我管理重定向,但不管理图像路径的 linking。我不知道该怎么做。
这是我目前所拥有的,它也可以工作,但是没有 link 路径和图像:
var numOfPromo = 0;
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func loadPromo() {
numOfPromo = 0;
PromoMan.sharedInstance.getAllPromoFromServer({
promotions in
for (_,promotion) in promotions {
self.downloadImage(NSURL(string: promotion.picture)!)
//The path for the promo is promotion.path
}},
onFail: { error_code, detail in Utility.log(self.dynamicType, msg: "Get All Promotions Fail, error_code: \(error_code), detail: \(detail)",
function: "viewDidLoad")})
}
//Add paths to the promtion images
func imageTapped(gesture: UIGestureRecognizer)
{
let url = NSURL(string: "http://google.com/")
UIApplication.sharedApplication().openURL(url!)
}
func downloadImage(url: NSURL){
getDataFromUrl(url) { (data, response, error) in
dispatch_async(dispatch_get_main_queue()) { () -> Void in
guard let data = data where error == nil else { return }
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(PromotionViewController.imageTapped))
let imageView = UIImageView(image: UIImage(data: data));
imageView.addGestureRecognizer(tapGesture)
imageView.userInteractionEnabled = true
imageView.frame = CGRect(x: 0,
y: Int(self.numOfPromo * 230), width: Int(self.pScrollView.frame.size.width), height: 200)
self.pScrollView.addSubview(imageView)
self.numOfPromo = self.numOfPromo + 1;
//Make sure the images will all fit into the scrollview
self.pScrollView.contentSize = CGSizeMake(self.pScrollView.frame.size.width,
CGFloat(self.numOfPromo * 230));
}
}
}
func getDataFromUrl(url:NSURL, completion: ((data: NSData?, response: NSURLResponse?, error: NSError? ) -> Void)) {
NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) in
completion(data: data, response: response, error: error)
}.resume()
}
更新
这是图像和数据的 http 调用
public func getAllPromotionsFromServer(
onSuccess: (promotions: [String: Promotion])->(),
onFail: (error_code: APIErrorCode, detail: String)->()){
let url = Config.getBaseUrl() + "/promotions"
Utility.log(self.dynamicType, msg: "Get All Promotions from Server", function: "getAllPromotionsFromServer")
APIManager.sharedInstance.get(url,params: nil,completion: { response in
//Change back to global queue
dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), {
switch response {
case APIResult.Failure(let error):
let msg = "Get Promotions Fail"
Utility.log(self.dynamicType, msg: msg, function: "getAllPromotionsFromServer")
let code = Utility.getAPIErrorCode(error)
onFail(error_code: code.error_code, detail: code.detail)
return
case APIResult.Success(let response):
if response.HTTP_Status == 200
{
let promotions = APIJSONParser.parsePromotions(response.jsonData)
print("Json response")
print(response.jsonData)
Utility.log(self.dynamicType, msg: "Get Promotions Success: no. \(promotions.count)", function: "getAllPromotionsFromServer")
onSuccess(promotions: promotions)
return
}
else{
let code = Utility.getAPIErrorCode(response)
onFail(error_code: code.error_code, detail: code.detail)
return
}
}
})
})
}
更新
新代码块:
private func loadPromotions() {
numberPromotions = 0;
PromotionManager.sharedInstance.getAllPromotionsFromServer({
promotions in
for (_,promotion) in promotions {
Utility.log(self.dynamicType, msg: promotion.picture, function: "viewDidLoad")
let p = (picture: promotion.picture, path: promotion.path)
self.promos.append(p)
self.downloadImage(NSURL(string: promotion.picture)!, index: self.promos.count)
//The path for the promo is promotion.path
}},
onFail: { error_code, detail in Utility.log(self.dynamicType, msg: "Get All Promotions Fail, error_code: \(error_code), detail: \(detail)",
function: "viewDidLoad")})
}
//Add paths to the promtion images
func imageTapped(gesture: UITapGestureRecognizer)
{
//let url = NSURL(string: "http://google.com/")
//UIApplication.sharedApplication().openURL(url!)
if let imageView = gesture as? UIImageView
{
if let url = NSURL(string: self.promos[imageView.tag].path)
{
UIApplication.sharedApplication().openURL(url)
}
}
}
func downloadImage(url: NSURL, index : Int){
getDataFromUrl(url) { (data, response, error) in
dispatch_async(dispatch_get_main_queue()) { () -> Void in
guard let data = data where error == nil else { return }
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(PromotionViewController.imageTapped))
let imageView = UIImageView(image: UIImage(data: data));
imageView.addGestureRecognizer(tapGesture)
imageView.userInteractionEnabled = true
imageView.tag = index
//get images with a space between them
//200 = no space
//230 = black space
imageView.frame = CGRect(x: 0,
y: Int(self.numberPromotions * 230), width: Int(self.promotionsScrollView.frame.size.width), height: 200)
self.promotionsScrollView.addSubview(imageView)
self.numberPromotions = self.numberPromotions + 1;
//Make sure the images will all fit into the scrollview
self.promotionsScrollView.contentSize = CGSizeMake(self.promotionsScrollView.frame.size.width,
CGFloat(self.numberPromotions * 230));
}
}
}
当你得到 promotions
对象(解析的 JSON 数据)时,你就有了图片和路径。
您已经在使用图片在滚动视图中显示图片。
现在您需要做的是告诉手势识别器转到属于该图像的特定路径。因为你有一个手势识别器来识别所有的图像(这是完美的),你需要将 "somehow" 图片与路径相关联。
为此,您可以在 class 的范围内创建一个变量,例如字典,您将在其中保存所有促销及其图片和路径。
我将使用元组数组,但您可以使用任何您想要的数据类型(字典、数组等)。
private var promos = Array<(picture: String, path: String)>()
在你的for循环中,将数据保存到刚刚创建的变量中:
for (_, promotion) in promotions {
let p = (picture: promotion.picture, path: promotion.path)
self.promos.append(p)
self.downloadImage(NSURL(string: promotion.picture)!, index: self.promos.count - 1)
}
现在你需要告诉每个 UIImageView
它属于 promos
数组的哪个索引,就在将它添加到滚动视图之前(可能是在设置 userInteractionEnabled
之后:
imageView.tag = index
并且您需要将 index
添加为函数的参数:
func downloadImage(url: NSURL, index: Int) { ... }
现在您可以从手势识别器操作访问它:
func imageTapped(gesture: UIGestureRecognizer)
{
if let imageView = gesture.view as? UIImageView {
if let url = NSURL(string: self.promos[imageView.tag].path) {
UIApplication.sharedApplication().openURL(url)
}
}
}
我建议将 gesture
更改为 sender
,因为这样会更有意义。
我正在尝试从 JSON 文件中获取 URL 的“路径”,并将其 link 到我项目中的 imageView。图片和路径像这样 JSON 一行
{image:"http//www.something.com", path:"http://www.godbsdahb.com" }
我设法下载并用图像填充滚动视图,但现在我想单击图像然后重定向到另一个 URL。我管理重定向,但不管理图像路径的 linking。我不知道该怎么做。
这是我目前所拥有的,它也可以工作,但是没有 link 路径和图像:
var numOfPromo = 0;
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func loadPromo() {
numOfPromo = 0;
PromoMan.sharedInstance.getAllPromoFromServer({
promotions in
for (_,promotion) in promotions {
self.downloadImage(NSURL(string: promotion.picture)!)
//The path for the promo is promotion.path
}},
onFail: { error_code, detail in Utility.log(self.dynamicType, msg: "Get All Promotions Fail, error_code: \(error_code), detail: \(detail)",
function: "viewDidLoad")})
}
//Add paths to the promtion images
func imageTapped(gesture: UIGestureRecognizer)
{
let url = NSURL(string: "http://google.com/")
UIApplication.sharedApplication().openURL(url!)
}
func downloadImage(url: NSURL){
getDataFromUrl(url) { (data, response, error) in
dispatch_async(dispatch_get_main_queue()) { () -> Void in
guard let data = data where error == nil else { return }
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(PromotionViewController.imageTapped))
let imageView = UIImageView(image: UIImage(data: data));
imageView.addGestureRecognizer(tapGesture)
imageView.userInteractionEnabled = true
imageView.frame = CGRect(x: 0,
y: Int(self.numOfPromo * 230), width: Int(self.pScrollView.frame.size.width), height: 200)
self.pScrollView.addSubview(imageView)
self.numOfPromo = self.numOfPromo + 1;
//Make sure the images will all fit into the scrollview
self.pScrollView.contentSize = CGSizeMake(self.pScrollView.frame.size.width,
CGFloat(self.numOfPromo * 230));
}
}
}
func getDataFromUrl(url:NSURL, completion: ((data: NSData?, response: NSURLResponse?, error: NSError? ) -> Void)) {
NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) in
completion(data: data, response: response, error: error)
}.resume()
}
更新
这是图像和数据的 http 调用
public func getAllPromotionsFromServer(
onSuccess: (promotions: [String: Promotion])->(),
onFail: (error_code: APIErrorCode, detail: String)->()){
let url = Config.getBaseUrl() + "/promotions"
Utility.log(self.dynamicType, msg: "Get All Promotions from Server", function: "getAllPromotionsFromServer")
APIManager.sharedInstance.get(url,params: nil,completion: { response in
//Change back to global queue
dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), {
switch response {
case APIResult.Failure(let error):
let msg = "Get Promotions Fail"
Utility.log(self.dynamicType, msg: msg, function: "getAllPromotionsFromServer")
let code = Utility.getAPIErrorCode(error)
onFail(error_code: code.error_code, detail: code.detail)
return
case APIResult.Success(let response):
if response.HTTP_Status == 200
{
let promotions = APIJSONParser.parsePromotions(response.jsonData)
print("Json response")
print(response.jsonData)
Utility.log(self.dynamicType, msg: "Get Promotions Success: no. \(promotions.count)", function: "getAllPromotionsFromServer")
onSuccess(promotions: promotions)
return
}
else{
let code = Utility.getAPIErrorCode(response)
onFail(error_code: code.error_code, detail: code.detail)
return
}
}
})
})
}
更新
新代码块:
private func loadPromotions() {
numberPromotions = 0;
PromotionManager.sharedInstance.getAllPromotionsFromServer({
promotions in
for (_,promotion) in promotions {
Utility.log(self.dynamicType, msg: promotion.picture, function: "viewDidLoad")
let p = (picture: promotion.picture, path: promotion.path)
self.promos.append(p)
self.downloadImage(NSURL(string: promotion.picture)!, index: self.promos.count)
//The path for the promo is promotion.path
}},
onFail: { error_code, detail in Utility.log(self.dynamicType, msg: "Get All Promotions Fail, error_code: \(error_code), detail: \(detail)",
function: "viewDidLoad")})
}
//Add paths to the promtion images
func imageTapped(gesture: UITapGestureRecognizer)
{
//let url = NSURL(string: "http://google.com/")
//UIApplication.sharedApplication().openURL(url!)
if let imageView = gesture as? UIImageView
{
if let url = NSURL(string: self.promos[imageView.tag].path)
{
UIApplication.sharedApplication().openURL(url)
}
}
}
func downloadImage(url: NSURL, index : Int){
getDataFromUrl(url) { (data, response, error) in
dispatch_async(dispatch_get_main_queue()) { () -> Void in
guard let data = data where error == nil else { return }
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(PromotionViewController.imageTapped))
let imageView = UIImageView(image: UIImage(data: data));
imageView.addGestureRecognizer(tapGesture)
imageView.userInteractionEnabled = true
imageView.tag = index
//get images with a space between them
//200 = no space
//230 = black space
imageView.frame = CGRect(x: 0,
y: Int(self.numberPromotions * 230), width: Int(self.promotionsScrollView.frame.size.width), height: 200)
self.promotionsScrollView.addSubview(imageView)
self.numberPromotions = self.numberPromotions + 1;
//Make sure the images will all fit into the scrollview
self.promotionsScrollView.contentSize = CGSizeMake(self.promotionsScrollView.frame.size.width,
CGFloat(self.numberPromotions * 230));
}
}
}
当你得到 promotions
对象(解析的 JSON 数据)时,你就有了图片和路径。
您已经在使用图片在滚动视图中显示图片。
现在您需要做的是告诉手势识别器转到属于该图像的特定路径。因为你有一个手势识别器来识别所有的图像(这是完美的),你需要将 "somehow" 图片与路径相关联。
为此,您可以在 class 的范围内创建一个变量,例如字典,您将在其中保存所有促销及其图片和路径。
我将使用元组数组,但您可以使用任何您想要的数据类型(字典、数组等)。
private var promos = Array<(picture: String, path: String)>()
在你的for循环中,将数据保存到刚刚创建的变量中:
for (_, promotion) in promotions {
let p = (picture: promotion.picture, path: promotion.path)
self.promos.append(p)
self.downloadImage(NSURL(string: promotion.picture)!, index: self.promos.count - 1)
}
现在你需要告诉每个 UIImageView
它属于 promos
数组的哪个索引,就在将它添加到滚动视图之前(可能是在设置 userInteractionEnabled
之后:
imageView.tag = index
并且您需要将 index
添加为函数的参数:
func downloadImage(url: NSURL, index: Int) { ... }
现在您可以从手势识别器操作访问它:
func imageTapped(gesture: UIGestureRecognizer)
{
if let imageView = gesture.view as? UIImageView {
if let url = NSURL(string: self.promos[imageView.tag].path) {
UIApplication.sharedApplication().openURL(url)
}
}
}
我建议将 gesture
更改为 sender
,因为这样会更有意义。