2017-05-30 10 views
-5

此功能會將照片上傳到存儲桶,然後在文本字段中顯示該照片的直接鏈接。我想要做的就是縮短鏈接,所以我使用alamofire創建了一個對Google的URL縮短器的發佈請求,並且它工作正常,但我不知道如何在文本框中顯示它。以JSON的響應並在textField中顯示

下面是函數

func ImageDownloader(){ 


    UIApplication.shared.isNetworkActivityIndicatorVisible = true 

    let imageContained = viewimage.image 

    let storage = Storage.storage() 
    var storageRef = storage.reference() 
    storageRef = storage.reference(forURL: "") // Link to bucket 

    var data = NSData() 
    data = UIImageJPEGRepresentation(imageContained!, 0.8)! as NSData 
    let dateFormat = DateFormatter() 
    dateFormat.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" 
    let imageName = dateFormat.string(from: NSDate() as Date) 
    let imagePath = "images/\(imageName).jpg" 
    let metaData = StorageMetadata() 
    let mountainsRef = storageRef.child(imagePath).putData(data as Data, metadata: metaData){(metaData,error) in 
     if let error = error { 
      print(error.localizedDescription) 
      return 
     }else{ 
      //store downloadURL 
      let downloadURL = metaData!.downloadURL()!.absoluteString 
      self.getLink.text = downloadURL 



       struct dlink { 
        let longLink: String 
       } 
       let v = dlink(longLink: "\(downloadURL)") 

       let parameters = ["longUrl":"\(v.longLink)","MYURL":""] 

       Alamofire.request("https://www.googleapis.com/urlshortener/v1/url?key=MY_KEY", method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON { response in 
        print(response) 
       } 


      } 
     metaData?.contentType = "image/jpeg" 
     } 

,這裏是表明它正常工作JSON響應。

enter image description here

任何形式的幫助,將不勝感激!

回答

1

您需要訪問result.valueresponse以獲得序列號爲JSON的響應。

Alamofire.request("https://www.googleapis.com/urlshortener/v1/url?key=MY_KEY", method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON { response in 
    if let dictionary = response.result.value as? [String:Any] { 
     //Now subscript on dictionary with keys to get your values. 
     let id = dictionary["id"] as? String ?? "DefaultValue" //set default value that you want 
     let kind = dictionary["kind"] as? String ?? "DV" 
     let longUrl = dictionary["longUrl"] as? String ?? "DV" 
     print(id, kind, longUrl) 
    } 
} 

可以檢查Alamofire文檔Response Handling部分,以獲得更多的想法。

+0

它工作!非常感謝,我真的很感激:) –

0

您將需要使用JSONSerialization分析數據:

let text = "{\"id\":\"https://link.right.here/\"}" 

do { 
    let json = try JSONSerialization.jsonObject(with: text.data(using: .ascii)!, options: []) as! [String: Any] 
    let id = json["id"] as? String 
    print(id) 
} catch { 
    print("Json parse failure") 
    fatalError() 
} 

(不要忘了在全球挽救id變量,或做/ catch語句的至少外)

然後您將需要訪問正在更改的文本框。要做到這一點,你應該爲故事板中連接到視圖控制器的文本框創建一個插口。我不會去探討這個問題,因爲這不是你的問題所要求的,因爲這裏有很多關於它的教程。關鍵工作是出路。

假設出口名稱爲myTextfield,只需例如,你的代碼應該是這樣的:

self.myTextfield.text = "\(id)" 

其中id是在代碼的第一部分設置變量。

+0

謝謝你的解釋。有一件事我不明白。在常量文本中包含一個鏈接應該在那裏插入什麼鏈接? –

+0

我寫了僞數據爲JSON,使用你的JSON代替 –