[jQuery]$.ajaxでcookieも送信

$.ajaxでcookieも送信
IE10未満は不可

$.ajax({
    type:'post',
    url:'url',
    dataType:'text',
    data:data,
    crossDomain:true,
    cache:false,
    xhrFields: {
        withCredentials:true
    },
    success:function(data, dataType){
        
    },
    error:function(XMLHttpRequest, textStatus, errorThrown){
        
    },
    complete:function(){
        
    }
});

[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;
}