Maui 教學 – 程式員往往寫App時需要把Result (如Text File, Image, Pdf)傳至其他人, 或用其他App再作修改, 所以我們也往往會用到Share的Function.
與用其他語言一樣, 寫Share功能是一件輕鬆的事, Maui 的Share功能都是簡化的CODE, 往往只需幾句CODE, 加上填上file extension就可完成, Share版面打開後會自動出現相關程式.
不過與其他語言不同, Maui 是cross platform的, 同一段CODE可以在Android用, IOS用, WINDOWS用, 減少了編程的程序. 把Share的Function獨立起來並用加入dll library內, 更可做到多程式共用.
本篇主要介紹Maui Share的功能及提供Code. 最後提供例子ShareManager作結尾.
Let’s Code.
IOS |
Platforms/iOS/Info.plist Platforms/MacCatalyst/Info.plist |
<key>NSPhotoLibraryAddUsageDescription</key> <string>This app needs access to the photo gallery to save photos and videos.</string> <key>NSPhotoLibraryUsageDescription</key> <string>This app needs access to the photo gallery to save photos and videos.</string> |
Code – Share Text |
await Share.Default.RequestAsync(new ShareTextRequest { Text = text, Title = “Share Text” }); |
Code – Share Link |
await Share.Default.RequestAsync(new ShareTextRequest { Uri = uri, Title = “Share Link” }); |
Code – Share Files |
string file1 = Path.Combine(FileSystem.CacheDirectory, “Invoice.pdf”); string file2 = Path.Combine(FileSystem.CacheDirectory, “PaymentNote.txt”); File.WriteAllText(file1, “Content 1”); File.WriteAllText(file2, “Content 2”); await Share.Default.RequestAsync(new ShareMultipleFilesRequest { Title = “Share invoice with payment note”, Files = new List<ShareFile> { new ShareFile(file1), new ShareFile(file2) } }); |
參考資料: https://docs.microsoft.com/en-us/dotnet/maui/