Xamarin.Forms(PCL)와 CoreTweet에서 트윗해 보았다.

16749 단어 Xamarin

개요



Xamarin이 재미있을 것 같았기 때문에 연습을 겸해 만들어 본 것을 게시합니다.
단순히 문자를 입력하고 트윗하는 간단한 앱입니다.
iOS에서도 Android에서도 동작합니다(`・ω・´)

환경


  • MacOS X 10.11.5
  • Xamarin Studio Community 6.1(Alpha channel)

  • 프로젝트 유형


  • Xamarin.Forms FormApp
  • Shared Code는 PCL (Portable Class Library)

  • NuGet에서 소개하는 패키지


  • CoreTweet Version 0.5.3
  • CoreTweet.Streaming.Reactive Version 0.5.3
  • Corcav.Behaviors 버전 2.1.1
    ※CoreTweet는, 왠지 최신판을 도입할 수 없고, 도입할 수 있는 가운데 최신의 버전이 0.5.3 때문에,
    CoreTweet은 0.5.3을 도입했습니다. (´・ω・`)
    (본건은 코멘트를 받았으므로 그쪽을 참고해주세요)

  • 덧붙여 상기를 도입하면 아래와 같이가 자동으로 들어갑니다.
  • Newtonsoft.Json
  • Rx-Core
  • Rx-Interfaces
  • Rx-Linq

  • 프로젝트 이름



    이번에는 TwitterSample이라는 이름으로 만들었습니다.

    주의사항


  • Android에서 제대로 작동하려면 AndroidManifest.xml에서 'Internet' Permission을 설정합니다.
  • iOS AppDelegate.cs의 LoadApplication(new App()); 앞에 다음을 추가하십시오.
    Corcav.Behaviors.Infrastructure.Init();

  • 출처



    MainPage.xaml



    XAML에서 UI를 작성합니다.
    화면을 옆으로 향한 경우 등, UI가 화면 밖으로 튀어 나올 때 조작할 수 없게 되어 버리므로,
    StackLayout을 ScrollView로 둘러싸고 있습니다.

    MainPage.xaml
    <?xml version="1.0" encoding="UTF-8"?>
    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
            xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
            xmlns:behaviors="clr-namespace:Corcav.Behaviors;assembly=Corcav.Behaviors"
            x:Class="TwitterSample.MainPage">
    
        <ScrollView Padding="30,60,30,30">
            <StackLayout>
                <Label Text="Tweetするよ!" HorizontalTextAlignment="Center" />
    
                <Editor Text="{Binding TweetText,Mode=TwoWay}" HeightRequest="200" BackgroundColor="Silver">
                    <behaviors:Interaction.Behaviors>
                        <behaviors:BehaviorCollection>
                            <behaviors:EventToCommand EventName="TextChanged" Command="{Binding CountWord}" />
                        </behaviors:BehaviorCollection>
                    </behaviors:Interaction.Behaviors>  
                </Editor>
    
                <Label Text="{Binding WordCount,Mode=OneWay}" HorizontalTextAlignment="End"/>
    
                <Button Command="{Binding Tweet}" Text="Tweetする!" />
            </StackLayout>
        </ScrollView>
    
    </ContentPage>
    

    MainPage.xaml.cs



    BindingContext를 사용합니다.

    MainPage.xaml.cs
    using Xamarin.Forms;
    
    namespace TwitterSample
    {
        public partial class MainPage : ContentPage
        {
            public MainPage()
            {
                InitializeComponent();
    
                var View = new ViewModel(){};
                this.BindingContext = View;
            }
        }
    }
    

    TwitterSample.cs



    처음에 들어 있던 코드는 거의 모두 지워, MainPage = new MainPage(); 로만 합니다.

    TwitterSample.cs
    using Xamarin.Forms;
    
    namespace TwitterSample
    {
        public class App : Application
        {
            public App()
            {
                // The root page of your application
                MainPage = new MainPage();
            }
    
            protected override void OnStart()
            {
                // Handle when your app starts
            }
    
            protected override void OnSleep()
            {
                // Handle when your app sleeps
            }
    
            protected override void OnResume()
            {
                // Handle when your app resumes
            }
        }
    }
    

    ViewModelBase.cs



    ViewModel에 대한 기본 클래스를 INotifyPropertyChanged를 상속하여 만듭니다.

    ViewModelBase.cs
    using System.ComponentModel;
    
    namespace TwitterSample
    {
        public class ViewModelBase : INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged;
    
            public void NotityPropertyChanged(string info)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(info));
                }
            }
        }
    }
    

    ViewModel.cs



    ViewModelBase에서 ViewModel을 만들고 MainPage.xaml과 Binding시키는 명령 등을 정의합니다.

    ViewModel.cs
    using System.Windows.Input;
    using Xamarin.Forms;
    
    namespace TwitterSample
    {
        public class ViewModel : ViewModelBase
        {
            public ICommand CountWord { get; set; }
            public ICommand Tweet { get; set; }
    
            Model Model = new Model(){};
    
            public ViewModel()
            {
                CountWord = new Command(() => WordCount = Model.CountWord(TweetText));
                Tweet = new Command(() => Model.TweetAsync(TweetText));
            }
    
            private string _TweetText;
            public string TweetText
            {
                get { return _TweetText; }
                set
                {
                    _TweetText = value;
                    NotityPropertyChanged("TweetText");
                }
            }
    
            private int _WordCount;
            public int WordCount
            {
                get { return _WordCount; }
                set
                {
                    _WordCount = value;
                    NotityPropertyChanged("WordCount");
                }
            }
        }
    }
    

    Model.cs



    여기에 Tweet시키는 코드 등을 씁니다.
    Key와 Secret은 "Twitter Apps"에서 얻을 수 있습니다.

    Model.cs
    using System.Threading.Tasks;
    using CoreTweet;
    namespace TwitterSample
    {
        public class Model
        {
    
            public int CountWord(string TweetText)
            {
                return TweetText.Length;
            }
    
            async public Task TweetAsync(string TweetText)
            {
                var tokens = Tokens.Create("API key",
                                           "API secret",
                                           "Access token",
                                           "Access token secret");
    
                var accepted = await Xamarin.Forms.Application.Current.MainPage.DisplayAlert("確認", "Tweetしますか?", "OK","Cancel");
                if (accepted)
                {
                    tokens.Statuses.UpdateAsync(status => TweetText);
                    await Xamarin.Forms.Application.Current.MainPage.DisplayAlert("(`・ω・´)", "Tweetしました!", "OK");
                }
            }
        }
    }
    

    할 수있는 것



    이제 단순히 트윗만 하는 앱이 생겼습니다(`・ω・´)
    (문자를 입력하면 자동으로 오른쪽 하단의 문자 수가 변경됩니다.)

    여기 잘못 됐어-라든지, Qiita의 투고 방법 이상해-라든지 등 있으면 가르쳐 주세요!
    (투고 처음입니다.)

    좋은 웹페이지 즐겨찾기