如何生成管道NSData

时间:2015-06-25 02:20:39

标签: ios objective-c nsdata

我在cachedResponseForRequest:拦截了AJAX请求,然后为请求构建了自定义响应。但似乎这个API方法总是在同一个线程上工作,所以如果我做了一个耗时的操作,新的请求将被阻止。在Android中,我使用PipedStream解决了这个问题,但是cachedResponseForRequest:返回了NSData的响应,如何让NSData变为pipable,任何人都可以帮助我

这是我的代码:

- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request
{
    NSURL *url=request.URL;
    NSCachedURLResponse *response=nil;
    if([url.path containsString:@"aa1"]){
        NSMutableData *data=[NSMutableData data];
        NSThread* asyncThread = [[NSThread alloc] initWithTarget:self selector:@selector(getData:) object:data];
        [asyncThread start];
        NSURLResponse *urlresponse=[[NSURLResponse alloc] initWithURL:url MIMEType:@"application/json" expectedContentLength:data.length textEncodingName:@"utf-8"];
        response=[[NSCachedURLResponse alloc] initWithResponse:urlresponse data:data];

    }
    return response;
}

-(void)getData:(NSMutableData*)data{
    NSMutableString *str=[NSMutableString stringWithString:@""];
    for(int i=0;i<1024*1024;i++){
        [str appendFormat:@"s"];
    }
    [data appendData:[str dataUsingEncoding:NSUTF8StringEncoding]];
    NSLog(@"%d",data.length);
}

而在Android中,我解决了这个问题,如关注

public WebResourceResponse shouldInterceptRequest(WebView view,
            String url) {
    WebResourceResponse response = null;
    if (url.contains("loca/aa0")) {
        try {
            final PipedOutputStream out = new PipedOutputStream();
            InputStream in = new PipedInputStream(out);
            AsyncTask<String, Integer, String> task = new AsyncTask<String, Integer, String>() {
                @Override
                protected String doInBackground(String... params) {
                    // TODO Auto-generated method stub
                    try {
                        InputStream s = ctx.getAssets().open("s.txt");
                        byte[] buffer = new byte[100];
                        while (s.read(buffer) != -1)
                            out.write(buffer);
                        out.flush();
                        out.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return null;
                }
            };
            task.execute();
            response = new WebResourceResponse("application/html","UTF-8", in);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return response;
}

任何人都可以看到我的问题吗?

0 个答案:

没有答案