顯示具有 xcode 標籤的文章。 顯示所有文章
顯示具有 xcode 標籤的文章。 顯示所有文章

2015年7月9日 星期四

[iOS] 處理iphone4/4s 與iphone5/5s 和 iphone 6/6 plus 尺寸不同問題(xib file)

在開發iOS的時候一定會遇到當不同機身(4s,5s,6,6plus)介面會跑掉的問題!

而這個問題也讓我苦惱了一個禮拜,網路上沒有非常好的解法(stackoverflow有,不過你要看

的懂他寫的,而且解法非完美要結合另一篇才行)


首先,概念其實很簡單,為每一個xib檔案配一個不同尺寸的xib檔(也就是各尺寸各一)

然後,判定現在的機型是哪一種,iphone 4s ? 5/5s? 6? 6 plus? 決定要套用哪一個xib檔案

該怎樣判定呢?

先定義螢幕長寬吧!

#define SCREEN_WIDTH ([[UIScreen mainScreen] bounds].size.width)
#define SCREEN_HEIGHT ([[UIScreen mainScreen] bounds].size.height)
#define SCREEN_MAX_LENGTH (MAX(SCREEN_WIDTH, SCREEN_HEIGHT))
#define SCREEN_MIN_LENGTH (MIN(SCREEN_WIDTH, SCREEN_HEIGHT))

#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
#define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
#define IS_RETINA ([[UIScreen mainScreen] scale] >= 2.0)

#define iPhone4s_or_less (IS_IPHONE && SCREEN_MAX_LENGTH < 568.0)
#define iphone5 (IS_IPHONE && SCREEN_MAX_LENGTH == 568.0)
#define iphone6 (IS_IPHONE && SCREEN_MAX_LENGTH == 667.0)

#define iphone6plus (IS_IPHONE && SCREEN_MAX_LENGTH == 736.0)

接著我們需要在initWithNibName()這邊判斷

現在是4s,5,6,6plus

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    if (iphone6plus) {
        NSLog(@"iphone 6 +");
        self = [super initWithNibName:@"Page2_6_plus" bundle:nibBundleOrNil];
    }
    else if(iphone6)
    {
        NSLog(@"iphone 6");
        self = [super initWithNibName:@"Page2_6" bundle:nibBundleOrNil];
    }
    else if (iphone5) {
        NSLog(@"iphone 5/5s ");
        self = [super initWithNibName:@"Page2_5s" bundle:nibBundleOrNil];
    }
    else{
        NSLog(@"iphone 4s ");
        self = [super initWithNibName:@"Page2" bundle:nibBundleOrNil];
    }
    
    return self;
    
}

當然,也是要把xib檔案複製->改名為相對應的名稱,這樣一來,就完成囉!

end

[iOS] 特效進度條(ASProgressPopupView)的使用方法

在Code4app網站中找到一個不錯的特效包--ASProgressPopupView


點此連結到Code4app


上面寫的很簡單,但實際使用起來卻不是這樣

"使用方法:


self.progressView.font = [UIFont fontWithName:@"Futura-CondensedExtraBold" size:26]; 
self.progressView.popUpViewAnimatedColors = @[[UIColor redColor], [UIColor orangeColor], [UIColor greenColor]]; 
self.progressView.popUpViewCornerRadius = 16.0;"

實際在github上的描述是:

github

How to use it

It’s very simple. Drag a UIProgressView into your Storyboard/nib and set its class to ASProgressPopUpView – that's it. The example below demonstrates how to customize the appearance.
self.progressView.font = [UIFont fontWithName:@"Futura-CondensedExtraBold" size:26];
self.progressView.popUpViewAnimatedColors = @[[UIColor redColor], [UIColor orangeColor], [UIColor greenColor]];
self.progressView.popUpViewCornerRadius = 16.0;
To show the popUpView, just call:
[self.progressView showPopUpViewAnimated:YES];
And to hide:
[self.progressView hidePopUpViewAnimated:YES];
You update the value exactly as you would normally use a UIProgressView, just update theprogress property self.progressView.progress = 0.31;
詳細的可以去github上面看

這邊的教學:
1.先把下面這四個檔案copy進去專案,然後在你要寫的.m file裡面新增
#import "ASValueTrackingSlider.h"
2.開啟你的xib file,拉一個slider進去畫面,把class改為ASValueTrackingSlider
然後把該元件拉到.m file產生一個名叫slider1的物件

可以看到他的屬性是ASValueTrackingSlider,不是uislider,是的話就搞錯囉!

接著我們就可以使用slider1來做事情(控制他)

3.為了讓我的進度條上面顯示的文字最後面都有個"V",所以這邊要增加三行(第一行是宣告)

    NSNumberFormatter *voltFormatter = [[NSNumberFormatter alloc] init];
    [voltFormatter setPositiveSuffix:@"V"];
    [voltFormatter setNegativeSuffix:@"V"];
再來就是一些基本的設定
    self.slider1.popUpViewCornerRadius = 12.0;
    [self.slider1 setNumberFormatter:voltFormatter];
    [self.slider1 setMaxFractionDigitsDisplayed:0];
    self.slider1.popUpViewColor = [UIColor colorWithHue:0.55 saturation:0.8 brightness:0.9 alpha:0.7];
    self.slider1.font = [UIFont fontWithName:@"GillSans-Bold" size:22];
    self.slider1.popUpViewAnimatedColors = @[[UIColor redColor], [UIColor orangeColor], [UIColor greenColor]];
//這邊是讓我前中後段的顏色有不同

    [self.slider1 showPopUpViewAnimated:YES];
//這一段一定要show不然他不會顯示文字出來


如果是要有%數的話則改用這段

    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setNumberStyle:NSNumberFormatterPercentStyle];
    [self.slider1 setNumberFormatter:formatter];
    self.slider1.popUpViewAnimatedColors = @[[UIColor greenColor], [UIColor orangeColor], [UIColor redColor]];
   self.slider1.font = [UIFont fontWithName:@"Futura-CondensedExtraBold" size:26];
    [self.slider1 showPopUpViewAnimated:YES];

又或者你想要到某個區段就顯示某些文字的話,請加入這一行

self.slider1.dataSource = self;

然後加入這一段

- (NSString *)slider:(ASValueTrackingSlider *)slider stringForValue:(float)value;
{
    value = roundf(value);
    NSString *s;
    if (value < 30) {
        s = @"Warning!! Low Voltage";
    } else if (value > 29.0 && value < 50.0) {
        s = [NSString stringWithFormat:@"😎 %@ 😎", [slider.numberFormatter stringFromNumber:@(value)]];
    } else if (value >= 50.0) {
        s = [NSString stringWithFormat:@"%dV", value];
    }
    return s;
}

最後,完成版本就像這樣~



























然後如果要調整他的弧度的話(邊角弧度)


self.slider2.popUpViewCornerRadius = 12.0;

這邊可以調整


希望大家都能夠開心使用,(畢竟作者沒有講很清楚,我也摸了一會兒才會),end

2015年6月9日 星期二

[iOS] 如何儲存使用者設定?(NSUserDefaults) / 類似Android的SharedPreferences

相信大家寫的app如果有登入之類的東西一定會遇到一個問題,就是儲存使用者設定!

不然每次叫使用者重新輸入應該會崩潰吧?!


--------------------------------------------------------------------------------------------------------------------------


正文開始:

Step1:

先到.h檔 (看是appdelegate.h or ViewController.h)

宣告一個NSUserDefaults屬性的變數

//
//  AppDelegate.h
//
//  Created by daniel on 2015/4/29.
//  Copyright (c) 2015年 daniel. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "AsyncUdpSocket.h"
#define global ((AppDelegate *)[[UIApplication sharedApplication] delegate])

@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
    NSUserDefaults *userDefaults;

}

這樣我們就可以在.m file內使用該變數(userDefaults)



Step2:

在.m file內的viewdidload()這裡面(反正就是第一個讀到的地方)

先初始化我們的userDefaults,這一部很重要!!沒有初始化會叫不出儲存的東西!!

初始化:userDefaults = [NSUserDefaults standardUserDefaults];

接下來就是儲存/讀取

儲存:

    NSString *string = @"192.168.0.1";
    [userDefaults setObject:string forKey:@"store IP"];

    NSArray *array = @[@"123",@"456"];
    [userDefaults setObject:array forKey:@"Array"];

    BOOL isValid = YES;
    [userDefaults setBool: isValid forKey:@"isValid"];

    int number = 100;
    [userDefaults setInteger:number forKey:@"number"];

可以看到上述四種不同的類型(nsstring,nsarray,BOOL,int)

大致上都是一樣的,差別只是在於setXXX(類型)

格式:(儲存)

[NSUserDefaults型態變數  setObject(或其他型態): 變數名稱 forKey: @"隨意取key 名稱"]

格式:(讀取)

[NSUserDefaults型態變數 stringforKey: @"隨意取key 名稱"]

(或是valueforKey:)

範例:NSString *store_ip = [userDefaults stringForKey:@"store IP"];


*****非常重要*****

在儲存完畢以後,要記得!!

[NSUserDefaults型態變數 synchronize];

如果沒有這行,就不會真正儲存到硬碟裡面!

完成以後,就可以透過這樣的方式來儲存使用者設定了:)

END


2015年5月15日 星期五

[iOS] 可展開/收和型的tableView

在找expantable listview,結果找了半天沒有找到,

原來是android叫做listview,ios則是叫做tableview!

這次在.h file完全不用作任何事情,所以就不說.h file了!

原始檔案在這邊:

http://code4app.com/ios/ExpansionTableView/5121cac66803fae949000002

是參考這個弄出來的


------------------------------------------------------------------------------------------------------------------

首先,如果你有開ARC的話,那不需要release/dealloc之類的

第一步:

在viewDidLoad裡面加入

    NSString *path  = [[NSBundle mainBundle] pathForResource:@"ExpansionTableTestData" ofType:@"plist"];//指定要去哪一個檔案名稱,檔案類型找,放進去path裡面

    _dataList = [[NSMutableArray alloc] initWithContentsOfFile:path];


pathForResource這邊是檔案名稱 

ofType則是檔案類型

所以我們要讀取的列表就是ExpansionTableTestData.plist這個檔案


顯然還沒宣告_dataList,所以在前面interface下面就要先宣告一個

NSMutableArray *_dataList;


像這樣

@interface Page3 ()<UITableViewDataSource,UITabBarDelegate>
{
    NSMutableArray *_dataList;
}
@property (assign)BOOL isOpen;
@property (nonatomic,retain) NSIndexPath *selectIndex;
@property (nonatomic,retain) IBOutlet UITableView *expansionTableView;

@end

@implementation Page3
@synthesize isOpen,selectIndex;

紅色部分為新增的


再來就是新增加建構子,

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [_dataList count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.isOpen) {
        if (self.selectIndex.section == section) {
            return [[[_dataList objectAtIndex:section] objectForKey:@"list"] count]+1;;
        }
    }
    return 1;
}

//iphone 5以下可以用float,5s~6 plus CGFloat
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isOpen&&self.selectIndex.section == indexPath.section&&indexPath.row!=0) {
        static NSString *CellIdentifier = @"Cell2";
        Cell2 *cell = (Cell2*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        
        if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil] objectAtIndex:0];
        }
        NSArray *list = [[_dataList objectAtIndex:self.selectIndex.section] objectForKey:@"list"];
        cell.titleLabel.text = [list objectAtIndex:indexPath.row-1];
        return cell;
    }else
    {
        static NSString *CellIdentifier = @"Cell1";
        Cell1 *cell = (Cell1*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil] objectAtIndex:0];
        }
        NSString *name = [[_dataList objectAtIndex:indexPath.section] objectForKey:@"name"];
        cell.titleLabel.text = name;
        [cell changeArrowWithUp:([self.selectIndex isEqual:indexPath]?YES:NO)];
        return cell;
    }
}


#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //展開items,開始判斷式
    if (indexPath.row == 0) {
        //第一層
        if ([indexPath isEqual:self.selectIndex]) {
            self.isOpen = NO;
            [self didSelectCellRowFirstDo:NO nextDo:NO];//進入下一段函式
            self.selectIndex = nil;
            
        }else
        {
            if (!self.selectIndex) {
                self.selectIndex = indexPath;
                [self didSelectCellRowFirstDo:YES nextDo:NO];
                
            }else
            {
                
                [self didSelectCellRowFirstDo:NO nextDo:YES];
            }
        }
        
    }else
    {
        //第二層
        NSDictionary *dic = [_dataList objectAtIndex:indexPath.section];
        NSArray *list = [dic objectForKey:@"list"];
        NSString *item = [list objectAtIndex:indexPath.row-1];
        //顯示點擊的item
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:item message:nil delegate:nil cancelButtonTitle:@"取消" otherButtonTitles: nil];
        [alert show];//跳出訊息
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


- (void)didSelectCellRowFirstDo:(BOOL)firstDoInsert nextDo:(BOOL)nextDoInsert
{
    self.isOpen = firstDoInsert;
    
    Cell1 *cell = (Cell1 *)[self.expansionTableView cellForRowAtIndexPath:self.selectIndex];
    [cell changeArrowWithUp:firstDoInsert];//疑似把箭頭往上?
    
    [self.expansionTableView beginUpdates];
    
    int section = self.selectIndex.section;
    int contentCount = [[[_dataList objectAtIndex:section] objectForKey:@"list"] count];
    NSMutableArray* rowToInsert = [[NSMutableArray alloc] init];
    for (NSUInteger i = 1; i < contentCount + 1; i++) { //第二層有幾行 = content count
        NSIndexPath* indexPathToInsert = [NSIndexPath indexPathForRow:i inSection:section];
        [rowToInsert addObject:indexPathToInsert];
    }
    
    if (firstDoInsert)
    {   [self.expansionTableView insertRowsAtIndexPaths:rowToInsert withRowAnimation:UITableViewRowAnimationTop];
    }
    else
    {
        [self.expansionTableView deleteRowsAtIndexPaths:rowToInsert withRowAnimation:UITableViewRowAnimationTop];
    }
    
    //[rowToInsert release];
    
    [self.expansionTableView endUpdates];
    if (nextDoInsert) {
        self.isOpen = YES;
        self.selectIndex = [self.expansionTableView indexPathForSelectedRow];
        [self didSelectCellRowFirstDo:YES nextDo:NO];
    }
    if (self.isOpen) [self.expansionTableView scrollToNearestSelectedRowAtScrollPosition:UITableViewScrollPositionTop animated:YES];
}

然後我們要建構xib檔,拉出一個table view (記得要選autolayer)

然後要與@property (nonatomic,retain) IBOutlet UITableView *expansionTableView;

這一行做連結(滑鼠右鍵拉過去connect)

















然後還要把dataSource/delegate也連結到file's Owner

如果要修改列表的內容,就要去expansiontabletestdata.plist那邊修改喔!

完整檔案在code4app可以下載,這邊就不附上囉!

end

2015年5月11日 星期一

[iOS] 可輸入文字(textfield)之警告視窗(alertview)

又遇到問題,於是找了方法來解決


android上面的alertview十分簡單(custom的部份)

iOS呢?是否一樣簡單?

[ iOS 7 + Xcode 6.3.1 ]


第一次看別人的code:


    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"輸入IP" message:@" " delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"確認",nil];
    UITextField * txt = [[UITextField alloc] init];
    txt.backgroundColor = [UIColor whiteColor];
    txt.frame = CGRectMake(alert.center.x+65,alert.center.y+48, 150,23);
    [alert addSubview:txt];

    [alert show];

結果有跳出警告視窗,但是沒有可以輸入的阿!

於是就繼續查,才發現要加上

alert.alertViewStyle = UIAlertViewStylePlainTextInput;


正確版本:

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"輸入IP" message:@" " delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"確認",nil];
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    UITextField * txt = [[UITextField alloc] init];
    txt.backgroundColor = [UIColor whiteColor];
    txt.frame = CGRectMake(alert.center.x+65,alert.center.y+48, 150,23);
    [alert addSubview:txt];
    [alert show];

當然style也有password/default(無法顯示)/login..之類的,大家可以自行嘗試喔!

end

2015年5月7日 星期四

[iOS] 改變文字顏色,無效?解決方式

在調整UI的時候常常需要改變顏色

可是使用[UIColor colorwithRed:  green: blue: alpha: ]為什麼輸入數值都沒有反應呢?


錯誤示範:[UIColor colorwithRed: 24 green:116 blue:250  alpha:1 ]

正確示範:[UIColor colorWithRed:24.0f/255.0f green:116.0f/255.0f blue:205.0f/255.0f alpha:1.0f];

需要除以255而且他是float喔!

改完以後就會正確顯示顏色了,簡單但是不知道會弄很久的功能!


end

2015年5月6日 星期三

[iOS] Xcode裡面xib檔內的物件改名後產生NSUnknowkeyException的錯誤解決方法

今天在做ios app的時候又發生了一個悲劇....


看到.h檔裡面的英文拼錯,於是就順手改一下...然後就error!!


找了很久以後,才發現錯誤出現在這邊------



看到Referencing Outlets這邊,

這邊是已經修改過的,如果錯誤的話應該會reference到兩個一個是拼錯字的

另一個才是正確的,我們需要把錯誤的按一下連線的那邊有個x,按下去以後就解除reference

這樣錯誤就修改完成囉!


End

2015年4月30日 星期四

[iOS] 如何讓object型態轉換為NSString並顯示在UI上?

今天又遇到讓我卡很久的難題了,一樣把它記錄起來以免日後忘記 .


首先.h檔跟storyboard(或xib檔)連結,h file長這樣:


#import <UIKit/UIKit.h>
#import "AppDelegate.h"
@interface Page1 : UIViewController
@property (weak, nonatomic) IBOutlet UILabel *in_volt;
@property (weak, nonatomic) IBOutlet UILabel *out_volt;
@property (weak, nonatomic) IBOutlet UILabel *load;
@property (weak, nonatomic) IBOutlet UILabel *bat_level;
@property (weak, nonatomic) IBOutlet UILabel *bat_backup_time;
@property (weak, nonatomic) IBOutlet UILabel *ups_status;
@property (weak, nonatomic) IBOutlet UILabel *bat_stauts;
@property (weak, nonatomic) IBOutlet UILabel *power_condition;


@end


step1:

第一步是要讓UILable可以顯示資料

所以很簡單,在要觸發的地方寫下self.(UILabel名稱).text = (nsstring型態);

好了,很顯然第一個問題就是,我們現在是object型態,該怎樣轉NSString呢?

step2:

因為要顯示的是數字,所以先把它轉為int

object to int :

[(NSString *)object  integerValue]

這樣就變成int型態囉!

step3:

轉int還是不能顯示在UILabel上阿!

所以我們還需要再轉一次,這時候使用

[NSString stringWithFormat:@"%d", (int型態)]

但是呢!Xcode會跟你說warning,所以要改成

NSString stringWithFormat:@"%ld", (強制轉換型態成long,就是前面加個(long)這樣)]

完成就長這樣:

self.in_volt.text = [NSString stringWithFormat:@"%ld", (long)[(NSString *)你填入的object型態在這邊 integerValue]];

完成!

end

2015年4月29日 星期三

[iOS] Tab Bar分頁+UDP通訊

不知道怎樣寫分頁或是怎樣做UDP通訊嗎??

最近好不容易弄出了一點樣子,把它記錄起來,以免以後忘記.

首先分頁是使用tab bar元件-GG Tab Bar(https://github.com/Goles/GGTabBar)

,讓分頁切成四塊(同時建立四個.h+.m+.xib檔案)

可以看到有分了Page1,2,3,4分頁,以及對應的xib檔


首先,先在各個page.m裡面新增:


- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.tabBarItem = [[UITabBarItem alloc] initWithTitle:nil
                                                        image:[UIImage imageNamed:@"user_normal"]
                                                selectedImage:[UIImage imageNamed:@"user_pressed"]];
    }
    return self;
}

(image的部份就是要自己找圖或是下載source code,名稱自行調整,但需要對應到Images.xcassets裡面的檔案名稱)


step2: AppDelegate.h+m的部份

AppDelegate.h

#import <UIKit/UIKit.h>

#import "AsyncUdpSocket.h"
#define global ((AppDelegate *)[[UIApplication sharedApplication] delegate])

@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
    AsyncUdpSocket *udpSocket;
    NSTimer *timer;
    long tag;
}
@property (strong, nonatomic) UIWindow *window;
@property (nonatomic,retain) NSMutableArray *globalData;


@end


AppDelegate.m


#import "AppDelegate.h"
#import "GGTabBarController.h"
#import "Page1.h"
#import "Page2.h"
#import "Page3.h"
#import "Page4.h"


@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    NSLog(@"open");
    
    global.globalData = [[NSMutableArray alloc] initWithCapacity:300];
    
    udpSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
    NSError *error = nil;
    [udpSocket bindToPort:2601 error:&error]; //綁定一個port 讓發送的source port / 指定接收的port 都是這一個
    [udpSocket receiveWithTimeout:-1 tag:0];//Start listening for a UDP packet.
    timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(sender) userInfo:nil repeats:YES];
    
    GGTabBarController *tabBar = [[GGTabBarController alloc] init];
    
    Page1 *vc1 = [[Page1 alloc] init];
    Page2 *vc2 = [[Page2 alloc] init];
    Page3 *vc3 = [[Page3 alloc] init];
    Page4 *vc4 = [[Page4 alloc] init];
    
    tabBar.viewControllers = @[vc1, vc2, vc3, vc4];
    self.window.rootViewController = tabBar;
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

//Server端 接收
-(BOOL) onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port
{
    //NSLog(@"in server");
    Byte *convert_to_byte = (Byte *)[data bytes];
    int length = data.length;
    //NSLog(@"length = %d",length);
    int receive[length];
    NSNumber *number;
    NSMutableArray *intArray = [[NSMutableArray alloc] init];
    
    for (int i = 0 ; i < [data length]; i++) {
        //printf("conver to byte = %d\n",convert_to_byte[i]);
        int combine = (int)convert_to_byte[i];
        //NSLog(@"%ld",combine);
        receive[i] = combine;
        number =[NSNumber numberWithInt:combine];
        [intArray addObject:number];
        NSLog(@"number =%@",number);
        //[global.globalData addObject:number];
        //NSLog(@"i=%@",global.globalData[i]);
        
        NSLog(@"%d",receive[i]);//詳細接收
    }
    [global.globalData setArray:intArray];
    [intArray removeAllObjects];
    
    for(int i = 0; i < global.globalData.count; i++){
        NSLog(@"i=%@",[global.globalData objectAtIndex:i]);
    }
    
    NSLog(@"global-data count= %lu",(unsigned long)global.globalData.count);
    
    //receive要解析,
    [udpSocket sendData:data toHost:host port:port withTimeout:-1 tag:0];
    [udpSocket receiveWithTimeout:-1 tag:0];
    return YES;
}


-(void) sender{
    //NSLog(@"timer");
    const unsigned char byte[] = {80,67,77,71,1,69,78,68};
    NSData *data = [NSData dataWithBytes:byte length:sizeof(byte)];
    [udpSocket sendData:data toHost:@"210.202.53.147" port:2601 withTimeout:-1 tag:tag];
}

@end

step3 : 建立udp通訊

這部份在前幾篇有講到附上網址:udp通訊part

(不過這部份已經有寫在上面了)



做完通訊,又有tab bar分頁功能以後,就是把分頁內容建立好囉!

教學到此結束,end.