2014年3月3日 星期一

[Android] 打包, 發佈APK到GooglePlay

打包APK

1. Project (Right Click) > Android Tools > Export Signed Application Package...




2. Click ""Browse" to choose the project we want to export. Then click "Next"


3. Suppose we have keystore already. Enter the password of the keystore.
Keystore可以把它想作是鑰匙圈, 裡面可存放不同名字(Alias)的key. 
通常適用於同一個公司/團體下, 有不同的產品. (一個Keystore多個key)


4. Again, enter the password of the key.


5. Then we will see the key information, and then click "Finish".


發佈APK

Log into Google Play Developer Console > "APK" tab view

That's it~
Evernote helps you remember everything and get organized effortlessly. Download Evernote.

2014年1月21日 星期二

iOS SDK Release Notes for iOS 7.1 beta 4

iOS7.1 beta4今早release了,翻了一下release note跟大家分享一下。

Bluetooth Known Issues 

32-bit apps running on a 64-bit device cannot attach to BTServer.

已知問題32位元的app在iPhone 5S會有藍牙連線的問題,已經beta好幾版都沒有改= =+


CFNetwork Notes

A compatibility behavior has been added to address an issue where some web servers would send the wrong Content-Length value for "Content-Encoding: gzip" content. Previously, NSURLConnection and NSURLSession would send a "network connection was lost" / NSURLErrorNetworkConnectionLost (-1005) error in this situation. The compatibility behavior applies only if the Content-Length value exactly matches the expanded gzip'd content. It won't apply for "off by 1" or similar miscounting.

針對一些網站的 content encoding是 gzip情況下又給了錯誤的Content-Length,有提昇兼容性。
先前NSURLConnection跟NSURLSession會拿到 network connection was lost或是 NSURLErrorNetworkConnectionLost (-1005)的錯誤。
但兼容性的情況僅限於gzip的內容擴展後要與Content-Length一樣才可以。


Messages Fixed in iOS 7.1 beta 4

Messages no longer indicates a send failure immediately after sending.

這版看起來唯一有解掉的就是Message送出訊息不會馬上出現失敗的訊息。


Safari Notes

A property, minimal-ui, has been added for the viewport meta tag key that allows minimizing the top and bottom bars on the iPhone as the page loads. While on a page using minimal-ui, tapping the top bar brings the bars back. Tapping back in the content dismisses them again.
For example, use <meta name="viewport" content="width=1024, minimal-ui">.

meta標籤viewport新增了minimal-ui的屬性,讓Safari載入頁面時可以最小化上下狀態欄,點擊可以再次顯示/隱藏狀態欄。


UIKit Known Issues

Bar button background images are ignored in apps built and deployed to iOS7.1 when they are set using UIBarButtonItem setBackgroundImage:forState:style:barMetrics: with UIBarButtonItemStyleBordered as the style argument.
Workaround: Use UIBarButtonItemStylePlain or UIBarButtonItemStyleAny in this case, or use UIBarButtonItem setBackgroundImage:forState:barMetrics:.

Bar Button背景圖片在使用 setBackgroundImage:forState:style:barMetrics:中類型設定為UIBarButtonItemStyleBordered的時候會失效。
解決方法是設定成 UIBarButtonItemStylePlain或是 UIBarButtonItemStyleAny抑或是使用 setBackgroundImage:forState:barMetrics:

If a UITextField or a UILabel that is baseline aligned with constraints has attributes that change after the constraints have been added, the layout may be incorrect. The exception to this is -setFont: on UILabel, which should work as expected.
Workaround: Avoid making changes in UITextField or UILabel after adding baseline-alignment constraints. If you must make changes, you should remove the constraints and then reapply them afterward. Note that this is a performance hit, so don't do it unless it is necessary.

UITextField跟UILabel如果設定了baseline aligned之後再設定其他屬性,這樣會使得layout錯誤。(除了UILabel設定字型是沒問題的)
目前要避免這樣的問題就是要調整先後順序,把baseline aligned放到最後設定。

The backIndicatorTransitionMaskImage from a storyboard or a xib will not be interpreted correctly at runtime.
Workaround: Set the backIndicatorTransitionMaskImage in code.

導航欄的按鈕圖案若是透過storyboard或是xib去設定的會無法作用,解決方法就是手動在code裡面設定

Sent from Evernote

2013年12月12日 星期四

iOS App 串接 Dropbox API第一次就上手

前言
最近發現我好飢渴阿(大誤!)
很多網路服務API都很有趣, 也很完整, 高手滿坑滿谷.
就像Steve Jobs說的 'stay hungry stay foolish'
今天就來玩玩Dropbox的API吧~


申請APP帳號
Dropbox開發者首頁(Link)
左側有App Console的標籤, 點擊然後選擇Create app.

> 要先同意使用者條款跟隱私權政策


> 然後要選擇app的類型.
1. 先選右邊的Dropbox API app
2. 然後選擇Files and datastores (注意!選Datastores only沒法對data做access動作!)
    就像這位仁兄遇到的問題一樣.
3. 我只允許我的app access自己app所建立的資料夾
4. 設定一下app名稱 (之後還可以更改)


> 建立完成, 複製App key以及App secret等等要用.


> 一切就緒, 讓我們切換到Core API的標籤頁, 點選Install SDK


先從Example Project試試
剛剛下載的iOS SDK裡面有個examples > DBRoulette 開啟DBRoulette.xcodeproj
把剛剛的App key跟App secret 貼到 DBRouletteAppDelegate.m
注意!root = kDBRootAppFolder/kDBRootDropbox 不要用預設的nil
不然跑起來會有錯誤訊息:
[WARNING] DropboxSDK: error making request to /1/metadata/(null) - (400) Expected 'root' ...

然後DBRoulette-Info.plist右鍵點選Open as > Source code
注意!db-(your app key) 記得保留'db-' .

設定完成來執行看看吧!

一開始可能會有一堆錯誤視窗跑出來.
因為資料夾是空的呀~不過登入自己的Dropbox可以發現.

Dropbox有建立了一個新的資料夾了, 丟一些照片進去就大功告成了!
下台一鞠躬, 謝謝大家XD
Sent from Evernote

2013年12月11日 星期三

iOS App share with Google Plus

前言
Google Plus的分享功能要加到iOS專案裡面不會太困難.
官方網站的原文教學

環境設定
下載Google+ iOS SDK (official link)
檢查一下
AssetsLibrary.framework
Foundation.framework
CoreLocation.framework
CoreMotion.framework
CoreGraphics.framework
CoreText.framework
MediaPlayer.framework
Security.framework
SystemConfiguration.framework
UIKit.framework

並從下載回來的Google+ iOS SDK資料夾內
拖曳&import
GooglePlus.framework
GoogleOpenSource.framework



建立一個API project
舊版的設定頁面


註冊一個app


完成後應該長得像這樣


新版的設定頁面
啟用Google+API


註冊一個app


填寫必要資訊


完成後應該長得像這樣



程式
在AppDelegate.m

#import 
#import  
static NSString * const kClientID = @"blahblahblah.apps.googleusercontent.com";

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Set app's client ID for |GPPSignIn| and |GPPShare|.
    [GPPSignIn sharedInstance].clientID = kClientID;
    ...
}

在ViewController.m
@interface YourViewController ()  {
     ...
- (void)viewDidLoad {
     [super viewDidLoad];
     [GPPShare sharedInstance].delegate = self;
}
     ...
- (void)gplusBtnPressed:(id)sender {   
    id shareBuilder = [[GPPShare sharedInstance] shareDialog];
   
    // This line will fill out the title, description, and thumbnail of the item
    // you're sharing based on the URL you included.
    //[shareBuilder setURLToShare:[NSURL URLWithString:@"The url you want to share"]];
    [shareBuilder setContentDeepLinkID:@"DeepLinkID"];
    [shareBuilder setTitle:@" 標題 "
               description:@" 描述"]
              thumbnailURL:[NSURL URLWithString:[@"縮圖網址"]]];

    [shareBuilder setPrefillText:msg];
    [shareBuilder open];
}

#pragma mark - GPPShareDelegate
- (void)finishedSharing:(BOOL)shared {
   
}

- (void)reportAuthStatus {
    if ([GPPSignIn sharedInstance].authentication) {
        NSLog(@"Status: Authenticated");
    } else {
        // To authenticate, use Google+ sign-in button.
        NSLog(@"Status: Not authenticated");
    }
}

如果分享時發生Error 404 Not Found, 那最有可能就是client ID沒有符合

希望大家都分享順利囉~
Sent from Evernote

[Android] share with Facebook SDK 3.5

前言
原本在開發者沙盒(SandBox)模式下一切都還滿順利的,
不料上到Google Play發現原本的功能不work, 
花了一些時間才發現小細節.
自己記錄一下, 同時也給需要的人參考一下.

以下我就自己的開發歷程, 
先從沙盒模式說起, 
最後再談關閉沙盒模式要注意的地方.


下載&Import FaceBook SDK
可以參考官方文件的原文教學
我是用SDK 3.5.2 (Official Download Link / Github SDK3.6)

I'll skip the installation of Facebook in emulator here.

> Right click / 'File' on top

> Existing Android Code Into Workspace

> make sure the 'facebook' project is checked

如果Project有Error可以先檢查android-support-v4.jar的版本是否一致
最快的方法就是把最新的jar在project list裡面copy起來,
然後把其他project有用到的都先delete掉, 再paste上去.


環境設定
接下來看看我們的project要做哪些設定
1. library

2. Manifest設定
     
     
        
    

3. res/values/strings.xml加上
(your Facebook App ID)


Facebook上建立應用程式後, copy App ID

4. 在Facebook App設定頁面加上Hash Key
Mac User
keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64



程式 - Facebook分享
// facebook
private static final String PERMISSION = "publish_actions";
private UiLifecycleHelper uiHelper;
private boolean canPresentShareDialog;
private PendingAction pendingAction = PendingAction.NONE;
private enum PendingAction {
     NONE,
    POST_PHOTO,
    POST_STATUS_UPDATE
}

// Facebook Login
Session.openActiveSession(this, true, new Session.StatusCallback()
{
     // callback when session changes state
     @Override
     public void call(final Session session, SessionState state, Exception exception)
     {
          if (session.isOpened())
          {   
               // make request to the /me API
               Request request = Request.newMeRequest(session, new Request.GraphUserCallback()
               {
                    @Override
                    public void onCompleted(GraphUser user, Response response)
                    {
                         // If the response is successful
                        Log.d("facebook", "GraphUserCallback" + user.getId()+" " + response.toString());
                                        
                        if (session == Session.getActiveSession())
                        {
                              if (user != null)
                             {
                                   performPublish(PendingAction.POST_STATUS_UPDATE, canPresentShareDialog);
                             }
                        }
                                        
                        if (response.getError() != null)
                        {
                              // Handle errors, will do so later.
                        }
                     }
               });
               request.executeAsync();
          }
     }
});

private void performPublish(PendingAction action, boolean allowNoSession) {
     Session session = Session.getActiveSession();
    if (session != null) {
        pendingAction = action;
        if (hasPublishPermission()) {
               // We can do the action right away.
            handlePendingAction();
            return;
        } else if (session.isOpened()) {
            // We need to get new permissions, then complete the action when we get called back.
            session.requestNewPublishPermissions(new Session.NewPermissionsRequest(this, PERMISSION));
            return;
          }
    }

    if (allowNoSession) {
          pendingAction = action;
        handlePendingAction();
     }
}
    
@SuppressWarnings("incomplete-switch")
private void handlePendingAction() {
    PendingAction previouslyPendingAction = pendingAction;
    // These actions may re-set pendingAction if they are still pending, but we assume they
    // will succeed.
    pendingAction = PendingAction.NONE;

    switch (previouslyPendingAction) {
          case POST_PHOTO:
               //postPhoto();
            break;
        case POST_STATUS_UPDATE:
            postStatusUpdate();
            break;
    }
}
    
private FacebookDialog.ShareDialogBuilder createShareDialogBuilder() {
    return new FacebookDialog.ShareDialogBuilder(this)
          .setName("fb app name")
        .setDescription("app description")
        .setLink("site link");
}
    
private void postStatusUpdate() {
     if (canPresentShareDialog) {
        FacebookDialog shareDialog = createShareDialogBuilder().build();
        uiHelper.trackPendingDialogCall(shareDialog.present());
    } else if (hasPublishPermission()) {
        Bundle params = new Bundle();
        params.putString("name", " link主標題 ");
        params.putString("caption", " link副標題 ");
        params.putString("message", " 描述 ");
        params.putString("link", " 分享連結 ");
        params.putString("picture", " 圖片url ");

        Request request = new Request(Session.getActiveSession(), "me/feed", params, HttpMethod.POST);
        request.setCallback(new Request.Callback() {
               @Override
             public void onCompleted(Response response) {
                    showPublishResult(null, response.getGraphObject(), response.getError());
             }
        });
        request.executeAsync();
     } else {
          pendingAction = PendingAction.POST_STATUS_UPDATE;
    }
}
    
private void showPublishResult(String message, GraphObject result, FacebookRequestError error) {
     String title = null;
    String alertMessage = null;
    if (error == null) {
          title = getString(R.string.success);
        alertMessage = getString(R.string.successfully_posted_post);
    } else {
        title = getString(R.string.error);
        alertMessage = error.getErrorMessage();
    }

    new AlertDialog.Builder(this)
          .setTitle(title)
        .setMessage(alertMessage)
        .setPositiveButton(R.string.ok, null)
        .show();
}

@Override
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {  
    // fb 登入結果
    Session.getActiveSession().onActivityResult(this, requestCode, responseCode, intent);
}


正式版本
1. Facebook APP設定頁面一定要把SandBox mode關閉

2. 確認Android app package name
> Export Signed Application Package

> KeyStore path別忘記副檔名.keystore !

> 輸入key的資訊 (一個keystore可以有很多把keys), Alias就是key的名稱

3. 複製正式版本的hashed key (建議在keystore的目錄下)
keytool -exportcert -alias (key的名稱) -keystore (keystore名稱).keystore | openssl sha1 -binary | openssl base64

這樣submit的正式版app就能夠正常分享資訊到Facebook啦!

Sent from Evernote

2013年12月4日 星期三

在iOS app用webview播放YouTube影片

前言
如果要直接launch YouTube app來播放, 那需要URL scheme:
  • youtube://
  • http://www.youtube.com/v/VIDEO_IDENTIFIER
  • http://www.youtube.com/watch?v=VIDEO_IDENTIFIER
今天我需要用嵌入webview 方式播放YouTube影片來提供比較好的使用者體驗:D



實作
原理就是用webview 的loadHTMLString 方法來讀取我們assign好的HTML內容.
廢話不說, 直接上code!
webplayer = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    webplayer.scalesPageToFit = YES;
    webplayer.delegate = self;
    [self.view addSubview:webplayer];
    NSString *videoURL = [NSString stringWithFormat:@"http://www.youtube.com/embed/%@", youtubeID];
    NSString *videoHTML = [NSString stringWithFormat:@"\
                 \
                 \
                 \
                 \
                 \
                 \
                 \
                 ", videoURL];
    [webplayer loadHTMLString:videoHTML baseURL:nil];
    webplayer.backgroundColor = [UIColor blackColor];
    webplayer.opaque = NO;



重點一
如果是使用xib來製作webplayer 那可以直接把delegate給定

不然就是在.m
webplayer.delegate = self;
以及在.h 加上
@interface webPlayerViewController : UIViewController <UIWebViewDelegate> 


重點二
videoURL 是 http://www.youtube.com/embed/(youtubeID)
不是一般網址
https://www.youtube.com/watch?v=b1aHBlaC0de
也不是分享用的縮址
http://youtu.be/b1aHBlaC0de
舊版的嵌入網址也不適用
www.youtube.com/v/b1aHBlaC0de?version=3&amp;hl=zh_TW&amp;rel=0


最後重點
HTML 樣式的調整, 可以觀察一下NSString中一些跳脫字元的使用方式.
另外, 我們可以加上一個按鈕來關閉這頁.
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" 
         style:UIBarButtonItemStylePlain 
         target:self 
         action:@selector(onClickedDone:)];
self.navigationItem.rightBarButtonItem = doneButton;
[doneButton release];

- (void)onClickedDone:(id)sender {
    [webplayer release];
    webplayer = nil;
    //popViewController or dismissViewController
}


參考連結: MightyMeta
Sent from Evernote     

2013年11月21日 星期四

iOS7 UITableViewCell imageView offset issue

前言
iOS7的新界面風格確實給UX設計師跟工程師帶來不少困擾,
尤其是UITableView的layout變動讓我花了不少時間去調整。

問題
我在cell.imageView裡頭放的圖片位置跑掉了。

嘗試
// Not work 1.
[cell.imageViewsetFrame:CGRectOffset(cell.imageView.frame,-15,0)];

// Not work 2.
[tableViewsetContentOffset:CGPointMake(-15,0)];

// Not work 3.
if([selfrespondsToSelector:@selector(edgesForExtendedLayout)])
 self.edgesForExtendedLayout=UIRectEdgeNone;
 
// Not work 4.
if([mainTablerespondsToSelector:@selector(setSeparatorInset:)])
 [tableViewsetSeparatorInset:UIEdgeInsetsZero];
 
// Not work 5.
if([mainTablerespondsToSelector:@selector(setContentInset:)])
 [tableViewsetContentInset:UIEdgeInsetsZero];

實作
解決方法要點就是要實作custom cell.
第二點就是在custom cell的.m裡面 overwrite layoutSubviews 這個function.
因為只有iOS7會跑版, 所以多加個判斷式檢查.
#define IOS_SEVEN ([[UIDevice currentDevice].systemVersion floatValue] >= 7)

- (void)layoutSubviews{
 [superlayoutSubviews];
 if(IOS_SEVEN){
  self.imageView.frame=CGRectOffset(self.imageView.frame,-15,0);
 }
}

Sent from Evernote

內容回應