objective-c

[objective-c]UIScrollViewのスクロール先のページインデックスを取得

pagingEnabled=YESのUIScrollViewのスクロール先のページインデックスを取得

ヘッダーファイル

<UIScrollViewDelegate>

メインファイル

-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    CGFloat width = scrollView.frame.size.width;
    NSInteger page = (targetContentOffset->x + (0.5f * width)) / width;
    int index=(int)page;   
}

[objective-c]performSelectorの警告を消す

performSelectorの警告を消す

#define SuppressPerformSelectorLeakWarning(Stuff) \
do { \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Warc-performSelector-leaks\"") \
Stuff; \
_Pragma("clang diagnostic pop") \
} while (0)

if (_delegate && _selector && [_delegate respondsToSelector:_selector]) {
    SuppressPerformSelectorLeakWarning([_delegate performSelector:_selector withObject:[NSNumber numberWithBool:success]]);
}

[objective-c]フォルダを作る

フォルダを作る

-(BOOL)makeDir:(NSString*)dirPath
{
    NSString* path=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    path=[path stringByAppendingPathComponent:dirPath];
    NSError *error;
    BOOL result = [[NSFileManager defaultManager] createDirectoryAtPath:path
                                            withIntermediateDirectories:YES
                                                             attributes:nil
                                                                  error:&error];
    return result;
}

[self makeDir:@"test1/test2/jack"];

上記を実行すると下記の3つのフォルダが作られる。
test1
test1/test2
test1/test2/jack

[objective-c]ファイル、フォルダ削除

ファイル、フォルダ削除

-(BOOL)removeFileByPath:(NSString*)filePath
{
    NSString* path=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    path=[path stringByAppendingPathComponent:filePath];
    NSFileManager *fm = [NSFileManager defaultManager];
    NSError *error=nil;
    BOOL flg=[fm fileExistsAtPath:path];
    if (!flg) {
        NSLog(@"no file");
        return YES;
    }
    
    return [fm removeItemAtPath:path error:&error];
}

[objective-c]NSURLConnection::sendAsynchronousRequest

NSURLConnection::sendAsynchronousRequest

NSURL *url = [NSURL URLWithString:_url];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"GET"];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    NSLog(@"complete");
    int statusCode = ((NSHTTPURLResponse *)response).statusCode;
    NSLog(@"%d", statusCode );
}];

[objective-c]NSURLConnectionでファイルダウンロード

NSURLConnectionでファイルダウンロード

ヘッダーファイル

__strong NSMutableData *mData;
long long filesize;
float downloadedPercentage;

メインファイル


-(NSURLConnection*)exeHttpGetWithURL:(NSString*)_url queryString:(NSString*)_getQueryString delegate:(id)delegate
{
    NSString *url=(_getQueryString)?[NSString stringWithFormat:@"%@?%@",_url,_getQueryString] : _url;
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];   
    //送信
    return [[NSURLConnection alloc] initWithRequest:request delegate:delegate];
}

/**
 認証
 **/
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    //basic認証のid,passを求められたら
    if ([challenge previousFailureCount] == 0) {
        NSURLCredential *newCredential = [NSURLCredential credentialWithUser:@"userID"
                                                                    password:@"password"
                                                                 persistence:NSURLCredentialPersistenceForSession];
        [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
        
    }else {
        //認証失敗
        NSLog(@"failure");
        [self hideDownloading];
    }
}

/**
レスポンスあり
 **/
- (void)connection: (NSURLConnection*) connection didReceiveResponse: (NSHTTPURLResponse*) response
{
    int statusCode = (int)[response statusCode];
    NSLog(@"statusCode:%d",statusCode);
    
    //成功
    if (statusCode == 200) {
        filesize = [response expectedContentLength];
        return;
    }
    
    //失敗
    [self hideDownloading];
    UIAlertView*alert=[[UIAlertView alloc]initWithTitle:@"Error" message:@"問題が発生しました。\n・URLが間違っている\n・サーバに障害が発生している\n・ネットワークがつながっていない" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
    [alert show];
}

/**
 データ受信
 受信データが大きいときは一回で全データを取得できないので、mDataにappendDataしておく
 **/
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    if (data) {
        [mData appendData:data];
        downloadedPercentage = ((float)[mData length] / (float)filesize);

        [self updateDownloading:downloadedPercentage];
    }
}

/**
 データ受信完了
 **/
- (void) connectionDidFinishLoading:(NSURLConnection *)connection{
    [self saveData2FileAsync:mData filename:@"testfile.zip" delegate:self selector:@selector(onFileSaved:)];
    
}
-(void)onFileSaved:(NSNumber*)num
{
    mData=nil;
    BOOL success = [num intValue]==1;
    NSLog(@"onFileSaved success:%d",success);
    [self hideDownloading];
}

// ローカルにデータを保存
- (void)saveData2File:(NSData *)data filename:(NSString*)filename
{
    NSString* dataPath=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    dataPath=[dataPath stringByAppendingPathComponent: filename ];
    BOOL success = [data writeToFile:dataPath atomically:YES];
    if (success) {
        
    }else{
        [self showSaveFailedAlert];
    }
}
- (void)saveData2FileAsync:(NSData *)data filename:(NSString*)filename delegate:(id)_delegate selector:(SEL)_selector
{
    NSString* dataPath=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    dataPath=[dataPath stringByAppendingPathComponent: filename ];
    
    dispatch_queue_t main=dispatch_get_main_queue();
    dispatch_queue_t sub=dispatch_queue_create("net.ktyr.sample", NULL);
    dispatch_async(sub, ^{
        BOOL success = [data writeToFile:dataPath atomically:YES];
        dispatch_async(main, ^{
            if (success) {
                
            }else{
                [self showSaveFailedAlert];
            }
            if (_delegate && _selector && [_delegate respondsToSelector:_selector]) {
                [_delegate performSelector:_selector withObject:[NSNumber numberWithBool:success]];
            }
        });
    });
}
-(void)showSaveFailedAlert
{
    UIAlertView*alert=[[UIAlertView alloc]initWithTitle:@"Failed to save file" message:@"ファイルの保存に失敗しました" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
    [alert show];
}


-(IBAction)onTapButton:(UIButton*)sender
{
    mData=[[NSMutableData alloc]init];
    filesize=0.0;
    downloadedPercentage=0.0;
    [self showDownloading];
    
    //ダウンロード開始
    [self exeHttpGetWithURL:url_tf.text queryString:nil delegate:self];
}


-(void)showDownloading
{
    loadingView.hidden=NO;
    loadingLable.text=@"0%";
    loadingPV.progress=0.0;
}
-(void)updateDownloading:(float)percentage
{
    loadingLable.text=[NSString stringWithFormat:@"%d%%",(int)(percentage*100.0)];
    loadingPV.progress=percentage;
}
-(void)hideDownloading
{
    loadingView.hidden=YES;
}

[objective-c]Get,Postリクエスト

Get,Postリクエスト

objective-c
ヘッダーファイル

__strong NSMutableData*mData;

メインファイル

-(NSString*)getQueryStringByDic:(NSDictionary*)dic
{
    NSArray*keys = [dic allKeys];
    NSMutableArray*tmp=[NSMutableArray array];
    for (NSString*key in keys) {
        [tmp addObject:[NSString stringWithFormat:@"%@=%@",key,dic[key]]];
    }
    return [tmp componentsJoinedByString:@"&"];
}
-(NSString*)getEncodedQueryStringByDic:(NSDictionary*)dic
{
    NSArray*keys = [dic allKeys];
    NSMutableArray*tmp=[NSMutableArray array];
    for (NSString*key in keys) {
        NSString*value = dic[key];
        [tmp addObject:[NSString stringWithFormat:@"%@=%@",key,[value stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet alphanumericCharacterSet]] ]];
    }
    return [tmp componentsJoinedByString:@"&"];
}
-(NSString*)getDatetimeFromDate:(NSDate*)date
{
    NSDateFormatter* form = [[NSDateFormatter alloc] init];
    NSCalendar* cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    [form setCalendar: cal];
    [form setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString* str = [form stringFromDate:date];
    return str;
}

/**
 返り値はNSArrayまたはNSDictionary
 **/
-(id)getDataByJsonString:(NSString*)jsonString{
    NSData *json_data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError*tmp=nil;
    id data = [NSJSONSerialization JSONObjectWithData:json_data options:NSJSONReadingAllowFragments error:&tmp];
    if (tmp) {
        return nil;
    }
    return data;
}

-(NSURLConnection*)exeHttpGetWithURL:(NSString*)_url queryString:(NSString*)_getQueryString delegate:(id)delegate
{
    
    NSString *url=[NSString stringWithFormat:@"%@?%@",_url,_getQueryString];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    
    //送信
    return [[NSURLConnection alloc] initWithRequest:request delegate:delegate];
}

-(NSURLConnection*)exeHttpPostWithURL:(NSString*)_url queryString:(NSString*)_postQueryString delegate:(id)delegate
{
    //リクエスト設定
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:_url]];
    [request setHTTPMethod:@"POST"];
    [request setCachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
    [request setTimeoutInterval:20];
    [request setHTTPShouldHandleCookies:FALSE];
    NSData*httpBody=[_postQueryString dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:httpBody];
    
    //送信
    return [[NSURLConnection alloc] initWithRequest:request delegate:delegate];
}

/**
 認証
 **/
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    //basic認証のid,passを求められたら
    if ([challenge previousFailureCount] == 0) {
        NSURLCredential *newCredential = [NSURLCredential credentialWithUser:@"userID"
                                                                    password:@"password"
                                                                 persistence:NSURLCredentialPersistenceForSession];
        [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
        
    }else {
        //認証失敗
        NSLog(@"failure");
    }
}

/**
 データ受信
 受信データが大きいときは一回で全データを取得できないので、mDataにappendDataしておく
 **/
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    
    if (data) {
        [mData appendData:data];
    }
}

/**
 データ受信完了
**/
- (void) connectionDidFinishLoading:(NSURLConnection *)connection{
    NSString*jsonString=[[NSString alloc] initWithData:mData encoding:NSUTF8StringEncoding];
    mData=nil;
    id json=[self getDataByJsonString:jsonString];
    
    //NSDictionaryのとき
    if ([json isKindOfClass:[NSDictionary class]]) {
        NSLog(@"NSDictionary\n%@", [json description]);
        
    //NSArrayのとき
    }else if([json isKindOfClass:[NSArray class]]){
        NSLog(@"NSDictionary\n%@", [json description]);
        
    }
}

-(IBAction)onTapButton:(UIButton*)sender
{
    mData=[[NSMutableData alloc]init];
    NSString*url=@"/php/50/index.php";
    NSMutableDictionary*dic=[NSMutableDictionary dictionary];
    dic[@"datetimeOfSend"]=[self getDatetimeFromDate:[NSDate date]];
    dic[@"message"]=@"あいうえお";
    
    switch ((int)sender.tag) {
        case 0://GET
            [self exeHttpGetWithURL:url queryString:[self getEncodedQueryStringByDic:dic] delegate:self];
            break;
        case 1://POST
            [self exeHttpPostWithURL:url queryString:[self getQueryStringByDic:dic] delegate:self];
            break;
        default:
            break;
    }
}

php

$tmp=array("yourData" => "none" );
if(!empty($_GET)){
	$tmp["yourData"]=$_GET;
	$tmp["method"]="GET";
}else if(!empty($_POST)){
	$tmp["yourData"]=$_POST;
	$tmp["method"]="POST";
}
$tmp["datetime"]=date("Y-m-d H:i:s");
$tmp["randomStr"]=getRandomStr(48);
$tmp["name"]="john";
$tmp["place"]="newyork";
$tmp["device"]="iPhone5s";

header("Content-Type: application/json; charset=utf-8");
echo json_encode($tmp);
exit;

function getRandomStr($length=8){
	$str='';
	for ($i = 0, $str = null; $i < $length; ) {
		$num = mt_rand(0x30, 0x7A);
		if ((0x30 <= $num && $num <= 0x39) || (0x41 <= $num && $num <= 0x5A) || (0x61 <= $num && $num <= 0x7A)) {
			$str .= chr($num);
			$i++;
		}
	}
	return $str;
}

NSLogの結果 GET

NSDictionary
{
    datetime = "2014-04-11 14:37:28";
    device = iPhone5s;
    method = GET;
    name = john;
    place = newyork;
    randomStr = aepa0FUQzn2hOJbB7mwzDztUzpE0FuV5kyihl8t90LQSfNoa;
    yourData =     {
        datetimeOfSend = "2014-04-11 14:37:28";
        message = "\U3042\U3044\U3046\U3048\U304a";
    };
}

NSLogの結果 Post

NSDictionary
{
    datetime = "2014-04-11 14:40:43";
    device = iPhone5s;
    method = POST;
    name = john;
    place = newyork;
    randomStr = if7wIKtiAIxgJ32GzIlXOPOvzmokZYR6emlJhIpDvmlO8F2S;
    yourData =     {
        datetimeOfSend = "2014-04-11 14:40:43";
        message = "\U3042\U3044\U3046\U3048\U304a";
    };
}

[objective-c]NSDictionaryをクエリ文字列にする

NSDictionaryをクエリ文字列にする

-(NSString*)getQueryStringByDic:(NSDictionary*)dic
{
    NSArray*keys = [dic allKeys];
    NSMutableArray*tmp=[NSMutableArray array];
    for (NSString*key in keys) {
        [tmp addObject:[NSString stringWithFormat:@"%@=%@",key,dic[key]]];
    }
    return [tmp componentsJoinedByString:@"&"];
}
-(NSString*)getEncodedQueryStringByDic:(NSDictionary*)dic
{
    NSArray*keys = [dic allKeys];
    NSMutableArray*tmp=[NSMutableArray array];
    for (NSString*key in keys) {
        NSString*value = dic[key];
        [tmp addObject:[NSString stringWithFormat:@"%@=%@",key,[value stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet alphanumericCharacterSet]] ]];
    }
    return [tmp componentsJoinedByString:@"&"];
}
-(IBAction)onTapButton:(id)sender
{
    NSMutableDictionary*dic=[NSMutableDictionary dictionary];
    dic[@"id"]=@"285";
    dic[@"name"]=@"jeff";
    dic[@"place"]=@"newyork";
    dic[@"version"]=@"iOS7.1";
    
    NSLog(@"%@", [self getQueryStringByDic:dic] );
}

結果

place=newyork&id=285&name=jeff&version=iOS7.1

[objective-c]UIWebViewのリンクタップ制御

UIWebViewのリンクタップ制御
ヘッダーファイル

<UIWebViewDelegate>

メインファイル

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if(navigationType == UIWebViewNavigationTypeLinkClicked) {
        NSString*url=[[request URL]absoluteString];
	NSLog(@"url : %@", url);
	//Safariで開く
        [[UIApplication sharedApplication] openURL:[request URL]];
    }
    return YES;
}