Это моя версия для Swift 3 / Swift 4.
Объяснение того, что происходит в коде.
Это по существу тот же ответ, что и Sh_Khan's. Но в его примере пользователь уже знает путь к ведро. В моем примере мы получаем путь от задачи загрузки. Именно это и привело меня к этому вопросу, а также то, что, как мне кажется, искал, когда он искал замену metadata.downloadURL()
.
class StorageManagager {
private let storageReference: StorageReference
init() {
// first we create a reference to our storage
// replace the URL with your firebase URL
self.storageReference = Storage.storage().reference(forURL: "gs://MYAPP.appspot.com")
}
// MARK: - UPLOAD DATA
open func uploadData(_ data: Data, named filename: String, completion: @escaping (URL? , Error?) -> Void) {
let reference = self.storageReference.child(filename)
let metadata = StorageMetadata()
metadata.contentType = "ourType" // in my example this was "PDF"
// we create an upload task using our reference and upload the
// data using the metadata object
let uploadTask = reference.putData(data, metadata: metadata) { metadata, error in
// first we check if the error is nil
if let error = error {
completion(nil, error)
return
}
// then we check if the metadata and path exists
// if the error was nil, we expect the metadata and path to exist
// therefore if not, we return an error
guard let metadata = metadata, let path = metadata.path else {
completion(nil, NSError(domain: "core", code: 0, userInfo: [NSLocalizedDescriptionKey: "Unexpected error. Path is nil."]))
return
}
// now we get the download url using the path
// and the basic reference object (without child paths)
self.getDownloadURL(from: path, completion: completion)
}
// further we are able to use the uploadTask for example to
// to get the progress
}
// MARK: - GET DOWNLOAD URL
private func getDownloadURL(from path: String, completion: @escaping (URL?, Error?) -> Void) {
self.storageReference.child(path).downloadURL(completion: completion)
}
}
Одна вещь, которую нужно добавить - я обнаружил, что синтаксис синтаксиса Razor (и, вероятно, компилятор) интерпретирует положение открытой скобки по-разному:
<script type="text/javascript">
var somevar = new Array();
@foreach (var item in items)
{ // <---- placed on a separate line, NOT WORKING, HILIGHTS SYNTAX ERRORS
<text>
</text>
}
@foreach (var item in items) { // <---- placed on the same line, WORKING !!!
<text>
</text>
}
</script>
Я просто написал эту вспомогательную функцию. Поместите его в App_Code/JS.cshtml
:
@using System.Web.Script.Serialization
@helper Encode(object obj)
{
@(new HtmlString(new JavaScriptSerializer().Serialize(obj)));
}
Тогда в вашем примере вы можете сделать что-то вроде этого:
var title = @JS.Encode(Model.Title);
Обратите внимание, как я не помещаю кавычки вокруг него. Если заголовок уже содержит кавычки, он не будет взорваться. Кажется, тоже прекрасно справляются со словарями и анонимными объектами!
Я предпочитаю «& lt;! -" "->" как "текст>"
<script type="text/javascript">
//some javascript here
@foreach (var item in itens)
{
<!--
var title = @(item.name)
...
-->
</script>
Какие конкретные ошибки вы видите?
Что-то вроде этого может работать лучше:
<script type="text/javascript">
//now add markers
@foreach (var item in Model) {
<text>
var markerlatLng = new google.maps.LatLng(@Model.Latitude, @Model.Longitude);
var title = '@(Model.Title)';
var description = '@(Model.Description)';
var contentString = '<h3>' + title + '</h3>' + '<p>' + description + '</p>'
</text>
}
</script>
Обратите внимание, что вам нужен магический тег <text>
после foreach
до что Razor должен переключиться в режим разметки.
Наконец я нашел решение (* .vbhtml):
function razorsyntax() {
/* Double */
@(MvcHtmlString.Create("var szam =" & mydoublevariable & ";"))
alert(szam);
/* String */
var str = '@stringvariable';
alert(str);
}