2017-08-30 51 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