문제

I have a method like this. It works fine when my device is connected through wifi network, but when it is connected through 3G network it freezes my app for some seconds. So, because it is an interactive app, when it does some various post request it must continuing running so the user can continue to use the app. Any solution for this ?

I tried reducing the [theRequest setTimeoutInterval:2.0]; but that didn't fix my problem.

// post request
    - (void)postRequestWithURL:(NSString *)url 
                                body:(NSString *)body 
                         contentType:(NSString *)contentType 
                             options:(NSDictionary *)dict
    {
        // set request
        NSURL *requestURL = [NSURL URLWithString:url];
        NSMutableURLRequest *theRequest = [[NSMutableURLRequest alloc] init];


        if([dict count] > 0)
        {
            for (id key in dict) {
                NSLog(@"[theRequest addValue:%@ forHTTPHeaderField:%@]", [dict valueForKey:key], key);
                [theRequest addValue:[dict valueForKey:key] forHTTPHeaderField:key];
            }
        }

        if (contentType != nil) {
            [theRequest addValue:contentType forHTTPHeaderField:@"Content-type"];
        }

        [theRequest setURL:requestURL];
        [theRequest setTimeoutInterval:2.0];
        [theRequest setHTTPMethod:@"POST"];
        [theRequest setHTTPBody:[body dataUsingEncoding:NSASCIIStringEncoding]];
        [self.oauthAuthentication authorizeRequest:theRequest];
        // make request
        //responseData = [NSURLConnection sendSynchronousRequest:theRequest 
        //                                   returningResponse:&response 
        //                                               error:&error]; 

        NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];
        self.web = conn;

        [conn release];

        NSLog(@"########## REQUEST URL: %@", url);




        // request and response sending and returning objects
    }
도움이 되었습니까?

해결책

It's freezing your app because you have told it to. You have passed YES into startImmediately. This means that it will start the connection on that thread and wait until it's finished. I guess the thread you're doing this on will be the main thread - the one that also handles the ui etc :)

You need to use something like connectionWithRequest:delegate: - this will run the request in the background and tell you when it's done.

PS The reason you didn't spot the bug in wifi is because the data was sent so fast you couldn't notice the pause in your app :)

PPS The reason the timeout didn't fix it is because the request wasn't timing out - it was just getting data very slowly :)


EDIT

Something like this :

self.web = [NSURLConnection connectionWithRequest:request delegate:self];
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top