2011-11-14 1 views
4

iphoneのobjective-cでアプリを開発しています。私の問題は、私のアプリケーションがURLから取得した画像を保存しなければならないことです。フォルダは、唯一の私は。これは、画像を保存するための私のコードだと思い読まれる:Objective-cのアプリのリソースフォルダにファイルを保存するには

-(void)banner:(NSString *)path{ 
    NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: path]]; 
    UIImage *image = [UIImage imageWithData: imageData]; 
    NSString* resourcePath = [[NSBundle mainBundle] resourcePath]; 
    NSString* pathEnd = [resourcePath stringByAppendingFormat:@"/banner.png"]; 
    NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)]; 
    NSError *writeError = nil; 
    [data1 writeToFile:pathEnd options:NSDataWritingAtomic error:&writeError]; 
} 

が、私は、画像を取得するとき、それはそのフォルダにありません。私に何ができる?

答えて

7

できません。アプリケーションバンドルは読み取り専用です。ドキュメントまたはキャッシュディレクトリのいずれかにすべてのデータを保存する必要があります。

-(void)banner:(NSString *)path{ 
    NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: path]]; 
    UIImage *image = [UIImage imageWithData: imageData]; 

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); 
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"banner.png"]; 

    NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)]; 
    NSError *writeError = nil; 

    [data1 writeToFile:filePath options:NSDataWritingAtomic error:&writeError]; 

    if (writeError) { 
     NSLog(@"Error writing file: %@", writeError); 
    } 
} 

再びNSData対象に第一及びバック画像をデータを変換する理由はありますか?

あなただけのこの操作を行うことができない場合は、次の

-(void)banner:(NSString *)path{ 
    NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: path]]; 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);         NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"banner.png"];  
    NSError *writeError = nil; 
    [imageData writeToFile:filePath options:NSDataWritingAtomic error:&writeError]; 

    if (writeError) { 
     NSLog(@"Error writing file: %@", writeError); 
    } 
} 
+0

おかげであなたを!私は試してみます:)私は最初のコードのために私をscuse、私はいくつかのソリューションを試して:) – JackTurky

+0

それは私のために働いた、なぜあなたは "アプリケーションのバンドルは読み取り専用です。 –

+2

@ArashZeinoddiniこれはシミュレータとjailbrokeの両方のデバイスで動作します。しかし、通常のiOSデバイスでは、アプリケーションバンドルは読み取り専用です。 – rckoenes

関連する問題