Search code examples
iosnsdata

converting nsMutablestring to nsdata in ios


I'm new to the iOS development I'm trying to convert the append in NSdata but I'm unable to do that conversion I have tried some codes. In my Nsmutable String I have a url link which have the video I'm passing the string form json so now I want to append with the NSdata to display that video url

this is code for the NSmutablesring which pass the url link

-(void)setDataSource:(vedios *)inVideosObj
{

    self.titile.text = inVideosObj.title;

    url =[NSURL URLWithString:inVideosObj.video];
    NSURLRequest *request =[NSURLRequest requestWithURL:url];
    connection =[[NSURLConnection alloc] initWithRequest:request delegate:self];
    self.responseData = [[NSMutableString alloc]init];

}

NSMutablestring appeand coding:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
{

    NSData *mydata =[self.responseData dataUsingEncoding:NSUTF16StringEncoding];

    [self.responseData appendString:data];



}

Solution

  • You are initialising responseData as a NSMutableString. Initialise it as a NSMutableData

    @property (nonatomic, weak) NSMutableData * responseData;
    

    now in

    -(void)setDataSource:(vedios *)inVideosObj
    {
        //Your work
        self.responseData = [NSMutableData alloc] init];
    }
    
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
    {
        [self.responseData appendData: data];
    
    }
    

    then convert this self.responseData to NSString if you want..

    NSString * responseString = [NSString alloc] initWithData: self.responseData encoding: NSUTF16StringEncoding]
    

    Enjoy..!!