如何在iOS中在后台运行NSURLConnection [英] How to run a NSURLConnection in background in iOS

查看:89
本文介绍了如何在iOS中在后台运行NSURLConnection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用待办事项列表组织者的应用程序,用户可以在其中添加注释.我正在使用coredata DB来存储注释.当我提供同步功能时,我正在将JSON数据解析到服务器,还从服务器获取JSON数据.
我正在使用NSURLConnection API及其委托函数

I am working with an app which is todo list organizer, where user adds notes. I am using coredata DB to store the notes. As I am providing sync feature, I am parsing JSON data to server, and also getting JSON data from server.
I am using NSURLConnection API and its delegate functions

- (void)pushData
{
      loop through the notes array and send notes 1 by one

       [[request setValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Content-Type"];

            [request setHTTPMethod:@"POST"];
            [request setHTTPBody:jsonData];

            m_dataPush = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];

            [m_dataPush start];
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{
      Process response from server, save to core DB
      and again pushData if any modified and again process the response
}

我在appEnterBackground和appBecomeActive上调用此API,因为我希望在多个设备上更新数据.

I call this API, on appEnterBackground and appBecomeActive, because, I want the data to updated on multiple devices.

我面临的问题是

1)当笔记更多时,应用卡住了,当我们退出并打开应用并开始添加笔记时.

1) When the notes are more, app is getting stuck, when we exit and open the app and start adding notes.

2)我尝试使用GCD,但随后我的NSURLConnection没有向我发送任何响应

2) I tried using GCD, but then my NSURLConnection doesnot send me any response

问候 兰吉特

推荐答案

Ranjit:根据您在不同响应中的评论,我怀疑您是从主线程发送第一个请求.收到第一个响应后,您将在后台对其进行处理,然后也从后台发送第二个请求.后续请求应从主线程发送

Ranjit: Based on your comments in the different responses, I suspect you are sending the 1st request from the main thread. When you receive the 1st response, you process it in the background, and then send the 2nd request also from the background. The subsequent requests should be sent from the main thread

[self performSelectorOnMainThread:@selector(myMethodToOpenConnection:)
                       withObject:myObject
                    waitUntilDone:NO];

否则,线程将在调用委托之前退出

otherwise the thread exits before the delegate is called

这篇关于如何在iOS中在后台运行NSURLConnection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆