2016-07-12 23 views
0

これで、jsonファイルからのURLである「パス」を取得し、プロジェクトのimageViewにリンクしようとしています。画像とパスは、私がダウンロードした画像とscrollviewを埋めるが、今、私は画像をクリックして、別のURLにリダイレクトすることに成功し、このjsonファイルswiftからNSURLをロードしてimageViewにリンクします

{image:"http//www.something.com", path:"http://www.godbsdahb.com" } 

のような1つのJSONラインに来ます。私はリダイレクトを管理しますが、パスとイメージのリンクは管理しません。私はそのことをどうやって迷っているのですか。どんな助けもありがとう。 これまで私がこれまで持っていたことはありますが、それも機能しますが、パスとイメージへのリンクはありません。これで任意のヘルプ

感謝:ここ

はそれのためのコードです:

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() 
} 

UPDATE:ここ

は、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 
        } 

       } 
      }) 
     }) 

} 
です

}

更新:

新しいコードあなたがpromotionsオブジェクト(解析されたJSONデータ)を取得すると、あなたがそこに絵やパスを持っている

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)); 
     } 
    } 
} 
+0

'imageTapped'メソッドが呼び出されていますか? –

+0

はい、私はすべての画像をタップすると、ページとしてGoogleとWebブラウザを開きます – MNM

+0

私がしたいのは、どのURLのgoogle Webページが – MNM

答えて

2

をブロックします。

既にスクロールビューで画像を表示するために画像を使用しています。

これで、ジェスチャー認識プログラムにその画像に属する特定のパスに移動するよう指示する必要があります。すべての画像(完全なもの)にジェスチャーレコグナイザが1つあるので、パスとピクチャを「何らかの形で」関連付けなければなりません。

これを行うには、クラスのスコープ内に変数を作成します。たとえば、そのピクチャとパスですべてのプロモーションを保存する辞書を作成できます。

タプルの配列を使用しますが、任意のデータ型(辞書、配列など)を使用できます。

ループのためのあなたの中
private var promos = Array<(picture: String, path: String)>() 

、変数先ほど作成したデータを保存します。

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) 
} 

今、あなただけに追加する前に、それが属するpromos配列のどのインデックスに各UIImageViewを伝える必要がありますscrollview(それはuserInteractionEnabledを設定した後に次のようになります。

imageView.tag = index 

そして、あなたはパラメータ0としてそのindexを追加する必要があります関数f:

func downloadImage(url: NSURL, index: Int) { ... } 

そして今、あなたはジェスチャー認識のアクションからアクセスすることができます:それはより多くの意味になるだろうと私はsendergestureを変更することをお勧め

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) 
     } 
    } 
} 

+0

これは非常に近いですが、画像をクリックすると表示されません。新しいURLに新しいコードを上に掲載しました。ありがとうございました – MNM

+0

これは私に 'UITapGestureRecognizer'から無関係な型 'UIImageView'へのキャストが常に失敗する唯一の警告です – MNM

+0

はい、間違いです。これは、 'imageView = gesture.viewをasとすれば? UIImageView {' –

関連する問題