2017-08-30 54 views
0

我有使用Swift和Alamofire將我的視頻,標題和描述上傳到YouTube的工作代碼。通過YouTube數據API插入描述和換行符

我的描述作爲一條線上傳到YouTube,我想在每個變量後分割線。

我的描述變量,像這樣:

myDescription = (price! as! String) + " " + (package! as! String) 

當該得到的發送到YouTube,它顯示爲:

「Pricehere PACKAGENAME」

我想PACKAGENAME在YouTube上展示使用換行符描述:

「Pricehere
PackageName」

我在目標C的老項目這樣做到了這一點:

 NSString *description = [NSString stringWithFormat:@"%@\n%@\n%@\n%@\n%@\n%@", str1, str2, str3, str4, str5, str6]; 

當傳遞給YouTube的它增加了每個變量,然後做了一個換行符。

感謝您的任何幫助。

編輯將在YouTube的上傳功能以供參考:

func postVideoToYouTube(token: String, callback: @escaping (Bool) -> Void){ 

    let headers = ["Authorization": "Bearer \(token)"] 
    let urlYoutube = "https://www.googleapis.com/upload/youtube/v3/videos?part=snippet" 

    let path = videoURL?.path 
    let videodata: Data = NSData.dataWithContentsOfMappedFile(path!)! as! Data 

    upload(
     multipartFormData: { multipartFormData in 
      multipartFormData.append("{'snippet':{'title' : '\(self.myTitle)', 'description': '\(self.myDescription)'}}".data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "snippet", mimeType: "application/json") 
      multipartFormData.append(videodata, withName: "video", fileName: "video.mp4", mimeType: "application/octet-stream") 
    }, 
     to: urlYoutube, 
     method:Alamofire.HTTPMethod.post, 
     headers:headers, 
     encodingCompletion: { encodingResult in 
      switch encodingResult { 
      case .success(let upload, _, _): 
       upload.responseJSON { response in 
        print(response) 
        let result = response.result.value 
        let JSON = result as! NSDictionary 
        let videoId = JSON.object(forKey: "id") as! String 
        print("VideoID: ", videoId) 
        self.addVideoToPlaylist(videoId: videoId, callback: { (result) in 
         callback(result) 
        }) 

       } 
       break 
      case .failure(let encodingError): 
       print(encodingError) 
       callback(false) 
       break 
      } 

    } 
    ) 
} 

回答

0

小心力鑄造的變量,比如你在做什麼,我會建議你做這樣的事情:

if let price = price as? String, let package = package as? String { 
    myDescription = "\(price)\n\(package)" 
} 

通過這種方式您可以安全地解開並使用字符串插值構建字符串,您可以在the documentation中閱讀更多信息。

+0

我試過了你的代碼,它會在「let videoId = JSON.object(forKey:」id「)as!String」的上傳代碼中崩潰,如果我使用\ n。如果我把它拿出來留下一個空間,它運行良好(但所有項目顯然仍然在一行上)。 – user3534305

+0

它最終成爲兩個快速變量之間的\\ n。感謝您指點我正確的方向。 – user3534305